@gram-ai/elements 1.18.8 → 1.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/bin/cli.js +144 -0
- package/dist/elements.cjs +103 -88
- package/dist/elements.cjs.map +1 -1
- package/dist/elements.js +29547 -16217
- package/dist/elements.js.map +1 -1
- package/dist/{index-CJRypLIa.js → index-Cb5sxQuN.js} +1429 -641
- package/dist/index-Cb5sxQuN.js.map +1 -0
- package/dist/index-hrhDHFgW.cjs +19 -0
- package/dist/index-hrhDHFgW.cjs.map +1 -0
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.js +1 -1
- package/package.json +9 -13
- package/dist/index-Bj7jPiuy.cjs +0 -17
- package/dist/index-Bj7jPiuy.cjs.map +0 -1
- package/dist/index-CJRypLIa.js.map +0 -1
package/dist/elements.cjs
CHANGED
|
@@ -1,46 +1,88 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
Error message: ${
|
|
3
|
-
Error message: ${
|
|
4
|
-
`;break;case"id":s=
|
|
5
|
-
`)?
|
|
6
|
-
`,
|
|
7
|
-
`&&o++}}return[t,r]}let Pn=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o}={}){let n;super({start(i){n=z0({onEvent:a=>{i.enqueue(a)},onError(a){t==="terminate"?i.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:o})},transform(i){n.feed(i)}})}};const Du=Object.freeze({status:"aborted"});function S(e,t,r){function o(s,l){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:l,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,l);const u=a.prototype,c=Object.keys(u);for(let d=0;d<c.length;d++){const f=c[d];f in s||(s[f]=u[f].bind(s))}}const n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function a(s){var l;const u=r?.Parent?new i:this;o(u,s),(l=u._zod).deferred??(l.deferred=[]);for(const c of u._zod.deferred)c();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}const jm=Symbol("zod_brand");class vr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Wi extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ci={};function De(e){return e&&Object.assign(ci,e),ci}function D0(e){return e}function U0(e){return e}function L0(e){}function Z0(e){throw new Error("Unexpected value in exhaustive check")}function F0(e){}function Uu(e){const t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function j(e,t="|"){return e.map(r=>H(r)).join(t)}function di(e,t){return typeof t=="bigint"?t.toString():t}function Xn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Er(e){return e==null}function Hi(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Am(e,t){const r=(e.toString().split(".")[1]||"").length,o=t.toString();let n=(o.split(".")[1]||"").length;if(n===0&&/\d?e-\d?/.test(o)){const l=o.match(/\d?e-(\d?)/);l?.[1]&&(n=Number.parseInt(l[1]))}const i=r>n?r:n,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}const zd=Symbol("evaluating");function ne(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==zd)return o===void 0&&(o=zd,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function q0(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function cr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){const t={};for(const r of e){const o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function V0(e){return Wt(e._zod.def)}function B0(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function J0(e){const t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{const n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function W0(e=10){const t="abcdefghijklmnopqrstuvwxyz";let r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Ys(e){return JSON.stringify(e)}function Rm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Lu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const zm=Xn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function yr(e){if(Wr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(Wr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Gi(e){return yr(e)?{...e}:Array.isArray(e)?[...e]:e}function H0(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}const G0=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}`)}},pi=new Set(["string","number","symbol"]),Mm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dt(e,t,r){const o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function P(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 K0(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function H(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Dm(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Um={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]},Lm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Zm(e,t){const r=e._zod.def,o=Wt(e._zod.def,{get shape(){const n={};for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(n[i]=r.shape[i])}return cr(this,"shape",n),n},checks:[]});return dt(e,o)}function Fm(e,t){const r=e._zod.def,o=Wt(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete n[i]}return cr(this,"shape",n),n},checks:[]});return dt(e,o)}function qm(e,t){if(!yr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const n=Wt(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return cr(this,"shape",i),i},checks:[]});return dt(e,n)}function Vm(e,t){if(!yr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r={...e._zod.def,get shape(){const o={...e._zod.def.shape,...t};return cr(this,"shape",o),o},checks:e._zod.def.checks};return dt(e,r)}function Bm(e,t){const r=Wt(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t._zod.def.shape};return cr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return dt(e,r)}function Jm(e,t,r){const o=Wt(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=e?new e({type:"optional",innerType:n[a]}):n[a])}else for(const a in n)i[a]=e?new e({type:"optional",innerType:n[a]}):n[a];return cr(this,"shape",i),i},checks:[]});return dt(t,o)}function Wm(e,t,r){const o=Wt(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:n[a]}))}else for(const a in n)i[a]=new e({type:"nonoptional",innerType:n[a]});return cr(this,"shape",i),i},checks:[]});return dt(t,o)}function mr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _t(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function $n(e){return typeof e=="string"?e:e?.message}function ut(e,t,r){const o={...e,path:e.path??[]};if(!e.message){const n=$n(e.inst?._zod.def?.error?.(e))??$n(t?.error?.(e))??$n(r.customError?.(e))??$n(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Ki(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Yi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Hr(...e){const[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function Y0(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Hm(e){const t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Gm(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Q0(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Hm(t+r)}function X0(e){return Gm(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function eI(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function tI(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class rI{constructor(...t){}}const Km=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:Lm,Class:rI,NUMBER_FORMAT_RANGES:Um,aborted:mr,allowsEval:zm,assert:F0,assertEqual:D0,assertIs:L0,assertNever:Z0,assertNotEqual:U0,assignProp:cr,base64ToUint8Array:Hm,base64urlToUint8Array:Q0,cached:Xn,captureStackTrace:Lu,cleanEnum:Y0,cleanRegex:Hi,clone:dt,cloneDef:V0,createTransparentProxy:K0,defineLazy:ne,esc:Ys,escapeRegex:qt,extend:qm,finalizeIssue:ut,floatSafeRemainder:Am,getElementAtPath:B0,getEnumValues:Uu,getLengthableOrigin:Yi,getParsedType:G0,getSizableOrigin:Ki,hexToUint8Array:eI,isObject:Wr,isPlainObject:yr,issue:Hr,joinValues:j,jsonStringifyReplacer:di,merge:Bm,mergeDefs:Wt,normalizeParams:P,nullish:Er,numKeys:H0,objectClone:q0,omit:Fm,optionalKeys:Dm,partial:Jm,pick:Zm,prefixIssues:_t,primitiveTypes:Mm,promiseAllObject:J0,propertyKeyTypes:pi,randomString:W0,required:Wm,safeExtend:Vm,shallowClone:Gi,slugify:Rm,stringifyPrimitive:H,uint8ArrayToBase64:Gm,uint8ArrayToBase64url:X0,uint8ArrayToHex:tI,unwrapMessage:$n},Symbol.toStringTag,{value:"Module"})),Ym=(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,di,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zu=S("$ZodError",Ym),nt=S("$ZodError",Ym,{Parent:Error});function Fu(e,t=r=>r.message){const r={},o=[];for(const n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function qu(e,t=r=>r.message){const r={_errors:[]},o=n=>{for(const i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let a=r,s=0;for(;s<i.path.length;){const l=i.path[s];s===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(i))):a[l]=a[l]||{_errors:[]},a=a[l],s++}}};return o(e),r}function Qm(e,t=r=>r.message){const r={errors:[]},o=(n,i=[])=>{var a,s;for(const l of n.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(u=>o({issues:u},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{const u=[...i,...l.path];if(u.length===0){r.errors.push(t(l));continue}let c=r,d=0;for(;d<u.length;){const f=u[d],p=d===u.length-1;typeof f=="string"?(c.properties??(c.properties={}),(a=c.properties)[f]??(a[f]={errors:[]}),c=c.properties[f]):(c.items??(c.items=[]),(s=c.items)[f]??(s[f]={errors:[]}),c=c.items[f]),p&&c.errors.push(t(l)),d++}}};return o(e),r}function Xm(e){const t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(const o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function eh(e){const t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(const o of r)t.push(`✖ ${o.message}`),o.path?.length&&t.push(` → at ${Xm(o.path)}`);return t.join(`
|
|
8
|
-
`)}const eo=e=>(t,r,o,n)=>{const i=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new vr;if(a.issues.length){const s=new(n?.Err??e)(a.issues.map(l=>ut(l,i,De())));throw Lu(s,n?.callee),s}return a.value},Qs=eo(nt),to=e=>async(t,r,o,n)=>{const i=o?Object.assign(o,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const s=new(n?.Err??e)(a.issues.map(l=>ut(l,i,De())));throw Lu(s,n?.callee),s}return a.value},Xs=to(nt),ro=e=>(t,r,o)=>{const n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new vr;return i.issues.length?{success:!1,error:new(e??Zu)(i.issues.map(a=>ut(a,n,De())))}:{success:!0,data:i.value}},th=ro(nt),no=e=>async(t,r,o)=>{const n=o?Object.assign(o,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>ut(a,n,De())))}:{success:!0,data:i.value}},rh=no(nt),Vu=e=>(t,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return eo(e)(t,r,n)},nI=Vu(nt),Bu=e=>(t,r,o)=>eo(e)(t,r,o),oI=Bu(nt),Ju=e=>async(t,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return to(e)(t,r,n)},iI=Ju(nt),Wu=e=>async(t,r,o)=>to(e)(t,r,o),aI=Wu(nt),Hu=e=>(t,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ro(e)(t,r,n)},sI=Hu(nt),Gu=e=>(t,r,o)=>ro(e)(t,r,o),uI=Gu(nt),Ku=e=>async(t,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return no(e)(t,r,n)},lI=Ku(nt),Yu=e=>async(t,r,o)=>no(e)(t,r,o),cI=Yu(nt),nh=/^[cC][^\s-]{8,}$/,oh=/^[0-9a-z]+$/,ih=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ah=/^[0-9a-vA-V]{20}$/,sh=/^[A-Za-z0-9]{27}$/,uh=/^[a-zA-Z0-9_-]{21}$/,lh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dI=/^[-+]?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)?)??$/,ch=/^([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})$/,Gr=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)$/,pI=Gr(4),fI=Gr(6),mI=Gr(7),dh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hI=/^[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])?)*$/,gI=/^(([^<>()\[\]\\.,;:\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,}))$/,ph=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,vI=ph,yI=/^[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])?)*$/,bI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fh(){return new RegExp(bI,"u")}const mh=/^(?:(?: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])$/,hh=/^(([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}|:))$/,gh=e=>{const t=qt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},vh=/^((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])$/,yh=/^(([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])$/,bh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qu=/^[A-Za-z0-9_-]*$/,_h=/^(?=.{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])?)*\.?$/,wh=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,xh=/^\+(?:[0-9]){6,14}[0-9]$/,$h="(?:(?:\\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])))",Sh=new RegExp(`^${$h}$`);function Ih(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 kh(e){return new RegExp(`^${Ih(e)}$`)}function Eh(e){const t=Ih({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${t}(?:${r.join("|")})`;return new RegExp(`^${$h}T(?:${o})$`)}const Th=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Oh=/^-?\d+n?$/,Nh=/^-?\d+$/,Ph=/^-?\d+(?:\.\d+)?/,Ch=/^(?:true|false)$/i,jh=/^null$/i,Ah=/^undefined$/i,Rh=/^[^A-Z]*$/,zh=/^[^a-z]*$/,Mh=/^[0-9a-fA-F]*$/;function oo(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function io(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const _I=/^[0-9a-fA-F]{32}$/,wI=oo(22,"=="),xI=io(22),$I=/^[0-9a-fA-F]{40}$/,SI=oo(27,"="),II=io(27),kI=/^[0-9a-fA-F]{64}$/,EI=oo(43,"="),TI=io(43),OI=/^[0-9a-fA-F]{96}$/,NI=oo(64,""),PI=io(64),CI=/^[0-9a-fA-F]{128}$/,jI=oo(86,"=="),AI=io(86),Xu=Object.freeze(Object.defineProperty({__proto__:null,base64:bh,base64url:Qu,bigint:Oh,boolean:Ch,browserEmail:yI,cidrv4:vh,cidrv6:yh,cuid:nh,cuid2:oh,date:Sh,datetime:Eh,domain:wh,duration:lh,e164:xh,email:dh,emoji:fh,extendedDuration:dI,guid:ch,hex:Mh,hostname:_h,html5Email:hI,idnEmail:vI,integer:Nh,ipv4:mh,ipv6:hh,ksuid:sh,lowercase:Rh,mac:gh,md5_base64:wI,md5_base64url:xI,md5_hex:_I,nanoid:uh,null:jh,number:Ph,rfc5322Email:gI,sha1_base64:SI,sha1_base64url:II,sha1_hex:$I,sha256_base64:EI,sha256_base64url:TI,sha256_hex:kI,sha384_base64:NI,sha384_base64url:PI,sha384_hex:OI,sha512_base64:jI,sha512_base64url:AI,sha512_hex:CI,string:Th,time:kh,ulid:ih,undefined:Ah,unicodeEmail:ph,uppercase:zh,uuid:Gr,uuid4:pI,uuid6:fI,uuid7:mI,xid:ah},Symbol.toStringTag,{value:"Module"})),Se=S("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Dh={number:"number",bigint:"bigint",object:"date"},el=S("$ZodCheckLessThan",(e,t)=>{Se.init(e,t);const r=Dh[typeof t.value];e._zod.onattach.push(o=>{const n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tl=S("$ZodCheckGreaterThan",(e,t)=>{Se.init(e,t);const r=Dh[typeof t.value];e._zod.onattach.push(o=>{const n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Uh=S("$ZodCheckMultipleOf",(e,t)=>{Se.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Am(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Lh=S("$ZodCheckNumberFormat",(e,t)=>{Se.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Um[t.format];e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,s.minimum=n,s.maximum=i,r&&(s.pattern=Nh)}),e._zod.check=a=>{const s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort});return}}s<n&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inst:e})}}),Zh=S("$ZodCheckBigIntFormat",(e,t)=>{Se.init(e,t);const[r,o]=Lm[t.format];e._zod.onattach.push(n=>{const i=n._zod.bag;i.format=t.format,i.minimum=r,i.maximum=o}),e._zod.check=n=>{const i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inst:e})}}),Fh=S("$ZodCheckMaxSize",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{const n=o.value;n.size<=t.maximum||o.issues.push({origin:Ki(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),qh=S("$ZodCheckMinSize",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{const n=o.value;n.size>=t.minimum||o.issues.push({origin:Ki(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Vh=S("$ZodCheckSizeEquals",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=o=>{const n=o.value,i=n.size;if(i===t.size)return;const a=i>t.size;o.issues.push({origin:Ki(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Bh=S("$ZodCheckMaxLength",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{const n=o.value;if(n.length<=t.maximum)return;const a=Yi(n);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Jh=S("$ZodCheckMinLength",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{const n=o.value;if(n.length>=t.minimum)return;const a=Yi(n);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Wh=S("$ZodCheckLengthEquals",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=o=>{const n=o.value;return!Er(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{const n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{const n=o.value,i=n.length;if(i===t.length)return;const a=Yi(n),s=i>t.length;o.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ao=S("$ZodCheckStringFormat",(e,t)=>{var r,o;Se.init(e,t),e._zod.onattach.push(n=>{const i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Hh=S("$ZodCheckRegex",(e,t)=>{ao.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Gh=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Rh),ao.init(e,t)}),Kh=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zh),ao.init(e,t)}),Yh=S("$ZodCheckIncludes",(e,t)=>{Se.init(e,t);const r=qt(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Qh=S("$ZodCheckStartsWith",(e,t)=>{Se.init(e,t);const r=new RegExp(`^${qt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{const n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Xh=S("$ZodCheckEndsWith",(e,t)=>{Se.init(e,t);const r=new RegExp(`.*${qt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{const n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function Md(e,t,r){e.issues.length&&t.issues.push(..._t(r,e.issues))}const eg=S("$ZodCheckProperty",(e,t)=>{Se.init(e,t),e._zod.check=r=>{const o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>Md(n,r,t.property));Md(o,r,t.property)}}),tg=S("$ZodCheckMimeType",(e,t)=>{Se.init(e,t);const r=new Set(t.mime);e._zod.onattach.push(o=>{o._zod.bag.mime=t.mime}),e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),rg=S("$ZodCheckOverwrite",(e,t)=>{Se.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class ng{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 o=t.split(`
|
|
9
|
-
`).filter(a=>a),
|
|
10
|
-
`))}}const og={major:4,minor:2,patch:1},X=S("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=og;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const n of o)for(const i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const n=(a,s,l)=>{let u=mr(a),c;for(const d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(u)continue;const f=a.issues.length,p=d._zod.check(a);if(p instanceof Promise&&l?.async===!1)throw new vr;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==f&&(u||(u=mr(a,f)))});else{if(a.issues.length===f)continue;u||(u=mr(a,f))}}return c?c.then(()=>a):a},i=(a,s,l)=>{if(mr(a))return a.aborted=!0,a;const u=n(s,o,l);if(u instanceof Promise){if(l.async===!1)throw new vr;return u.then(c=>e._zod.parse(c,l))}return e._zod.parse(u,l)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){const u=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return u instanceof Promise?u.then(c=>i(c,a,s)):i(u,a,s)}const l=e._zod.parse(a,s);if(l instanceof Promise){if(s.async===!1)throw new vr;return l.then(u=>n(u,o,s))}return n(l,o,s)}}e["~standard"]={validate:n=>{try{const i=th(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return rh(e,n).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),so=S("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Th(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ge=S("$ZodStringFormat",(e,t)=>{ao.init(e,t),so.init(e,t)}),ig=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ch),ge.init(e,t)}),ag=S("$ZodUUID",(e,t)=>{if(t.version){const o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gr(o))}else t.pattern??(t.pattern=Gr());ge.init(e,t)}),sg=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=dh),ge.init(e,t)}),ug=S("$ZodURL",(e,t)=>{ge.init(e,t),e._zod.check=r=>{try{const o=r.value.trim(),n=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),lg=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=fh()),ge.init(e,t)}),cg=S("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=uh),ge.init(e,t)}),dg=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=nh),ge.init(e,t)}),pg=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=oh),ge.init(e,t)}),fg=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ih),ge.init(e,t)}),mg=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ah),ge.init(e,t)}),hg=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=sh),ge.init(e,t)}),gg=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Eh(t)),ge.init(e,t)}),vg=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Sh),ge.init(e,t)}),yg=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=kh(t)),ge.init(e,t)}),bg=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=lh),ge.init(e,t)}),_g=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=mh),ge.init(e,t),e._zod.bag.format="ipv4"}),wg=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=hh),ge.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),xg=S("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=gh(t.delimiter)),ge.init(e,t),e._zod.bag.format="mac"}),$g=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=vh),ge.init(e,t)}),Sg=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=yh),ge.init(e,t),e._zod.check=r=>{const o=r.value.split("/");try{if(o.length!==2)throw new Error;const[n,i]=o;if(!i)throw new Error;const a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function rl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Ig=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=bh),ge.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{rl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function kg(e){if(!Qu.test(e))return!1;const t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return rl(r)}const Eg=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Qu),ge.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{kg(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Tg=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xh),ge.init(e,t)});function Og(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[o]=r;if(!o)return!1;const n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}const Ng=S("$ZodJWT",(e,t)=>{ge.init(e,t),e._zod.check=r=>{Og(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Pg=S("$ZodCustomStringFormat",(e,t)=>{ge.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),nl=S("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ph,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Cg=S("$ZodNumberFormat",(e,t)=>{Lh.init(e,t),nl.init(e,t)}),ol=S("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=Ch,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),il=S("$ZodBigInt",(e,t)=>{X.init(e,t),e._zod.pattern=Oh,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),jg=S("$ZodBigIntFormat",(e,t)=>{Zh.init(e,t),il.init(e,t)}),Ag=S("$ZodSymbol",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),Rg=S("$ZodUndefined",(e,t)=>{X.init(e,t),e._zod.pattern=Ah,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,o)=>{const n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),zg=S("$ZodNull",(e,t)=>{X.init(e,t),e._zod.pattern=jh,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),Mg=S("$ZodAny",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),Dg=S("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),Ug=S("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),Lg=S("$ZodVoid",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),Zg=S("$ZodDate",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}const n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function Dd(e,t,r){e.issues.length&&t.issues.push(..._t(r,e.issues)),t.value[r]=e.value}const Fg=S("$ZodArray",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);const i=[];for(let a=0;a<n.length;a++){const s=n[a],l=t.element._zod.run({value:s,issues:[]},o);l instanceof Promise?i.push(l.then(u=>Dd(u,r,a))):Dd(l,r,a)}return i.length?Promise.all(i).then(()=>r):r}});function fi(e,t,r,o){e.issues.length&&t.issues.push(..._t(r,e.issues)),e.value===void 0?r in o&&(t.value[r]=void 0):t.value[r]=e.value}function qg(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const r=Dm(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Vg(e,t,r,o,n,i){const a=[],s=n.keySet,l=n.catchall._zod,u=l.def.type;for(const c in t){if(s.has(c))continue;if(u==="never"){a.push(c);continue}const d=l.run({value:t[c],issues:[]},o);d instanceof Promise?e.push(d.then(f=>fi(f,r,c,t))):fi(d,r,c,t)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}const Bg=S("$ZodObject",(e,t)=>{if(X.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const s=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...s};return Object.defineProperty(t,"shape",{value:l}),l}})}const o=Xn(()=>qg(t));ne(e._zod,"propValues",()=>{const s=t.shape,l={};for(const u in s){const c=s[u]._zod;if(c.values){l[u]??(l[u]=new Set);for(const d of c.values)l[u].add(d)}}return l});const n=Wr,i=t.catchall;let a;e._zod.parse=(s,l)=>{a??(a=o.value);const u=s.value;if(!n(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};const c=[],d=a.shape;for(const f of a.keys){const g=d[f]._zod.run({value:u[f],issues:[]},l);g instanceof Promise?c.push(g.then(h=>fi(h,s,f,u))):fi(g,s,f,u)}return i?Vg(c,u,s,l,o.value,e):c.length?Promise.all(c).then(()=>s):s}}),Jg=S("$ZodObjectJIT",(e,t)=>{Bg.init(e,t);const r=e._zod.parse,o=Xn(()=>qg(t)),n=f=>{const p=new ng(["shape","payload","ctx"]),g=o.value,h=$=>{const v=Ys($);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");const b=Object.create(null);let y=0;for(const $ of g.keys)b[$]=`key_${y++}`;p.write("const newResult = {};");for(const $ of g.keys){const v=b[$],k=Ys($);p.write(`const ${v} = ${h($)};`),p.write(`
|
|
11
|
-
if (${
|
|
12
|
-
payload.issues = payload.issues.concat(${
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("react/jsx-runtime"),_=require("./index-hrhDHFgW.cjs"),$=require("react"),Wr=require("zustand"),$n=require("motion/react"),_A=require("motion/react-m"),gy=require("zustand/shallow"),vy=require("react-dom"),wA=require("remark-gfm"),xA=require("shiki");function pd(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 w=pd($),En=pd(_A),yy=pd(vy);function SA({tools:e}){return h.jsx(h.Fragment,{children:Object.entries(e).map(([,t])=>t({}))})}var by="vercel.ai.error",IA=Symbol.for(by),_y,kA=class wy extends Error{constructor({name:t,message:n,cause:i}){super(n),this[_y]=!0,this.name=t,this.cause=i}static isInstance(t){return wy.hasMarker(t,by)}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}};_y=IA;var ue=kA,xy="AI_APICallError",Sy=`vercel.ai.error.${xy}`,EA=Symbol.for(Sy),Iy,ut=class extends ue{constructor({message:t,url:n,requestBodyValues:i,statusCode:r,responseHeaders:o,responseBody:a,cause:s,isRetryable:u=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:xy,message:t,cause:s}),this[Iy]=!0,this.url=n,this.requestBodyValues=i,this.statusCode=r,this.responseHeaders=o,this.responseBody=a,this.isRetryable=u,this.data=l}static isInstance(t){return ue.hasMarker(t,Sy)}};Iy=EA;var ky="AI_EmptyResponseBodyError",Ey=`vercel.ai.error.${ky}`,TA=Symbol.for(Ey),Ty,$A=class extends ue{constructor({message:t="Empty response body"}={}){super({name:ky,message:t}),this[Ty]=!0}static isInstance(t){return ue.hasMarker(t,Ey)}};Ty=TA;function ci(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var $y="AI_InvalidArgumentError",Cy=`vercel.ai.error.${$y}`,CA=Symbol.for(Cy),Ay,js=class extends ue{constructor({message:t,cause:n,argument:i}){super({name:$y,message:t,cause:n}),this[Ay]=!0,this.argument=i}static isInstance(t){return ue.hasMarker(t,Cy)}};Ay=CA;var Py="AI_InvalidPromptError",Ry=`vercel.ai.error.${Py}`,AA=Symbol.for(Ry),Oy,Pr=class extends ue{constructor({prompt:t,message:n,cause:i}){super({name:Py,message:`Invalid prompt: ${n}`,cause:i}),this[Oy]=!0,this.prompt=t}static isInstance(t){return ue.hasMarker(t,Ry)}};Oy=AA;var Ny="AI_JSONParseError",jy=`vercel.ai.error.${Ny}`,PA=Symbol.for(jy),My,Gr=class extends ue{constructor({text:t,cause:n}){super({name:Ny,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
+
Error message: ${ci(n)}`,cause:n}),this[My]=!0,this.text=t}static isInstance(t){return ue.hasMarker(t,jy)}};My=PA;var zy="AI_NoSuchModelError",Dy=`vercel.ai.error.${zy}`,RA=Symbol.for(Dy),Uy,OA=class extends ue{constructor({errorName:e=zy,modelId:t,modelType:n,message:i=`No such ${n}: ${t}`}){super({name:e,message:i}),this[Uy]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ue.hasMarker(e,Dy)}};Uy=RA;var Ly="AI_TypeValidationError",Fy=`vercel.ai.error.${Ly}`,NA=Symbol.for(Fy),By,jA=class uc extends ue{constructor({value:t,cause:n}){super({name:Ly,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
3
|
+
Error message: ${ci(n)}`,cause:n}),this[By]=!0,this.value=t}static isInstance(t){return ue.hasMarker(t,Fy)}static wrap({value:t,cause:n}){return uc.isInstance(n)&&n.value===t?n:new uc({value:t,cause:n})}};By=NA;var Cn=jA;let Nh=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 cu(e){}function MA(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=cu,onError:n=cu,onRetry:i=cu,onComment:r}=e;let o="",a=!0,s,u="",l="";function c(m){const y=a?m.replace(/^\xEF\xBB\xBF/,""):m,[v,x]=zA(`${o}${y}`);for(const S of v)d(S);o=x,a=!1}function d(m){if(m===""){p();return}if(m.startsWith(":")){r&&r(m.slice(m.startsWith(": ")?2:1));return}const y=m.indexOf(":");if(y!==-1){const v=m.slice(0,y),x=m[y+1]===" "?2:1,S=m.slice(y+x);f(v,S,m);return}f(m,"",m)}function f(m,y,v){switch(m){case"event":l=y;break;case"data":u=`${u}${y}
|
|
4
|
+
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?i(parseInt(y,10)):n(new Nh(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:n(new Nh(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:y,line:v}));break}}function p(){u.length>0&&t({id:s,event:l||void 0,data:u.endsWith(`
|
|
5
|
+
`)?u.slice(0,-1):u}),s=void 0,u="",l=""}function g(m={}){o&&m.consume&&d(o),a=!0,s=void 0,u="",l="",o=""}return{feed:c,reset:g}}function zA(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
6
|
+
`,i);let a=-1;if(r!==-1&&o!==-1?a=Math.min(r,o):r!==-1?r===e.length-1?a=-1:a=r:o!==-1&&(a=o),a===-1){n=e.slice(i);break}else{const s=e.slice(i,a);t.push(s),i=a+1,e[i-1]==="\r"&&e[i]===`
|
|
7
|
+
`&&i++}}return[t,n]}let Bi=class extends TransformStream{constructor({onError:t,onRetry:n,onComment:i}={}){let r;super({start(o){r=MA({onEvent:a=>{o.enqueue(a)},onError(a){t==="terminate"?o.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:i})},transform(o){r.feed(o)}})}};const fd=Object.freeze({status:"aborted"});function R(e,t,n){function i(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);const l=a.prototype,c=Object.keys(l);for(let d=0;d<c.length;d++){const f=c[d];f in s||(s[f]=l[f].bind(s))}}const r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function a(s){var u;const l=n?.Parent?new o:this;i(l,s),(u=l._zod).deferred??(u.deferred=[]);for(const c of l._zod.deferred)c();return l}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}const Zy=Symbol("zod_brand");class fr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ms extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Wa={};function tt(e){return e&&Object.assign(Wa,e),Wa}function DA(e){return e}function UA(e){return e}function LA(e){}function FA(e){throw new Error("Unexpected value in exhaustive check")}function BA(e){}function hd(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=>oe(n)).join(t)}function Ga(e,t){return typeof t=="bigint"?t.toString():t}function vo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Sr(e){return e==null}function zs(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function qy(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 u=i.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const o=n>r?n:r,a=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return a%s/10**o}const jh=Symbol("evaluating");function ge(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==jh)return i===void 0&&(i=jh,i=n()),i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ZA(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function tr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Nn(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function qA(e){return Nn(e._zod.def)}function VA(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function HA(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 JA(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 cc(e){return JSON.stringify(e)}function Vy(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const md="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Hy=vo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function mr(e){if(Kr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Kr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ds(e){return mr(e)?{...e}:Array.isArray(e)?[...e]:e}function WA(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const GA=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}`)}},Ka=new Set(["string","number","symbol"]),Jy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function An(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function M(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 KA(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 oe(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Wy(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Gy={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]},Ky={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Yy(e,t){const n=e._zod.def,i=Nn(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 tr(this,"shape",r),r},checks:[]});return Bt(e,i)}function Qy(e,t){const n=e._zod.def,i=Nn(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 tr(this,"shape",r),r},checks:[]});return Bt(e,i)}function Xy(e,t){if(!mr(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=Nn(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return tr(this,"shape",o),o},checks:[]});return Bt(e,r)}function eb(e,t){if(!mr(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 tr(this,"shape",i),i},checks:e._zod.def.checks};return Bt(e,n)}function tb(e,t){const n=Nn(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return tr(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Bt(e,n)}function nb(e,t,n){const i=Nn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(o[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)o[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return tr(this,"shape",o),o},checks:[]});return Bt(t,i)}function rb(e,t,n){const i=Nn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const a in n){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(o[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)o[a]=new e({type:"nonoptional",innerType:r[a]});return tr(this,"shape",o),o},checks:[]});return Bt(t,i)}function ur(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 Kt(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Ci(e){return typeof e=="string"?e:e?.message}function Ut(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const r=Ci(e.inst?._zod.def?.error?.(e))??Ci(t?.error?.(e))??Ci(n.customError?.(e))??Ci(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Us(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ls(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Yr(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function YA(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function ib(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 ob(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function QA(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return ib(t+n)}function XA(e){return ob(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function eP(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 tP(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class nP{constructor(...t){}}const ab=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:Ky,Class:nP,NUMBER_FORMAT_RANGES:Gy,aborted:ur,allowsEval:Hy,assert:BA,assertEqual:DA,assertIs:LA,assertNever:FA,assertNotEqual:UA,assignProp:tr,base64ToUint8Array:ib,base64urlToUint8Array:QA,cached:vo,captureStackTrace:md,cleanEnum:YA,cleanRegex:zs,clone:Bt,cloneDef:qA,createTransparentProxy:KA,defineLazy:ge,esc:cc,escapeRegex:An,extend:Xy,finalizeIssue:Ut,floatSafeRemainder:qy,getElementAtPath:VA,getEnumValues:hd,getLengthableOrigin:Ls,getParsedType:GA,getSizableOrigin:Us,hexToUint8Array:eP,isObject:Kr,isPlainObject:mr,issue:Yr,joinValues:q,jsonStringifyReplacer:Ga,merge:tb,mergeDefs:Nn,normalizeParams:M,nullish:Sr,numKeys:WA,objectClone:ZA,omit:Qy,optionalKeys:Wy,partial:nb,pick:Yy,prefixIssues:Kt,primitiveTypes:Jy,promiseAllObject:HA,propertyKeyTypes:Ka,randomString:JA,required:rb,safeExtend:eb,shallowClone:Ds,slugify:Vy,stringifyPrimitive:oe,uint8ArrayToBase64:ob,uint8ArrayToBase64url:XA,uint8ArrayToHex:tP,unwrapMessage:Ci},Symbol.toStringTag,{value:"Module"})),sb=(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,Ga,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},gd=R("$ZodError",sb),At=R("$ZodError",sb,{Parent:Error});function vd(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 yd(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(a=>i({issues:a}));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 a=n,s=0;for(;s<o.path.length;){const u=o.path[s];s===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(t(o))):a[u]=a[u]||{_errors:[]},a=a[u],s++}}};return i(e),n}function lb(e,t=n=>n.message){const n={errors:[]},i=(r,o=[])=>{var a,s;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>i({issues:l},u.path));else if(u.code==="invalid_key")i({issues:u.issues},u.path);else if(u.code==="invalid_element")i({issues:u.issues},u.path);else{const l=[...o,...u.path];if(l.length===0){n.errors.push(t(u));continue}let c=n,d=0;for(;d<l.length;){const f=l[d],p=d===l.length-1;typeof f=="string"?(c.properties??(c.properties={}),(a=c.properties)[f]??(a[f]={errors:[]}),c=c.properties[f]):(c.items??(c.items=[]),(s=c.items)[f]??(s[f]={errors:[]}),c=c.items[f]),p&&c.errors.push(t(u)),d++}}};return i(e),n}function ub(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 cb(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 ${ub(i.path)}`);return t.join(`
|
|
8
|
+
`)}const yo=e=>(t,n,i,r)=>{const o=i?Object.assign(i,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new fr;if(a.issues.length){const s=new(r?.Err??e)(a.issues.map(u=>Ut(u,o,tt())));throw md(s,r?.callee),s}return a.value},dc=yo(At),bo=e=>async(t,n,i,r)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const s=new(r?.Err??e)(a.issues.map(u=>Ut(u,o,tt())));throw md(s,r?.callee),s}return a.value},pc=bo(At),_o=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 fr;return o.issues.length?{success:!1,error:new(e??gd)(o.issues.map(a=>Ut(a,r,tt())))}:{success:!0,data:o.value}},db=_o(At),wo=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(a=>Ut(a,r,tt())))}:{success:!0,data:o.value}},pb=wo(At),bd=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return yo(e)(t,n,r)},rP=bd(At),_d=e=>(t,n,i)=>yo(e)(t,n,i),iP=_d(At),wd=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return bo(e)(t,n,r)},oP=wd(At),xd=e=>async(t,n,i)=>bo(e)(t,n,i),aP=xd(At),Sd=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return _o(e)(t,n,r)},sP=Sd(At),Id=e=>(t,n,i)=>_o(e)(t,n,i),lP=Id(At),kd=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return wo(e)(t,n,r)},uP=kd(At),Ed=e=>async(t,n,i)=>wo(e)(t,n,i),cP=Ed(At),fb=/^[cC][^\s-]{8,}$/,hb=/^[0-9a-z]+$/,mb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gb=/^[0-9a-vA-V]{20}$/,vb=/^[A-Za-z0-9]{27}$/,yb=/^[a-zA-Z0-9_-]{21}$/,bb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dP=/^[-+]?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)?)??$/,_b=/^([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})$/,Qr=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)$/,pP=Qr(4),fP=Qr(6),hP=Qr(7),wb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mP=/^[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])?)*$/,gP=/^(([^<>()\[\]\\.,;:\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,}))$/,xb=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,vP=xb,yP=/^[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])?)*$/,bP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Sb(){return new RegExp(bP,"u")}const Ib=/^(?:(?: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])$/,kb=/^(([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}|:))$/,Eb=e=>{const t=An(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Tb=/^((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])$/,$b=/^(([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])$/,Cb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Td=/^[A-Za-z0-9_-]*$/,Ab=/^(?=.{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])?)*\.?$/,Pb=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Rb=/^\+(?:[0-9]){6,14}[0-9]$/,Ob="(?:(?:\\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])))",Nb=new RegExp(`^${Ob}$`);function jb(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 Mb(e){return new RegExp(`^${jb(e)}$`)}function zb(e){const t=jb({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(`^${Ob}T(?:${i})$`)}const Db=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ub=/^-?\d+n?$/,Lb=/^-?\d+$/,Fb=/^-?\d+(?:\.\d+)?/,Bb=/^(?:true|false)$/i,Zb=/^null$/i,qb=/^undefined$/i,Vb=/^[^A-Z]*$/,Hb=/^[^a-z]*$/,Jb=/^[0-9a-fA-F]*$/;function xo(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function So(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const _P=/^[0-9a-fA-F]{32}$/,wP=xo(22,"=="),xP=So(22),SP=/^[0-9a-fA-F]{40}$/,IP=xo(27,"="),kP=So(27),EP=/^[0-9a-fA-F]{64}$/,TP=xo(43,"="),$P=So(43),CP=/^[0-9a-fA-F]{96}$/,AP=xo(64,""),PP=So(64),RP=/^[0-9a-fA-F]{128}$/,OP=xo(86,"=="),NP=So(86),$d=Object.freeze(Object.defineProperty({__proto__:null,base64:Cb,base64url:Td,bigint:Ub,boolean:Bb,browserEmail:yP,cidrv4:Tb,cidrv6:$b,cuid:fb,cuid2:hb,date:Nb,datetime:zb,domain:Pb,duration:bb,e164:Rb,email:wb,emoji:Sb,extendedDuration:dP,guid:_b,hex:Jb,hostname:Ab,html5Email:mP,idnEmail:vP,integer:Lb,ipv4:Ib,ipv6:kb,ksuid:vb,lowercase:Vb,mac:Eb,md5_base64:wP,md5_base64url:xP,md5_hex:_P,nanoid:yb,null:Zb,number:Fb,rfc5322Email:gP,sha1_base64:IP,sha1_base64url:kP,sha1_hex:SP,sha256_base64:TP,sha256_base64url:$P,sha256_hex:EP,sha384_base64:AP,sha384_base64url:PP,sha384_hex:CP,sha512_base64:OP,sha512_base64url:NP,sha512_hex:RP,string:Db,time:Mb,ulid:mb,undefined:qb,unicodeEmail:xb,uppercase:Hb,uuid:Qr,uuid4:pP,uuid6:fP,uuid7:hP,xid:gb},Symbol.toStringTag,{value:"Module"})),De=R("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Wb={number:"number",bigint:"bigint",object:"date"},Cd=R("$ZodCheckLessThan",(e,t)=>{De.init(e,t);const n=Wb[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})}}),Ad=R("$ZodCheckGreaterThan",(e,t)=>{De.init(e,t);const n=Wb[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})}}),Gb=R("$ZodCheckMultipleOf",(e,t)=>{De.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):qy(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})}}),Kb=R("$ZodCheckNumberFormat",(e,t)=>{De.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[r,o]=Gy[t.format];e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o,n&&(s.pattern=Lb)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort}):a.issues.push({input:s,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}}s<r&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),Yb=R("$ZodCheckBigIntFormat",(e,t)=>{De.init(e,t);const[n,i]=Ky[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})}}),Qb=R("$ZodCheckMaxSize",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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:Us(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xb=R("$ZodCheckMinSize",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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:Us(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),e_=R("$ZodCheckSizeEquals",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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 a=o>t.size;i.issues.push({origin:Us(r),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),t_=R("$ZodCheckMaxLength",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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 a=Ls(r);i.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),n_=R("$ZodCheckMinLength",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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 a=Ls(r);i.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),r_=R("$ZodCheckLengthEquals",(e,t)=>{var n;De.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Sr(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 a=Ls(r),s=o>t.length;i.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),Io=R("$ZodCheckStringFormat",(e,t)=>{var n,i;De.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=()=>{})}),i_=R("$ZodCheckRegex",(e,t)=>{Io.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})}}),o_=R("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Vb),Io.init(e,t)}),a_=R("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Hb),Io.init(e,t)}),s_=R("$ZodCheckIncludes",(e,t)=>{De.init(e,t);const n=An(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})}}),l_=R("$ZodCheckStartsWith",(e,t)=>{De.init(e,t);const n=new RegExp(`^${An(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})}}),u_=R("$ZodCheckEndsWith",(e,t)=>{De.init(e,t);const n=new RegExp(`.*${An(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 Mh(e,t,n){e.issues.length&&t.issues.push(...Kt(n,e.issues))}const c_=R("$ZodCheckProperty",(e,t)=>{De.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=>Mh(r,n,t.property));Mh(i,n,t.property)}}),d_=R("$ZodCheckMimeType",(e,t)=>{De.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})}}),p_=R("$ZodCheckOverwrite",(e,t)=>{De.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class f_{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(a=>a),r=Math.min(...i.map(a=>a.length-a.trimStart().length)),o=i.map(a=>a.slice(r)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,r.join(`
|
|
10
|
+
`))}}const h_={major:4,minor:2,patch:1},ce=R("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=h_;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=(a,s,u)=>{let l=ur(a),c;for(const d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(l)continue;const f=a.issues.length,p=d._zod.check(a);if(p instanceof Promise&&u?.async===!1)throw new fr;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==f&&(l||(l=ur(a,f)))});else{if(a.issues.length===f)continue;l||(l=ur(a,f))}}return c?c.then(()=>a):a},o=(a,s,u)=>{if(ur(a))return a.aborted=!0,a;const l=r(s,i,u);if(l instanceof Promise){if(u.async===!1)throw new fr;return l.then(c=>e._zod.parse(c,u))}return e._zod.parse(l,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return l instanceof Promise?l.then(c=>o(c,a,s)):o(l,a,s)}const u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new fr;return u.then(l=>r(l,i,s))}return r(u,i,s)}}e["~standard"]={validate:r=>{try{const o=db(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return pb(e,r).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),ko=R("$ZodString",(e,t)=>{ce.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Db(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}}),Ce=R("$ZodStringFormat",(e,t)=>{Io.init(e,t),ko.init(e,t)}),m_=R("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_b),Ce.init(e,t)}),g_=R("$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=Qr(i))}else t.pattern??(t.pattern=Qr());Ce.init(e,t)}),v_=R("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=wb),Ce.init(e,t)}),y_=R("$ZodURL",(e,t)=>{Ce.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})}}}),b_=R("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Sb()),Ce.init(e,t)}),__=R("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=yb),Ce.init(e,t)}),w_=R("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=fb),Ce.init(e,t)}),x_=R("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=hb),Ce.init(e,t)}),S_=R("$ZodULID",(e,t)=>{t.pattern??(t.pattern=mb),Ce.init(e,t)}),I_=R("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gb),Ce.init(e,t)}),k_=R("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=vb),Ce.init(e,t)}),E_=R("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=zb(t)),Ce.init(e,t)}),T_=R("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Nb),Ce.init(e,t)}),$_=R("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Mb(t)),Ce.init(e,t)}),C_=R("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bb),Ce.init(e,t)}),A_=R("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ib),Ce.init(e,t),e._zod.bag.format="ipv4"}),P_=R("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=kb),Ce.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})}}}),R_=R("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Eb(t.delimiter)),Ce.init(e,t),e._zod.bag.format="mac"}),O_=R("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Tb),Ce.init(e,t)}),N_=R("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=$b),Ce.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 a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>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 Pd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const j_=R("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Cb),Ce.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Pd(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function M_(e){if(!Td.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Pd(n)}const z_=R("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Td),Ce.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{M_(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),D_=R("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Rb),Ce.init(e,t)});function U_(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 L_=R("$ZodJWT",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{U_(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),F_=R("$ZodCustomStringFormat",(e,t)=>{Ce.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})}}),Rd=R("$ZodNumber",(e,t)=>{ce.init(e,t),e._zod.pattern=e._zod.bag.pattern??Fb,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}}),B_=R("$ZodNumberFormat",(e,t)=>{Kb.init(e,t),Rd.init(e,t)}),Od=R("$ZodBoolean",(e,t)=>{ce.init(e,t),e._zod.pattern=Bb,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}}),Nd=R("$ZodBigInt",(e,t)=>{ce.init(e,t),e._zod.pattern=Ub,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}}),Z_=R("$ZodBigIntFormat",(e,t)=>{Yb.init(e,t),Nd.init(e,t)}),q_=R("$ZodSymbol",(e,t)=>{ce.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}}),V_=R("$ZodUndefined",(e,t)=>{ce.init(e,t),e._zod.pattern=qb,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}}),H_=R("$ZodNull",(e,t)=>{ce.init(e,t),e._zod.pattern=Zb,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}}),J_=R("$ZodAny",(e,t)=>{ce.init(e,t),e._zod.parse=n=>n}),W_=R("$ZodUnknown",(e,t)=>{ce.init(e,t),e._zod.parse=n=>n}),G_=R("$ZodNever",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),K_=R("$ZodVoid",(e,t)=>{ce.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}}),Y_=R("$ZodDate",(e,t)=>{ce.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 zh(e,t,n){e.issues.length&&t.issues.push(...Kt(n,e.issues)),t.value[n]=e.value}const Q_=R("$ZodArray",(e,t)=>{ce.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 a=0;a<r.length;a++){const s=r[a],u=t.element._zod.run({value:s,issues:[]},i);u instanceof Promise?o.push(u.then(l=>zh(l,n,a))):zh(u,n,a)}return o.length?Promise.all(o).then(()=>n):n}});function Ya(e,t,n,i){e.issues.length&&t.issues.push(...Kt(n,e.issues)),e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function X_(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=Wy(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ew(e,t,n,i,r,o){const a=[],s=r.keySet,u=r.catchall._zod,l=u.def.type;for(const c in t){if(s.has(c))continue;if(l==="never"){a.push(c);continue}const d=u.run({value:t[c],issues:[]},i);d instanceof Promise?e.push(d.then(f=>Ya(f,n,c,t))):Ya(d,n,c,t)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const tw=R("$ZodObject",(e,t)=>{if(ce.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const s=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}const i=vo(()=>X_(t));ge(e._zod,"propValues",()=>{const s=t.shape,u={};for(const l in s){const c=s[l]._zod;if(c.values){u[l]??(u[l]=new Set);for(const d of c.values)u[l].add(d)}}return u});const r=Kr,o=t.catchall;let a;e._zod.parse=(s,u)=>{a??(a=i.value);const l=s.value;if(!r(l))return s.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),s;s.value={};const c=[],d=a.shape;for(const f of a.keys){const g=d[f]._zod.run({value:l[f],issues:[]},u);g instanceof Promise?c.push(g.then(m=>Ya(m,s,f,l))):Ya(g,s,f,l)}return o?ew(c,l,s,u,i.value,e):c.length?Promise.all(c).then(()=>s):s}}),nw=R("$ZodObjectJIT",(e,t)=>{tw.init(e,t);const n=e._zod.parse,i=vo(()=>X_(t)),r=f=>{const p=new f_(["shape","payload","ctx"]),g=i.value,m=S=>{const b=cc(S);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const S of g.keys)y[S]=`key_${v++}`;p.write("const newResult = {};");for(const S of g.keys){const b=y[S],A=cc(S);p.write(`const ${b} = ${m(S)};`),p.write(`
|
|
11
|
+
if (${b}.issues.length) {
|
|
12
|
+
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
13
13
|
...iss,
|
|
14
|
-
path: iss.path ? [${
|
|
14
|
+
path: iss.path ? [${A}, ...iss.path] : [${A}]
|
|
15
15
|
})));
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
if (${
|
|
20
|
-
if (${
|
|
21
|
-
newResult[${
|
|
19
|
+
if (${b}.value === undefined) {
|
|
20
|
+
if (${A} in input) {
|
|
21
|
+
newResult[${A}] = undefined;
|
|
22
22
|
}
|
|
23
23
|
} else {
|
|
24
|
-
newResult[${
|
|
24
|
+
newResult[${A}] = ${b}.value;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
`)}p.write("payload.value = newResult;"),p.write("return payload;");const x=p.compile();return($,v)=>x(f,$,v)};let i;const a=Wr,s=!ci.jitless,u=s&&zm.value,c=t.catchall;let d;e._zod.parse=(f,p)=>{d??(d=o.value);const g=f.value;return a(g)?s&&u&&p?.async===!1&&p.jitless!==!0?(i||(i=n(t.shape)),f=i(f,p),c?Vg([],g,f,p,d,e):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f)}});function Ud(e,t,r,o){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const n=e.filter(i=>!mr(i));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ut(a,o,De())))}),t)}const Qi=S("$ZodUnion",(e,t)=>{X.init(e,t),ne(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ne(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ne(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ne(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>Hi(i.source)).join("|")})$`)}});const r=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(n,i)=>{if(r)return o(n,i);let a=!1;const s=[];for(const l of t.options){const u=l._zod.run({value:n.value,issues:[]},i);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(l=>Ud(l,n,e,i)):Ud(s,n,e,i)}});function Ld(e,t,r,o){const n=e.filter(i=>i.issues.length===0);return n.length===1?(t.value=n[0].value,t):(n.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ut(a,o,De())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}const Wg=S("$ZodXor",(e,t)=>{Qi.init(e,t),t.inclusive=!1;const r=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(n,i)=>{if(r)return o(n,i);let a=!1;const s=[];for(const l of t.options){const u=l._zod.run({value:n.value,issues:[]},i);u instanceof Promise?(s.push(u),a=!0):s.push(u)}return a?Promise.all(s).then(l=>Ld(l,n,e,i)):Ld(s,n,e,i)}}),Hg=S("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Qi.init(e,t);const r=e._zod.parse;ne(e._zod,"propValues",()=>{const n={};for(const i of t.options){const a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[s,l]of Object.entries(a)){n[s]||(n[s]=new Set);for(const u of l)n[s].add(u)}}return n});const o=Xn(()=>{const n=t.options,i=new Map;for(const a of n){const s=a._zod.propValues?.[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of s){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,a)}}return i});e._zod.parse=(n,i)=>{const a=n.value;if(!Wr(a))return n.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),n;const s=o.value.get(a?.[t.discriminator]);return s?s._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),n)}}),Gg=S("$ZodIntersection",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value,i=t.left._zod.run({value:n,issues:[]},o),a=t.right._zod.run({value:n,issues:[]},o);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([l,u])=>Zd(r,l,u)):Zd(r,i,a)}});function eu(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(yr(e)&&yr(t)){const r=Object.keys(t),o=Object.keys(e).filter(i=>r.indexOf(i)!==-1),n={...e,...t};for(const i of o){const a=eu(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n[i]=a.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let o=0;o<e.length;o++){const n=e[o],i=t[o],a=eu(n,i);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Zd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),mr(e))return e;const o=eu(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const al=S("$ZodTuple",(e,t)=>{X.init(e,t);const r=t.items;e._zod.parse=(o,n)=>{const i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const a=[],s=[...r].reverse().findIndex(c=>c._zod.optin!=="optional"),l=s===-1?0:r.length-s;if(!t.rest){const c=i.length>r.length,d=i.length<l-1;if(c||d)return o.issues.push({...c?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},input:i,inst:e,origin:"array"}),o}let u=-1;for(const c of r){if(u++,u>=i.length&&u>=l)continue;const d=c._zod.run({value:i[u],issues:[]},n);d instanceof Promise?a.push(d.then(f=>Uo(f,o,u))):Uo(d,o,u)}if(t.rest){const c=i.slice(r.length);for(const d of c){u++;const f=t.rest._zod.run({value:d,issues:[]},n);f instanceof Promise?a.push(f.then(p=>Uo(p,o,u))):Uo(f,o,u)}}return a.length?Promise.all(a).then(()=>o):o}});function Uo(e,t,r){e.issues.length&&t.issues.push(..._t(r,e.issues)),t.value[r]=e.value}const Kg=S("$ZodRecord",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!yr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;const i=[],a=t.keyType._zod.values;if(a){r.value={};const s=new Set;for(const u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){s.add(typeof u=="number"?u.toString():u);const c=t.valueType._zod.run({value:n[u],issues:[]},o);c instanceof Promise?i.push(c.then(d=>{d.issues.length&&r.issues.push(..._t(u,d.issues)),r.value[u]=d.value})):(c.issues.length&&r.issues.push(..._t(u,c.issues)),r.value[u]=c.value)}let l;for(const u in n)s.has(u)||(l=l??[],l.push(u));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(const s of Reflect.ownKeys(n)){if(s==="__proto__")continue;const l=t.keyType._zod.run({value:s,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){t.mode==="loose"?r.value[s]=n[s]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(c=>ut(c,o,De())),input:s,path:[s],inst:e});continue}const u=t.valueType._zod.run({value:n[s],issues:[]},o);u instanceof Promise?i.push(u.then(c=>{c.issues.length&&r.issues.push(..._t(s,c.issues)),r.value[l.value]=c.value})):(u.issues.length&&r.issues.push(..._t(s,u.issues)),r.value[l.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}}),Yg=S("$ZodMap",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;const i=[];r.value=new Map;for(const[a,s]of n){const l=t.keyType._zod.run({value:a,issues:[]},o),u=t.valueType._zod.run({value:s,issues:[]},o);l instanceof Promise||u instanceof Promise?i.push(Promise.all([l,u]).then(([c,d])=>{Fd(c,d,r,a,n,e,o)})):Fd(l,u,r,a,n,e,o)}return i.length?Promise.all(i).then(()=>r):r}});function Fd(e,t,r,o,n,i,a){e.issues.length&&(pi.has(typeof o)?r.issues.push(..._t(o,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:i,issues:e.issues.map(s=>ut(s,a,De()))})),t.issues.length&&(pi.has(typeof o)?r.issues.push(..._t(o,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:o,issues:t.issues.map(s=>ut(s,a,De()))})),r.value.set(e.value,t.value)}const Qg=S("$ZodSet",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;const i=[];r.value=new Set;for(const a of n){const s=t.valueType._zod.run({value:a,issues:[]},o);s instanceof Promise?i.push(s.then(l=>qd(l,r))):qd(s,r)}return i.length?Promise.all(i).then(()=>r):r}});function qd(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const Xg=S("$ZodEnum",(e,t)=>{X.init(e,t);const r=Uu(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>pi.has(typeof n)).map(n=>typeof n=="string"?qt(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{const a=n.value;return o.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:e}),n}}),ev=S("$ZodLiteral",(e,t)=>{if(X.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(o=>typeof o=="string"?qt(o):o?qt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{const i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}}),tv=S("$ZodFile",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;return n instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),r}}),rv=S("$ZodTransform",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Wi(e.constructor.name);const n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(a=>(r.value=a,r));if(n instanceof Promise)throw new vr;return r.value=n,r}});function Vd(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const nv=S("$ZodOptional",(e,t)=>{X.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ne(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Hi(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Vd(i,r.value)):Vd(n,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,o)}}),ov=S("$ZodNullable",(e,t)=>{X.init(e,t),ne(e._zod,"optin",()=>t.innerType._zod.optin),ne(e._zod,"optout",()=>t.innerType._zod.optout),ne(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Hi(r.source)}|null)$`):void 0}),ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),iv=S("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Bd(i,t)):Bd(n,t)}});function Bd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const av=S("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(o.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),sv=S("$ZodNonOptional",(e,t)=>{X.init(e,t),ne(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Jd(i,e)):Jd(n,e)}});function Jd(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 uv=S("$ZodSuccess",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Wi("ZodSuccess");const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>(r.value=i.issues.length===0,r)):(r.value=n.issues.length===0,r)}}),lv=S("$ZodCatch",(e,t)=>{X.init(e,t),ne(e._zod,"optin",()=>t.innerType._zod.optin),ne(e._zod,"optout",()=>t.innerType._zod.optout),ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(a=>ut(a,o,De()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(i=>ut(i,o,De()))},input:r.value}),r.issues=[]),r)}}),cv=S("$ZodNaN",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),dv=S("$ZodPipe",(e,t)=>{X.init(e,t),ne(e._zod,"values",()=>t.in._zod.values),ne(e._zod,"optin",()=>t.in._zod.optin),ne(e._zod,"optout",()=>t.out._zod.optout),ne(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){const i=t.out._zod.run(r,o);return i instanceof Promise?i.then(a=>Lo(a,t.in,o)):Lo(i,t.in,o)}const n=t.in._zod.run(r,o);return n instanceof Promise?n.then(i=>Lo(i,t.out,o)):Lo(n,t.out,o)}});function Lo(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const sl=S("$ZodCodec",(e,t)=>{X.init(e,t),ne(e._zod,"values",()=>t.in._zod.values),ne(e._zod,"optin",()=>t.in._zod.optin),ne(e._zod,"optout",()=>t.out._zod.optout),ne(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if((o.direction||"forward")==="forward"){const i=t.in._zod.run(r,o);return i instanceof Promise?i.then(a=>Zo(a,t,o)):Zo(i,t,o)}else{const i=t.out._zod.run(r,o);return i instanceof Promise?i.then(a=>Zo(a,t,o)):Zo(i,t,o)}}});function Zo(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){const n=t.transform(e.value,e);return n instanceof Promise?n.then(i=>Fo(e,i,t.out,r)):Fo(e,n,t.out,r)}else{const n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(i=>Fo(e,i,t.in,r)):Fo(e,n,t.in,r)}}function Fo(e,t,r,o){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},o)}const pv=S("$ZodReadonly",(e,t)=>{X.init(e,t),ne(e._zod,"propValues",()=>t.innerType._zod.propValues),ne(e._zod,"values",()=>t.innerType._zod.values),ne(e._zod,"optin",()=>t.innerType?._zod?.optin),ne(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(Wd):Wd(n)}});function Wd(e){return e.value=Object.freeze(e.value),e}const fv=S("$ZodTemplateLiteral",(e,t)=>{X.init(e,t);const r=[];for(const o of t.parts)if(typeof o=="object"&&o!==null){if(!o._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);const n=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!n)throw new Error(`Invalid template literal part: ${o._zod.traits}`);const i=n.startsWith("^")?1:0,a=n.endsWith("$")?n.length-1:n.length;r.push(n.slice(i,a))}else if(o===null||Mm.has(typeof o))r.push(qt(`${o}`));else throw new Error(`Invalid template literal part: ${o}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(o,n)=>typeof o.value!="string"?(o.issues.push({input:o.value,inst:e,expected:"template_literal",code:"invalid_type"}),o):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(o.value)||o.issues.push({input:o.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),o)}),mv=S("$ZodFunction",(e,t)=>(X.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...o){const n=e._def.input?Qs(e._def.input,o):o,i=Reflect.apply(r,this,n);return e._def.output?Qs(e._def.output,i):i}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...o){const n=e._def.input?await Xs(e._def.input,o):o,i=await Reflect.apply(r,this,n);return e._def.output?await Xs(e._def.output,i):i}},e._zod.parse=(r,o)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{const o=e.constructor;return Array.isArray(r[0])?new o({type:"function",input:new al({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new o({type:"function",input:r[0],output:e._def.output})},e.output=r=>{const o=e.constructor;return new o({type:"function",input:e._def.input,output:r})},e)),hv=S("$ZodPromise",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>Promise.resolve(r.value).then(n=>t.innerType._zod.run({value:n,issues:[]},o))}),gv=S("$ZodLazy",(e,t)=>{X.init(e,t),ne(e._zod,"innerType",()=>t.getter()),ne(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ne(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ne(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ne(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),vv=S("$ZodCustom",(e,t)=>{Se.init(e,t),X.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{const o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(i=>Hd(i,r,o,e));Hd(n,r,o,e)}});function Hd(e,t,r,o){if(!e){const n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),t.issues.push(Hr(n))}}const RI=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${n.expected}، ولكن تم إدخال ${r(n.input)}`;case"invalid_value":return n.values.length===1?`مدخلات غير مقبولة: يفترض إدخال ${H(n.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?` أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${i} ${n.maximum.toString()} ${a.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${i} ${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${i} ${n.minimum.toString()} ${a.unit}`:`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${i} ${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`نَص غير مقبول: يجب أن يبدأ بـ "${n.prefix}"`:i.format==="ends_with"?`نَص غير مقبول: يجب أن ينتهي بـ "${i.suffix}"`:i.format==="includes"?`نَص غير مقبول: يجب أن يتضمَّن "${i.includes}"`:i.format==="regex"?`نَص غير مقبول: يجب أن يطابق النمط ${i.pattern}`:`${o[i.format]??n.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${n.divisor}`;case"unrecognized_keys":return`معرف${n.keys.length>1?"ات":""} غريب${n.keys.length>1?"ة":""}: ${j(n.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${n.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${n.origin}`;default:return"مدخل غير مقبول"}}};function zI(){return{localeError:RI()}}const MI=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${n.expected}, daxil olan ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Yanlış dəyər: gözlənilən ${H(n.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${i}${n.maximum.toString()} ${a.unit??"element"}`:`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Çox kiçik: gözlənilən ${n.origin} ${i}${n.minimum.toString()} ${a.unit}`:`Çox kiçik: gözlənilən ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Yanlış mətn: "${i.prefix}" ilə başlamalıdır`:i.format==="ends_with"?`Yanlış mətn: "${i.suffix}" ilə bitməlidir`:i.format==="includes"?`Yanlış mətn: "${i.includes}" daxil olmalıdır`:i.format==="regex"?`Yanlış mətn: ${i.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${o[i.format]??n.format}`}case"not_multiple_of":return`Yanlış ədəd: ${n.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${n.keys.length>1?"lar":""}: ${j(n.keys,", ")}`;case"invalid_key":return`${n.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${n.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function DI(){return{localeError:MI()}}function Gd(e,t,r,o){const n=Math.abs(e),i=n%10,a=n%100;return a>=11&&a<=19?o:i===1?t:i>=2&&i<=4?r:o}const UI=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"лік";case"object":{if(Array.isArray(n))return"масіў";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${n.expected}, атрымана ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Няправільны ўвод: чакалася ${H(n.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);if(a){const s=Number(n.maximum),l=Gd(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна ${a.verb} ${i}${n.maximum.toString()} ${l}`}return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна быць ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);if(a){const s=Number(n.minimum),l=Gd(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта малы: чакалася, што ${n.origin} павінна ${a.verb} ${i}${n.minimum.toString()} ${l}`}return`Занадта малы: чакалася, што ${n.origin} павінна быць ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Няправільны радок: павінен пачынацца з "${i.prefix}"`:i.format==="ends_with"?`Няправільны радок: павінен заканчвацца на "${i.suffix}"`:i.format==="includes"?`Няправільны радок: павінен змяшчаць "${i.includes}"`:i.format==="regex"?`Няправільны радок: павінен адпавядаць шаблону ${i.pattern}`:`Няправільны ${o[i.format]??n.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${n.keys.length>1?"ключы":"ключ"}: ${j(n.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${n.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${n.origin}`;default:return"Няправільны ўвод"}}};function LI(){return{localeError:UI()}}const ZI=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},FI=()=>{const e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function t(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`Невалиден вход: очакван ${o.expected}, получен ${ZI(o.input)}`;case"invalid_value":return o.values.length===1?`Невалиден вход: очакван ${H(o.values[0])}`:`Невалидна опция: очаквано едно от ${j(o.values,"|")}`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Твърде голямо: очаква се ${o.origin??"стойност"} да съдържа ${n}${o.maximum.toString()} ${i.unit??"елемента"}`:`Твърде голямо: очаква се ${o.origin??"стойност"} да бъде ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`Твърде малко: очаква се ${o.origin} да съдържа ${n}${o.minimum.toString()} ${i.unit}`:`Твърде малко: очаква се ${o.origin} да бъде ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;if(n.format==="starts_with")return`Невалиден низ: трябва да започва с "${n.prefix}"`;if(n.format==="ends_with")return`Невалиден низ: трябва да завършва с "${n.suffix}"`;if(n.format==="includes")return`Невалиден низ: трябва да включва "${n.includes}"`;if(n.format==="regex")return`Невалиден низ: трябва да съвпада с ${n.pattern}`;let i="Невалиден";return n.format==="emoji"&&(i="Невалидно"),n.format==="datetime"&&(i="Невалидно"),n.format==="date"&&(i="Невалидна"),n.format==="time"&&(i="Невалидно"),n.format==="duration"&&(i="Невалидна"),`${i} ${r[n.format]??o.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${o.divisor}`;case"unrecognized_keys":return`Неразпознат${o.keys.length>1?"и":""} ключ${o.keys.length>1?"ове":""}: ${j(o.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${o.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${o.origin}`;default:return"Невалиден вход"}}};function qI(){return{localeError:FI()}}const VI=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Tipus invàlid: s'esperava ${n.expected}, s'ha rebut ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Valor invàlid: s'esperava ${H(n.values[0])}`:`Opció invàlida: s'esperava una de ${j(n.values," o ")}`;case"too_big":{const i=n.inclusive?"com a màxim":"menys de",a=t(n.origin);return a?`Massa gran: s'esperava que ${n.origin??"el valor"} contingués ${i} ${n.maximum.toString()} ${a.unit??"elements"}`:`Massa gran: s'esperava que ${n.origin??"el valor"} fos ${i} ${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?"com a mínim":"més de",a=t(n.origin);return a?`Massa petit: s'esperava que ${n.origin} contingués ${i} ${n.minimum.toString()} ${a.unit}`:`Massa petit: s'esperava que ${n.origin} fos ${i} ${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Format invàlid: ha de començar amb "${i.prefix}"`:i.format==="ends_with"?`Format invàlid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format invàlid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format invàlid: ha de coincidir amb el patró ${i.pattern}`:`Format invàlid per a ${o[i.format]??n.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${n.divisor}`;case"unrecognized_keys":return`Clau${n.keys.length>1?"s":""} no reconeguda${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${n.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${n.origin}`;default:return"Entrada invàlida"}}};function BI(){return{localeError:VI()}}const JI=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"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(n))return"pole";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Neplatný vstup: očekáváno ${n.expected}, obdrženo ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Neplatný vstup: očekáváno ${H(n.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Hodnota je příliš velká: ${n.origin??"hodnota"} musí mít ${i}${n.maximum.toString()} ${a.unit??"prvků"}`:`Hodnota je příliš velká: ${n.origin??"hodnota"} musí být ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Hodnota je příliš malá: ${n.origin??"hodnota"} musí mít ${i}${n.minimum.toString()} ${a.unit??"prvků"}`:`Hodnota je příliš malá: ${n.origin??"hodnota"} musí být ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Neplatný řetězec: musí začínat na "${i.prefix}"`:i.format==="ends_with"?`Neplatný řetězec: musí končit na "${i.suffix}"`:i.format==="includes"?`Neplatný řetězec: musí obsahovat "${i.includes}"`:i.format==="regex"?`Neplatný řetězec: musí odpovídat vzoru ${i.pattern}`:`Neplatný formát ${o[i.format]??n.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${n.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${j(n.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${n.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${n.origin}`;default:return"Neplatný vstup"}}};function WI(){return{localeError:JI()}}const HI=()=>{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 r(a){return e[a]??null}function o(a){return t[a]??a}const n=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"tal";case"object":return Array.isArray(a)?"liste":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype&&a.constructor?a.constructor.name:"objekt"}return s},i={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 a=>{switch(a.code){case"invalid_type":return`Ugyldigt input: forventede ${o(a.expected)}, fik ${o(n(a.input))}`;case"invalid_value":return a.values.length===1?`Ugyldig værdi: forventede ${H(a.values[0])}`:`Ugyldigt valg: forventede en af følgende ${j(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",l=r(a.origin),u=o(a.origin);return l?`For stor: forventede ${u??"value"} ${l.verb} ${s} ${a.maximum.toString()} ${l.unit??"elementer"}`:`For stor: forventede ${u??"value"} havde ${s} ${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",l=r(a.origin),u=o(a.origin);return l?`For lille: forventede ${u} ${l.verb} ${s} ${a.minimum.toString()} ${l.unit}`:`For lille: forventede ${u} havde ${s} ${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Ugyldig streng: skal starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: skal ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: skal indeholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: skal matche mønsteret ${s.pattern}`:`Ugyldig ${i[s.format]??a.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${j(a.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${a.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${a.origin}`;default:return"Ugyldigt input"}}};function GI(){return{localeError:HI()}}const KI=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"Zahl";case"object":{if(Array.isArray(n))return"Array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${n.expected}, erhalten ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Ungültige Eingabe: erwartet ${H(n.values[0])}`:`Ungültige Option: erwartet eine von ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Zu groß: erwartet, dass ${n.origin??"Wert"} ${i}${n.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${n.origin??"Wert"} ${i}${n.maximum.toString()} ist`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Zu klein: erwartet, dass ${n.origin} ${i}${n.minimum.toString()} ${a.unit} hat`:`Zu klein: erwartet, dass ${n.origin} ${i}${n.minimum.toString()} ist`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Ungültiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ungültiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ungültiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ungültiger String: muss dem Muster ${i.pattern} entsprechen`:`Ungültig: ${o[i.format]??n.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${n.divisor} sein`;case"unrecognized_keys":return`${n.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${j(n.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${n.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${n.origin}`;default:return"Ungültige Eingabe"}}};function YI(){return{localeError:KI()}}const QI=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},XI=()=>{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(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${QI(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${H(o.values[0])}`:`Invalid option: expected one of ${j(o.values,"|")}`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${j(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function yv(){return{localeError:XI()}}const ek=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},tk=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${o.expected}, riceviĝis ${ek(o.input)}`;case"invalid_value":return o.values.length===1?`Nevalida enigo: atendiĝis ${H(o.values[0])}`:`Nevalida opcio: atendiĝis unu el ${j(o.values,"|")}`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Tro granda: atendiĝis ke ${o.origin??"valoro"} havu ${n}${o.maximum.toString()} ${i.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${o.origin??"valoro"} havu ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`Tro malgranda: atendiĝis ke ${o.origin} havu ${n}${o.minimum.toString()} ${i.unit}`:`Tro malgranda: atendiĝis ke ${o.origin} estu ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`Nevalida karaktraro: devas komenciĝi per "${n.prefix}"`:n.format==="ends_with"?`Nevalida karaktraro: devas finiĝi per "${n.suffix}"`:n.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${n.includes}"`:n.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${n.pattern}`:`Nevalida ${r[n.format]??o.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${o.divisor}`;case"unrecognized_keys":return`Nekonata${o.keys.length>1?"j":""} ŝlosilo${o.keys.length>1?"j":""}: ${j(o.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${o.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${o.origin}`;default:return"Nevalida enigo"}}};function rk(){return{localeError:tk()}}const nk=()=>{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 r(a){return e[a]??null}function o(a){return t[a]??a}const n=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"number";case"object":return Array.isArray(a)?"array":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype?a.constructor.name:"object"}return s},i={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 a=>{switch(a.code){case"invalid_type":return`Entrada inválida: se esperaba ${o(a.expected)}, recibido ${o(n(a.input))}`;case"invalid_value":return a.values.length===1?`Entrada inválida: se esperaba ${H(a.values[0])}`:`Opción inválida: se esperaba una de ${j(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",l=r(a.origin),u=o(a.origin);return l?`Demasiado grande: se esperaba que ${u??"valor"} tuviera ${s}${a.maximum.toString()} ${l.unit??"elementos"}`:`Demasiado grande: se esperaba que ${u??"valor"} fuera ${s}${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",l=r(a.origin),u=o(a.origin);return l?`Demasiado pequeño: se esperaba que ${u} tuviera ${s}${a.minimum.toString()} ${l.unit}`:`Demasiado pequeño: se esperaba que ${u} fuera ${s}${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Cadena inválida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inválida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inválida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inválida: debe coincidir con el patrón ${s.pattern}`:`Inválido ${i[s.format]??a.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${a.divisor}`;case"unrecognized_keys":return`Llave${a.keys.length>1?"s":""} desconocida${a.keys.length>1?"s":""}: ${j(a.keys,", ")}`;case"invalid_key":return`Llave inválida en ${o(a.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${o(a.origin)}`;default:return"Entrada inválida"}}};function ok(){return{localeError:nk()}}const ik=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"عدد";case"object":{if(Array.isArray(n))return"آرایه";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${n.expected} میبود، ${r(n.input)} دریافت شد`;case"invalid_value":return n.values.length===1?`ورودی نامعتبر: میبایست ${H(n.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${j(n.values,"|")} میبود`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`خیلی بزرگ: ${n.origin??"مقدار"} باید ${i}${n.maximum.toString()} ${a.unit??"عنصر"} باشد`:`خیلی بزرگ: ${n.origin??"مقدار"} باید ${i}${n.maximum.toString()} باشد`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`خیلی کوچک: ${n.origin} باید ${i}${n.minimum.toString()} ${a.unit} باشد`:`خیلی کوچک: ${n.origin} باید ${i}${n.minimum.toString()} باشد`}case"invalid_format":{const i=n;return i.format==="starts_with"?`رشته نامعتبر: باید با "${i.prefix}" شروع شود`:i.format==="ends_with"?`رشته نامعتبر: باید با "${i.suffix}" تمام شود`:i.format==="includes"?`رشته نامعتبر: باید شامل "${i.includes}" باشد`:i.format==="regex"?`رشته نامعتبر: باید با الگوی ${i.pattern} مطابقت داشته باشد`:`${o[i.format]??n.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${n.divisor} باشد`;case"unrecognized_keys":return`کلید${n.keys.length>1?"های":""} ناشناس: ${j(n.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${n.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${n.origin}`;default:return"ورودی نامعتبر"}}};function ak(){return{localeError:ik()}}const sk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${n.expected}, oli ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Virheellinen syöte: täytyy olla ${H(n.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Liian suuri: ${a.subject} täytyy olla ${i}${n.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon täytyy olla ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Liian pieni: ${a.subject} täytyy olla ${i}${n.minimum.toString()} ${a.unit}`.trim():`Liian pieni: arvon täytyy olla ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Virheellinen syöte: täytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen syöte: täytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen syöte: täytyy sisältää "${i.includes}"`:i.format==="regex"?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${i.pattern}`:`Virheellinen ${o[i.format]??n.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${n.divisor} monikerta`;case"unrecognized_keys":return`${n.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${j(n.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 uk(){return{localeError:sk()}}const lk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"nombre";case"object":{if(Array.isArray(n))return"tableau";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Entrée invalide : ${n.expected} attendu, ${r(n.input)} reçu`;case"invalid_value":return n.values.length===1?`Entrée invalide : ${H(n.values[0])} attendu`:`Option invalide : une valeur parmi ${j(n.values,"|")} attendue`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Trop grand : ${n.origin??"valeur"} doit ${a.verb} ${i}${n.maximum.toString()} ${a.unit??"élément(s)"}`:`Trop grand : ${n.origin??"valeur"} doit être ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Trop petit : ${n.origin} doit ${a.verb} ${i}${n.minimum.toString()} ${a.unit}`:`Trop petit : ${n.origin} doit être ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Chaîne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Chaîne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Chaîne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Chaîne invalide : doit correspondre au modèle ${i.pattern}`:`${o[i.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${j(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function ck(){return{localeError:lk()}}const dk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Entrée invalide : attendu ${n.expected}, reçu ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Entrée invalide : attendu ${H(n.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"≤":"<",a=t(n.origin);return a?`Trop grand : attendu que ${n.origin??"la valeur"} ait ${i}${n.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${n.origin??"la valeur"} soit ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?"≥":">",a=t(n.origin);return a?`Trop petit : attendu que ${n.origin} ait ${i}${n.minimum.toString()} ${a.unit}`:`Trop petit : attendu que ${n.origin} soit ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Chaîne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Chaîne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Chaîne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Chaîne invalide : doit correspondre au motif ${i.pattern}`:`${o[i.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${j(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function pk(){return{localeError:dk()}}const fk=()=>{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:"גדול"}},r=u=>u?e[u]:void 0,o=u=>{const c=r(u);return c?c.label:u??e.unknown.label},n=u=>`ה${o(u)}`,i=u=>(r(u)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",a=u=>u?t[u]??null:null,s=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=o(c),f=s(u.input),p=e[f]?.label??f;return`קלט לא תקין: צריך להיות ${d}, התקבל ${p}`}case"invalid_value":{if(u.values.length===1)return`ערך לא תקין: הערך חייב להיות ${H(u.values[0])}`;const c=u.values.map(p=>H(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=a(u.origin),d=n(u.origin??"value");if(u.origin==="string")return`${c?.longLabel??"ארוך"} מדי: ${d} צריכה להכיל ${u.maximum.toString()} ${c?.unit??""} ${u.inclusive?"או פחות":"לכל היותר"}`.trim();if(u.origin==="number"){const g=u.inclusive?`קטן או שווה ל-${u.maximum}`:`קטן מ-${u.maximum}`;return`גדול מדי: ${d} צריך להיות ${g}`}if(u.origin==="array"||u.origin==="set"){const g=u.origin==="set"?"צריכה":"צריך",h=u.inclusive?`${u.maximum} ${c?.unit??""} או פחות`:`פחות מ-${u.maximum} ${c?.unit??""}`;return`גדול מדי: ${d} ${g} להכיל ${h}`.trim()}const f=u.inclusive?"<=":"<",p=i(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=a(u.origin),d=n(u.origin??"value");if(u.origin==="string")return`${c?.shortLabel??"קצר"} מדי: ${d} צריכה להכיל ${u.minimum.toString()} ${c?.unit??""} ${u.inclusive?"או יותר":"לפחות"}`.trim();if(u.origin==="number"){const g=u.inclusive?`גדול או שווה ל-${u.minimum}`:`גדול מ-${u.minimum}`;return`קטן מדי: ${d} צריך להיות ${g}`}if(u.origin==="array"||u.origin==="set"){const g=u.origin==="set"?"צריכה":"צריך";if(u.minimum===1&&u.inclusive){const b=(u.origin==="set","לפחות פריט אחד");return`קטן מדי: ${d} ${g} להכיל ${b}`}const h=u.inclusive?`${u.minimum} ${c?.unit??""} או יותר`:`יותר מ-${u.minimum} ${c?.unit??""}`;return`קטן מדי: ${d} ${g} להכיל ${h}`.trim()}const f=u.inclusive?">=":">",p=i(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,g=(d?.gender??"m")==="f"?"תקינה":"תקין";return`${f} לא ${g}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${u.divisor}`;case"unrecognized_keys":return`מפתח${u.keys.length>1?"ות":""} לא מזוה${u.keys.length>1?"ים":"ה"}: ${j(u.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${n(u.origin??"array")}`;default:return"קלט לא תקין"}}};function mk(){return{localeError:fk()}}const hk=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"szám";case"object":{if(Array.isArray(n))return"tömb";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${n.expected}, a kapott érték ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Érvénytelen bemenet: a várt érték ${H(n.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Túl nagy: ${n.origin??"érték"} mérete túl nagy ${i}${n.maximum.toString()} ${a.unit??"elem"}`:`Túl nagy: a bemeneti érték ${n.origin??"érték"} túl nagy: ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Túl kicsi: a bemeneti érték ${n.origin} mérete túl kicsi ${i}${n.minimum.toString()} ${a.unit}`:`Túl kicsi: a bemeneti érték ${n.origin} túl kicsi ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Érvénytelen string: "${i.prefix}" értékkel kell kezdődnie`:i.format==="ends_with"?`Érvénytelen string: "${i.suffix}" értékkel kell végződnie`:i.format==="includes"?`Érvénytelen string: "${i.includes}" értéket kell tartalmaznia`:i.format==="regex"?`Érvénytelen string: ${i.pattern} mintának kell megfelelnie`:`Érvénytelen ${o[i.format]??n.format}`}case"not_multiple_of":return`Érvénytelen szám: ${n.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${n.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${n.origin}`;default:return"Érvénytelen bemenet"}}};function gk(){return{localeError:hk()}}const vk=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Input tidak valid: diharapkan ${n.expected}, diterima ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Input tidak valid: diharapkan ${H(n.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Terlalu besar: diharapkan ${n.origin??"value"} memiliki ${i}${n.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${n.origin??"value"} menjadi ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Terlalu kecil: diharapkan ${n.origin} memiliki ${i}${n.minimum.toString()} ${a.unit}`:`Terlalu kecil: diharapkan ${n.origin} menjadi ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${o[i.format]??n.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${n.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${n.origin}`;default:return"Input tidak valid"}}};function yk(){return{localeError:vk()}}const bk=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},_k=()=>{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(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${bk(o.input)} þar sem á að vera ${o.expected}`;case"invalid_value":return o.values.length===1?`Rangt gildi: gert ráð fyrir ${H(o.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${j(o.values,"|")}`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Of stórt: gert er ráð fyrir að ${o.origin??"gildi"} hafi ${n}${o.maximum.toString()} ${i.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${o.origin??"gildi"} sé ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`Of lítið: gert er ráð fyrir að ${o.origin} hafi ${n}${o.minimum.toString()} ${i.unit}`:`Of lítið: gert er ráð fyrir að ${o.origin} sé ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`Ógildur strengur: verður að byrja á "${n.prefix}"`:n.format==="ends_with"?`Ógildur strengur: verður að enda á "${n.suffix}"`:n.format==="includes"?`Ógildur strengur: verður að innihalda "${n.includes}"`:n.format==="regex"?`Ógildur strengur: verður að fylgja mynstri ${n.pattern}`:`Rangt ${r[n.format]??o.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${o.divisor}`;case"unrecognized_keys":return`Óþekkt ${o.keys.length>1?"ir lyklar":"ur lykill"}: ${j(o.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${o.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${o.origin}`;default:return"Rangt gildi"}}};function wk(){return{localeError:_k()}}const xk=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"numero";case"object":{if(Array.isArray(n))return"vettore";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Input non valido: atteso ${n.expected}, ricevuto ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Input non valido: atteso ${H(n.values[0])}`:`Opzione non valida: atteso uno tra ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Troppo grande: ${n.origin??"valore"} deve avere ${i}${n.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${n.origin??"valore"} deve essere ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Troppo piccolo: ${n.origin} deve avere ${i}${n.minimum.toString()} ${a.unit}`:`Troppo piccolo: ${n.origin} deve essere ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Invalid ${o[i.format]??n.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${n.divisor}`;case"unrecognized_keys":return`Chiav${n.keys.length>1?"i":"e"} non riconosciut${n.keys.length>1?"e":"a"}: ${j(n.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${n.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${n.origin}`;default:return"Input non valido"}}};function $k(){return{localeError:xk()}}const Sk=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"数値";case"object":{if(Array.isArray(n))return"配列";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`無効な入力: ${n.expected}が期待されましたが、${r(n.input)}が入力されました`;case"invalid_value":return n.values.length===1?`無効な入力: ${H(n.values[0])}が期待されました`:`無効な選択: ${j(n.values,"、")}のいずれかである必要があります`;case"too_big":{const i=n.inclusive?"以下である":"より小さい",a=t(n.origin);return a?`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${a.unit??"要素"}${i}必要があります`:`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${i}必要があります`}case"too_small":{const i=n.inclusive?"以上である":"より大きい",a=t(n.origin);return a?`小さすぎる値: ${n.origin}は${n.minimum.toString()}${a.unit}${i}必要があります`:`小さすぎる値: ${n.origin}は${n.minimum.toString()}${i}必要があります`}case"invalid_format":{const i=n;return i.format==="starts_with"?`無効な文字列: "${i.prefix}"で始まる必要があります`:i.format==="ends_with"?`無効な文字列: "${i.suffix}"で終わる必要があります`:i.format==="includes"?`無効な文字列: "${i.includes}"を含む必要があります`:i.format==="regex"?`無効な文字列: パターン${i.pattern}に一致する必要があります`:`無効な${o[i.format]??n.format}`}case"not_multiple_of":return`無効な数値: ${n.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${n.keys.length>1?"群":""}: ${j(n.keys,"、")}`;case"invalid_key":return`${n.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${n.origin}内の無効な値`;default:return"無効な入力"}}};function Ik(){return{localeError:Sk()}}const kk=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},Ek=()=>{const e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function t(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`არასწორი შეყვანა: მოსალოდნელი ${o.expected}, მიღებული ${kk(o.input)}`;case"invalid_value":return o.values.length===1?`არასწორი შეყვანა: მოსალოდნელი ${H(o.values[0])}`:`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${j(o.values,"|")}-დან`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`ზედმეტად დიდი: მოსალოდნელი ${o.origin??"მნიშვნელობა"} ${i.verb} ${n}${o.maximum.toString()} ${i.unit}`:`ზედმეტად დიდი: მოსალოდნელი ${o.origin??"მნიშვნელობა"} იყოს ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`ზედმეტად პატარა: მოსალოდნელი ${o.origin} ${i.verb} ${n}${o.minimum.toString()} ${i.unit}`:`ზედმეტად პატარა: მოსალოდნელი ${o.origin} იყოს ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`არასწორი სტრინგი: უნდა იწყებოდეს "${n.prefix}"-ით`:n.format==="ends_with"?`არასწორი სტრინგი: უნდა მთავრდებოდეს "${n.suffix}"-ით`:n.format==="includes"?`არასწორი სტრინგი: უნდა შეიცავდეს "${n.includes}"-ს`:n.format==="regex"?`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${n.pattern}`:`არასწორი ${r[n.format]??o.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${o.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${o.keys.length>1?"ები":"ი"}: ${j(o.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${o.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${o.origin}-ში`;default:return"არასწორი შეყვანა"}}};function Tk(){return{localeError:Ek()}}const Ok=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":{if(Array.isArray(n))return"អារេ (Array)";if(n===null)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${n.expected} ប៉ុន្តែទទួលបាន ${r(n.input)}`;case"invalid_value":return n.values.length===1?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${H(n.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${i} ${n.maximum.toString()} ${a.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${i} ${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`តូចពេក៖ ត្រូវការ ${n.origin} ${i} ${n.minimum.toString()} ${a.unit}`:`តូចពេក៖ ត្រូវការ ${n.origin} ${i} ${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${i.prefix}"`:i.format==="ends_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${i.suffix}"`:i.format==="includes"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${i.includes}"`:i.format==="regex"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${i.pattern}`:`មិនត្រឹមត្រូវ៖ ${o[i.format]??n.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${n.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${j(n.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function bv(){return{localeError:Ok()}}function Nk(){return bv()}const Pk=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${n.expected}, 받은 타입은 ${r(n.input)}입니다`;case"invalid_value":return n.values.length===1?`잘못된 입력: 값은 ${H(n.values[0])} 이어야 합니다`:`잘못된 옵션: ${j(n.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const i=n.inclusive?"이하":"미만",a=i==="미만"?"이어야 합니다":"여야 합니다",s=t(n.origin),l=s?.unit??"요소";return s?`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()}${l} ${i}${a}`:`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()} ${i}${a}`}case"too_small":{const i=n.inclusive?"이상":"초과",a=i==="이상"?"이어야 합니다":"여야 합니다",s=t(n.origin),l=s?.unit??"요소";return s?`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()}${l} ${i}${a}`:`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()} ${i}${a}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`잘못된 문자열: "${i.prefix}"(으)로 시작해야 합니다`:i.format==="ends_with"?`잘못된 문자열: "${i.suffix}"(으)로 끝나야 합니다`:i.format==="includes"?`잘못된 문자열: "${i.includes}"을(를) 포함해야 합니다`:i.format==="regex"?`잘못된 문자열: 정규식 ${i.pattern} 패턴과 일치해야 합니다`:`잘못된 ${o[i.format]??n.format}`}case"not_multiple_of":return`잘못된 숫자: ${n.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${j(n.keys,", ")}`;case"invalid_key":return`잘못된 키: ${n.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${n.origin}`;default:return"잘못된 입력"}}};function Ck(){return{localeError:Pk()}}const jk=e=>Sn(typeof e,e),Sn=(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},bn=e=>e.charAt(0).toUpperCase()+e.slice(1);function Kd(e){const t=Math.abs(e),r=t%10,o=t%100;return o>=11&&o<=19||r===0?"many":r===1?"one":"few"}const Ak=()=>{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(o,n,i,a){const s=e[o]??null;return s===null?s:{unit:s.unit[n],verb:s.verb[a][i?"inclusive":"notInclusive"]}}const r={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 o=>{switch(o.code){case"invalid_type":return`Gautas tipas ${jk(o.input)}, o tikėtasi - ${Sn(o.expected)}`;case"invalid_value":return o.values.length===1?`Privalo būti ${H(o.values[0])}`:`Privalo būti vienas iš ${j(o.values,"|")} pasirinkimų`;case"too_big":{const n=Sn(o.origin),i=t(o.origin,Kd(Number(o.maximum)),o.inclusive??!1,"smaller");if(i?.verb)return`${bn(n??o.origin??"reikšmė")} ${i.verb} ${o.maximum.toString()} ${i.unit??"elementų"}`;const a=o.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${bn(n??o.origin??"reikšmė")} turi būti ${a} ${o.maximum.toString()} ${i?.unit}`}case"too_small":{const n=Sn(o.origin),i=t(o.origin,Kd(Number(o.minimum)),o.inclusive??!1,"bigger");if(i?.verb)return`${bn(n??o.origin??"reikšmė")} ${i.verb} ${o.minimum.toString()} ${i.unit??"elementų"}`;const a=o.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${bn(n??o.origin??"reikšmė")} turi būti ${a} ${o.minimum.toString()} ${i?.unit}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`Eilutė privalo prasidėti "${n.prefix}"`:n.format==="ends_with"?`Eilutė privalo pasibaigti "${n.suffix}"`:n.format==="includes"?`Eilutė privalo įtraukti "${n.includes}"`:n.format==="regex"?`Eilutė privalo atitikti ${n.pattern}`:`Neteisingas ${r[n.format]??o.format}`}case"not_multiple_of":return`Skaičius privalo būti ${o.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${o.keys.length>1?"i":"as"} rakt${o.keys.length>1?"ai":"as"}: ${j(o.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{const n=Sn(o.origin);return`${bn(n??o.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function Rk(){return{localeError:Ak()}}const zk=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"број";case"object":{if(Array.isArray(n))return"низа";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Грешен внес: се очекува ${n.expected}, примено ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${H(n.values[0])}`:`Грешана опција: се очекува една ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Премногу голем: се очекува ${n.origin??"вредноста"} да има ${i}${n.maximum.toString()} ${a.unit??"елементи"}`:`Премногу голем: се очекува ${n.origin??"вредноста"} да биде ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Премногу мал: се очекува ${n.origin} да има ${i}${n.minimum.toString()} ${a.unit}`:`Премногу мал: се очекува ${n.origin} да биде ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Неважечка низа: мора да започнува со "${i.prefix}"`:i.format==="ends_with"?`Неважечка низа: мора да завршува со "${i.suffix}"`:i.format==="includes"?`Неважечка низа: мора да вклучува "${i.includes}"`:i.format==="regex"?`Неважечка низа: мора да одгоара на патернот ${i.pattern}`:`Invalid ${o[i.format]??n.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${j(n.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${n.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${n.origin}`;default:return"Грешен внес"}}};function Mk(){return{localeError:zk()}}const Dk=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"nombor";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Input tidak sah: dijangka ${n.expected}, diterima ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Input tidak sah: dijangka ${H(n.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Terlalu besar: dijangka ${n.origin??"nilai"} ${a.verb} ${i}${n.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${n.origin??"nilai"} adalah ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Terlalu kecil: dijangka ${n.origin} ${a.verb} ${i}${n.minimum.toString()} ${a.unit}`:`Terlalu kecil: dijangka ${n.origin} adalah ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${o[i.format]??n.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${j(n.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${n.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${n.origin}`;default:return"Input tidak sah"}}};function Uk(){return{localeError:Dk()}}const Lk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"getal";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Ongeldige invoer: verwacht ${n.expected}, ontving ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Ongeldige invoer: verwacht ${H(n.values[0])}`:`Ongeldige optie: verwacht één van ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Te groot: verwacht dat ${n.origin??"waarde"} ${a.verb} ${i}${n.maximum.toString()} ${a.unit??"elementen"}`:`Te groot: verwacht dat ${n.origin??"waarde"} ${i}${n.maximum.toString()} is`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Te klein: verwacht dat ${n.origin} ${a.verb} ${i}${n.minimum.toString()} ${a.unit}`:`Te klein: verwacht dat ${n.origin} ${i}${n.minimum.toString()} is`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${o[i.format]??n.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${n.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${n.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${n.origin}`;default:return"Ongeldige invoer"}}};function Zk(){return{localeError:Lk()}}const Fk=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"tall";case"object":{if(Array.isArray(n))return"liste";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Ugyldig input: forventet ${n.expected}, fikk ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Ugyldig verdi: forventet ${H(n.values[0])}`:`Ugyldig valg: forventet en av ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`For stor(t): forventet ${n.origin??"value"} til å ha ${i}${n.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${n.origin??"value"} til å ha ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`For lite(n): forventet ${n.origin} til å ha ${i}${n.minimum.toString()} ${a.unit}`:`For lite(n): forventet ${n.origin} til å ha ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Ugyldig streng: må starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: må ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: må inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: må matche mønsteret ${i.pattern}`:`Ugyldig ${o[i.format]??n.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${j(n.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${n.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${n.origin}`;default:return"Ugyldig input"}}};function qk(){return{localeError:Fk()}}const Vk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"numara";case"object":{if(Array.isArray(n))return"saf";if(n===null)return"gayb";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Fâsit giren: umulan ${n.expected}, alınan ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Fâsit giren: umulan ${H(n.values[0])}`:`Fâsit tercih: mûteberler ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Fazla büyük: ${n.origin??"value"}, ${i}${n.maximum.toString()} ${a.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${n.origin??"value"}, ${i}${n.maximum.toString()} olmalıydı.`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Fazla küçük: ${n.origin}, ${i}${n.minimum.toString()} ${a.unit} sahip olmalıydı.`:`Fazla küçük: ${n.origin}, ${i}${n.minimum.toString()} olmalıydı.`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Fâsit metin: "${i.prefix}" ile başlamalı.`:i.format==="ends_with"?`Fâsit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`Fâsit metin: "${i.includes}" ihtivâ etmeli.`:i.format==="regex"?`Fâsit metin: ${i.pattern} nakşına uymalı.`:`Fâsit ${o[i.format]??n.format}`}case"not_multiple_of":return`Fâsit sayı: ${n.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`${n.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${n.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function Bk(){return{localeError:Vk()}}const Jk=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"عدد";case"object":{if(Array.isArray(n))return"ارې";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`ناسم ورودي: باید ${n.expected} وای, مګر ${r(n.input)} ترلاسه شو`;case"invalid_value":return n.values.length===1?`ناسم ورودي: باید ${H(n.values[0])} وای`:`ناسم انتخاب: باید یو له ${j(n.values,"|")} څخه وای`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`ډیر لوی: ${n.origin??"ارزښت"} باید ${i}${n.maximum.toString()} ${a.unit??"عنصرونه"} ولري`:`ډیر لوی: ${n.origin??"ارزښت"} باید ${i}${n.maximum.toString()} وي`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`ډیر کوچنی: ${n.origin} باید ${i}${n.minimum.toString()} ${a.unit} ولري`:`ډیر کوچنی: ${n.origin} باید ${i}${n.minimum.toString()} وي`}case"invalid_format":{const i=n;return i.format==="starts_with"?`ناسم متن: باید د "${i.prefix}" سره پیل شي`:i.format==="ends_with"?`ناسم متن: باید د "${i.suffix}" سره پای ته ورسيږي`:i.format==="includes"?`ناسم متن: باید "${i.includes}" ولري`:i.format==="regex"?`ناسم متن: باید د ${i.pattern} سره مطابقت ولري`:`${o[i.format]??n.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${n.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${n.keys.length>1?"کلیډونه":"کلیډ"}: ${j(n.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${n.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${n.origin} کې`;default:return"ناسمه ورودي"}}};function Wk(){return{localeError:Jk()}}const Hk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"liczba";case"object":{if(Array.isArray(n))return"tablica";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${n.expected}, otrzymano ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Nieprawidłowe dane wejściowe: oczekiwano ${H(n.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Za duża wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${i}${n.maximum.toString()} ${a.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Za mała wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${i}${n.minimum.toString()} ${a.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${i.prefix}"`:i.format==="ends_with"?`Nieprawidłowy ciąg znaków: musi kończyć się na "${i.suffix}"`:i.format==="includes"?`Nieprawidłowy ciąg znaków: musi zawierać "${i.includes}"`:i.format==="regex"?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${i.pattern}`:`Nieprawidłow(y/a/e) ${o[i.format]??n.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${n.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${n.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${n.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function Gk(){return{localeError:Hk()}}const Kk=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"número";case"object":{if(Array.isArray(n))return"array";if(n===null)return"nulo";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Tipo inválido: esperado ${n.expected}, recebido ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Entrada inválida: esperado ${H(n.values[0])}`:`Opção inválida: esperada uma das ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Muito grande: esperado que ${n.origin??"valor"} tivesse ${i}${n.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${n.origin??"valor"} fosse ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Muito pequeno: esperado que ${n.origin} tivesse ${i}${n.minimum.toString()} ${a.unit}`:`Muito pequeno: esperado que ${n.origin} fosse ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Texto inválido: deve começar com "${i.prefix}"`:i.format==="ends_with"?`Texto inválido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inválido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inválido: deve corresponder ao padrão ${i.pattern}`:`${o[i.format]??n.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${n.divisor}`;case"unrecognized_keys":return`Chave${n.keys.length>1?"s":""} desconhecida${n.keys.length>1?"s":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Chave inválida em ${n.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${n.origin}`;default:return"Campo inválido"}}};function Yk(){return{localeError:Kk()}}function Yd(e,t,r,o){const n=Math.abs(e),i=n%10,a=n%100;return a>=11&&a<=19?o:i===1?t:i>=2&&i<=4?r:o}const Qk=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"число";case"object":{if(Array.isArray(n))return"массив";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Неверный ввод: ожидалось ${n.expected}, получено ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Неверный ввод: ожидалось ${H(n.values[0])}`:`Неверный вариант: ожидалось одно из ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);if(a){const s=Number(n.maximum),l=Yd(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет иметь ${i}${n.maximum.toString()} ${l}`}return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);if(a){const s=Number(n.minimum),l=Yd(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком маленькое значение: ожидалось, что ${n.origin} будет иметь ${i}${n.minimum.toString()} ${l}`}return`Слишком маленькое значение: ожидалось, что ${n.origin} будет ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Неверная строка: должна начинаться с "${i.prefix}"`:i.format==="ends_with"?`Неверная строка: должна заканчиваться на "${i.suffix}"`:i.format==="includes"?`Неверная строка: должна содержать "${i.includes}"`:i.format==="regex"?`Неверная строка: должна соответствовать шаблону ${i.pattern}`:`Неверный ${o[i.format]??n.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспознанн${n.keys.length>1?"ые":"ый"} ключ${n.keys.length>1?"и":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${n.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${n.origin}`;default:return"Неверные входные данные"}}};function Xk(){return{localeError:Qk()}}const eE=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"število";case"object":{if(Array.isArray(n))return"tabela";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${n.expected}, prejeto ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Neveljaven vnos: pričakovano ${H(n.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} imelo ${i}${n.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Premajhno: pričakovano, da bo ${n.origin} imelo ${i}${n.minimum.toString()} ${a.unit}`:`Premajhno: pričakovano, da bo ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Neveljaven niz: mora se začeti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se končati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${o[i.format]??n.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${n.divisor}`;case"unrecognized_keys":return`Neprepoznan${n.keys.length>1?"i ključi":" ključ"}: ${j(n.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${n.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${n.origin}`;default:return"Neveljaven vnos"}}};function tE(){return{localeError:eE()}}const rE=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"antal";case"object":{if(Array.isArray(n))return"lista";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${n.expected}, fick ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Ogiltig inmatning: förväntat ${H(n.values[0])}`:`Ogiltigt val: förväntade en av ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`För stor(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.maximum.toString()} ${a.unit??"element"}`:`För stor(t): förväntat ${n.origin??"värdet"} att ha ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`För lite(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.minimum.toString()} ${a.unit}`:`För lite(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Ogiltig sträng: måste börja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig sträng: måste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig sträng: måste innehålla "${i.includes}"`:i.format==="regex"?`Ogiltig sträng: måste matcha mönstret "${i.pattern}"`:`Ogiltig(t) ${o[i.format]??n.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${j(n.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${n.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${n.origin??"värdet"}`;default:return"Ogiltig input"}}};function nE(){return{localeError:rE()}}const oE=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"எண் அல்லாதது":"எண்";case"object":{if(Array.isArray(n))return"அணி";if(n===null)return"வெறுமை";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${n.expected}, பெறப்பட்டது ${r(n.input)}`;case"invalid_value":return n.values.length===1?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${H(n.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${j(n.values,"|")} இல் ஒன்று`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${i}${n.maximum.toString()} ${a.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${i}${n.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${i}${n.minimum.toString()} ${a.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${i}${n.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const i=n;return i.format==="starts_with"?`தவறான சரம்: "${i.prefix}" இல் தொடங்க வேண்டும்`:i.format==="ends_with"?`தவறான சரம்: "${i.suffix}" இல் முடிவடைய வேண்டும்`:i.format==="includes"?`தவறான சரம்: "${i.includes}" ஐ உள்ளடக்க வேண்டும்`:i.format==="regex"?`தவறான சரம்: ${i.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${o[i.format]??n.format}`}case"not_multiple_of":return`தவறான எண்: ${n.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${n.keys.length>1?"கள்":""}: ${j(n.keys,", ")}`;case"invalid_key":return`${n.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${n.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function iE(){return{localeError:oE()}}const aE=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":{if(Array.isArray(n))return"อาร์เรย์ (Array)";if(n===null)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${n.expected} แต่ได้รับ ${r(n.input)}`;case"invalid_value":return n.values.length===1?`ค่าไม่ถูกต้อง: ควรเป็น ${H(n.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"ไม่เกิน":"น้อยกว่า",a=t(n.origin);return a?`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${i} ${n.maximum.toString()} ${a.unit??"รายการ"}`:`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${i} ${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?"อย่างน้อย":"มากกว่า",a=t(n.origin);return a?`น้อยกว่ากำหนด: ${n.origin} ควรมี${i} ${n.minimum.toString()} ${a.unit}`:`น้อยกว่ากำหนด: ${n.origin} ควรมี${i} ${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${i.prefix}"`:i.format==="ends_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${i.suffix}"`:i.format==="includes"?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${i.includes}" อยู่ในข้อความ`:i.format==="regex"?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${i.pattern}`:`รูปแบบไม่ถูกต้อง: ${o[i.format]??n.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${n.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${j(n.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${n.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${n.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function sE(){return{localeError:aE()}}const uE=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},lE=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(o){return e[o]??null}const r={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 o=>{switch(o.code){case"invalid_type":return`Geçersiz değer: beklenen ${o.expected}, alınan ${uE(o.input)}`;case"invalid_value":return o.values.length===1?`Geçersiz değer: beklenen ${H(o.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${j(o.values,"|")}`;case"too_big":{const n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Çok büyük: beklenen ${o.origin??"değer"} ${n}${o.maximum.toString()} ${i.unit??"öğe"}`:`Çok büyük: beklenen ${o.origin??"değer"} ${n}${o.maximum.toString()}`}case"too_small":{const n=o.inclusive?">=":">",i=t(o.origin);return i?`Çok küçük: beklenen ${o.origin} ${n}${o.minimum.toString()} ${i.unit}`:`Çok küçük: beklenen ${o.origin} ${n}${o.minimum.toString()}`}case"invalid_format":{const n=o;return n.format==="starts_with"?`Geçersiz metin: "${n.prefix}" ile başlamalı`:n.format==="ends_with"?`Geçersiz metin: "${n.suffix}" ile bitmeli`:n.format==="includes"?`Geçersiz metin: "${n.includes}" içermeli`:n.format==="regex"?`Geçersiz metin: ${n.pattern} desenine uymalı`:`Geçersiz ${r[n.format]??o.format}`}case"not_multiple_of":return`Geçersiz sayı: ${o.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${o.keys.length>1?"lar":""}: ${j(o.keys,", ")}`;case"invalid_key":return`${o.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${o.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function cE(){return{localeError:lE()}}const dE=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"число";case"object":{if(Array.isArray(n))return"масив";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${n.expected}, отримано ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Неправильні вхідні дані: очікується ${H(n.values[0])}`:`Неправильна опція: очікується одне з ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Занадто велике: очікується, що ${n.origin??"значення"} ${a.verb} ${i}${n.maximum.toString()} ${a.unit??"елементів"}`:`Занадто велике: очікується, що ${n.origin??"значення"} буде ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Занадто мале: очікується, що ${n.origin} ${a.verb} ${i}${n.minimum.toString()} ${a.unit}`:`Занадто мале: очікується, що ${n.origin} буде ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Неправильний рядок: повинен починатися з "${i.prefix}"`:i.format==="ends_with"?`Неправильний рядок: повинен закінчуватися на "${i.suffix}"`:i.format==="includes"?`Неправильний рядок: повинен містити "${i.includes}"`:i.format==="regex"?`Неправильний рядок: повинен відповідати шаблону ${i.pattern}`:`Неправильний ${o[i.format]??n.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${n.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${n.keys.length>1?"і":""}: ${j(n.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${n.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${n.origin}`;default:return"Неправильні вхідні дані"}}};function _v(){return{localeError:dE()}}function pE(){return _v()}const fE=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"نمبر";case"object":{if(Array.isArray(n))return"آرے";if(n===null)return"نل";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`غلط ان پٹ: ${n.expected} متوقع تھا، ${r(n.input)} موصول ہوا`;case"invalid_value":return n.values.length===1?`غلط ان پٹ: ${H(n.values[0])} متوقع تھا`:`غلط آپشن: ${j(n.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`بہت بڑا: ${n.origin??"ویلیو"} کے ${i}${n.maximum.toString()} ${a.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${n.origin??"ویلیو"} کا ${i}${n.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`بہت چھوٹا: ${n.origin} کے ${i}${n.minimum.toString()} ${a.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${n.origin} کا ${i}${n.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const i=n;return i.format==="starts_with"?`غلط سٹرنگ: "${i.prefix}" سے شروع ہونا چاہیے`:i.format==="ends_with"?`غلط سٹرنگ: "${i.suffix}" پر ختم ہونا چاہیے`:i.format==="includes"?`غلط سٹرنگ: "${i.includes}" شامل ہونا چاہیے`:i.format==="regex"?`غلط سٹرنگ: پیٹرن ${i.pattern} سے میچ ہونا چاہیے`:`غلط ${o[i.format]??n.format}`}case"not_multiple_of":return`غلط نمبر: ${n.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${n.keys.length>1?"ز":""}: ${j(n.keys,"، ")}`;case"invalid_key":return`${n.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${n.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function mE(){return{localeError:fE()}}const hE=()=>{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(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"số";case"object":{if(Array.isArray(n))return"mảng";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${n.expected}, nhận được ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Đầu vào không hợp lệ: mong đợi ${H(n.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Quá lớn: mong đợi ${n.origin??"giá trị"} ${a.verb} ${i}${n.maximum.toString()} ${a.unit??"phần tử"}`:`Quá lớn: mong đợi ${n.origin??"giá trị"} ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Quá nhỏ: mong đợi ${n.origin} ${a.verb} ${i}${n.minimum.toString()} ${a.unit}`:`Quá nhỏ: mong đợi ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Chuỗi không hợp lệ: phải bắt đầu bằng "${i.prefix}"`:i.format==="ends_with"?`Chuỗi không hợp lệ: phải kết thúc bằng "${i.suffix}"`:i.format==="includes"?`Chuỗi không hợp lệ: phải bao gồm "${i.includes}"`:i.format==="regex"?`Chuỗi không hợp lệ: phải khớp với mẫu ${i.pattern}`:`${o[i.format]??n.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 ${n.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${j(n.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${n.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 ${n.origin}`;default:return"Đầu vào không hợp lệ"}}};function gE(){return{localeError:hE()}}const vE=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"非数字(NaN)":"数字";case"object":{if(Array.isArray(n))return"数组";if(n===null)return"空值(null)";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`无效输入:期望 ${n.expected},实际接收 ${r(n.input)}`;case"invalid_value":return n.values.length===1?`无效输入:期望 ${H(n.values[0])}`:`无效选项:期望以下之一 ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`数值过大:期望 ${n.origin??"值"} ${i}${n.maximum.toString()} ${a.unit??"个元素"}`:`数值过大:期望 ${n.origin??"值"} ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`数值过小:期望 ${n.origin} ${i}${n.minimum.toString()} ${a.unit}`:`数值过小:期望 ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`无效字符串:必须以 "${i.prefix}" 开头`:i.format==="ends_with"?`无效字符串:必须以 "${i.suffix}" 结尾`:i.format==="includes"?`无效字符串:必须包含 "${i.includes}"`:i.format==="regex"?`无效字符串:必须满足正则表达式 ${i.pattern}`:`无效${o[i.format]??n.format}`}case"not_multiple_of":return`无效数字:必须是 ${n.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${j(n.keys,", ")}`;case"invalid_key":return`${n.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${n.origin} 中包含无效值(value)`;default:return"无效输入"}}};function yE(){return{localeError:vE()}}const bE=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"number";case"object":{if(Array.isArray(n))return"array";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`無效的輸入值:預期為 ${n.expected},但收到 ${r(n.input)}`;case"invalid_value":return n.values.length===1?`無效的輸入值:預期為 ${H(n.values[0])}`:`無效的選項:預期為以下其中之一 ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`數值過大:預期 ${n.origin??"值"} 應為 ${i}${n.maximum.toString()} ${a.unit??"個元素"}`:`數值過大:預期 ${n.origin??"值"} 應為 ${i}${n.maximum.toString()}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`數值過小:預期 ${n.origin} 應為 ${i}${n.minimum.toString()} ${a.unit}`:`數值過小:預期 ${n.origin} 應為 ${i}${n.minimum.toString()}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`無效的字串:必須以 "${i.prefix}" 開頭`:i.format==="ends_with"?`無效的字串:必須以 "${i.suffix}" 結尾`:i.format==="includes"?`無效的字串:必須包含 "${i.includes}"`:i.format==="regex"?`無效的字串:必須符合格式 ${i.pattern}`:`無效的 ${o[i.format]??n.format}`}case"not_multiple_of":return`無效的數字:必須為 ${n.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${n.keys.length>1?"們":""}:${j(n.keys,"、")}`;case"invalid_key":return`${n.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${n.origin} 中有無效的值`;default:return"無效的輸入值"}}};function _E(){return{localeError:bE()}}const wE=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(n){return e[n]??null}const r=n=>{const i=typeof n;switch(i){case"number":return Number.isNaN(n)?"NaN":"nọ́mbà";case"object":{if(Array.isArray(n))return"akopọ";if(n===null)return"null";if(Object.getPrototypeOf(n)!==Object.prototype&&n.constructor)return n.constructor.name}}return i},o={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 n=>{switch(n.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${n.expected}, àmọ̀ a rí ${r(n.input)}`;case"invalid_value":return n.values.length===1?`Ìbáwọlé aṣìṣe: a ní láti fi ${H(n.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${j(n.values,"|")}`;case"too_big":{const i=n.inclusive?"<=":"<",a=t(n.origin);return a?`Tó pọ̀ jù: a ní láti jẹ́ pé ${n.origin??"iye"} ${a.verb} ${i}${n.maximum} ${a.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${i}${n.maximum}`}case"too_small":{const i=n.inclusive?">=":">",a=t(n.origin);return a?`Kéré ju: a ní láti jẹ́ pé ${n.origin} ${a.verb} ${i}${n.minimum} ${a.unit}`:`Kéré ju: a ní láti jẹ́ ${i}${n.minimum}`}case"invalid_format":{const i=n;return i.format==="starts_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${i.prefix}"`:i.format==="ends_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${i.suffix}"`:i.format==="includes"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${i.includes}"`:i.format==="regex"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${i.pattern}`:`Aṣìṣe: ${o[i.format]??n.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${n.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${j(n.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${n.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${n.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function xE(){return{localeError:wE()}}const wv=Object.freeze(Object.defineProperty({__proto__:null,ar:zI,az:DI,be:LI,bg:qI,ca:BI,cs:WI,da:GI,de:YI,en:yv,eo:rk,es:ok,fa:ak,fi:uk,fr:ck,frCA:pk,he:mk,hu:gk,id:yk,is:wk,it:$k,ja:Ik,ka:Tk,kh:Nk,km:bv,ko:Ck,lt:Rk,mk:Mk,ms:Uk,nl:Zk,no:qk,ota:Bk,pl:Gk,ps:Wk,pt:Yk,ru:Xk,sl:tE,sv:nE,ta:iE,th:sE,tr:cE,ua:pE,uk:_v,ur:mE,vi:gE,yo:xE,zhCN:yE,zhTW:_E},Symbol.toStringTag,{value:"Module"}));var Qd;const xv=Symbol("ZodOutput"),$v=Symbol("ZodInput");class Sv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const o=r[0];if(this._map.set(t,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,t)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const o={...this.get(r)??{}};delete o.id;const n={...o,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function ul(){return new Sv}(Qd=globalThis).__zod_globalRegistry??(Qd.__zod_globalRegistry=ul());const wt=globalThis.__zod_globalRegistry;function Iv(e,t){return new e({type:"string",...P(t)})}function kv(e,t){return new e({type:"string",coerce:!0,...P(t)})}function ll(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function mi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function cl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function dl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function pl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function fl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Xi(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function ml(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function hl(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function gl(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function vl(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function yl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function bl(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function _l(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function wl(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function xl(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Ev(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...P(t)})}function $l(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Sl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Il(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function kl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function El(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function Tl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}const Tv={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Ov(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Nv(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function Pv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function Cv(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function jv(e,t){return new e({type:"number",checks:[],...P(t)})}function Av(e,t){return new e({type:"number",coerce:!0,checks:[],...P(t)})}function Rv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function zv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...P(t)})}function Mv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...P(t)})}function Dv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...P(t)})}function Uv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...P(t)})}function Lv(e,t){return new e({type:"boolean",...P(t)})}function Zv(e,t){return new e({type:"boolean",coerce:!0,...P(t)})}function Fv(e,t){return new e({type:"bigint",...P(t)})}function qv(e,t){return new e({type:"bigint",coerce:!0,...P(t)})}function Vv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...P(t)})}function Bv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...P(t)})}function Jv(e,t){return new e({type:"symbol",...P(t)})}function Wv(e,t){return new e({type:"undefined",...P(t)})}function Hv(e,t){return new e({type:"null",...P(t)})}function Gv(e){return new e({type:"any"})}function Kv(e){return new e({type:"unknown"})}function Yv(e,t){return new e({type:"never",...P(t)})}function Qv(e,t){return new e({type:"void",...P(t)})}function Xv(e,t){return new e({type:"date",...P(t)})}function ey(e,t){return new e({type:"date",coerce:!0,...P(t)})}function ty(e,t){return new e({type:"nan",...P(t)})}function ir(e,t){return new el({check:"less_than",...P(t),value:e,inclusive:!1})}function st(e,t){return new el({check:"less_than",...P(t),value:e,inclusive:!0})}function ar(e,t){return new tl({check:"greater_than",...P(t),value:e,inclusive:!1})}function We(e,t){return new tl({check:"greater_than",...P(t),value:e,inclusive:!0})}function Ol(e){return ar(0,e)}function Nl(e){return ir(0,e)}function Pl(e){return st(0,e)}function Cl(e){return We(0,e)}function Kr(e,t){return new Uh({check:"multiple_of",...P(t),value:e})}function uo(e,t){return new Fh({check:"max_size",...P(t),maximum:e})}function Yr(e,t){return new qh({check:"min_size",...P(t),minimum:e})}function ea(e,t){return new Vh({check:"size_equals",...P(t),size:e})}function lo(e,t){return new Bh({check:"max_length",...P(t),maximum:e})}function br(e,t){return new Jh({check:"min_length",...P(t),minimum:e})}function co(e,t){return new Wh({check:"length_equals",...P(t),length:e})}function ta(e,t){return new Hh({check:"string_format",format:"regex",...P(t),pattern:e})}function ra(e){return new Gh({check:"string_format",format:"lowercase",...P(e)})}function na(e){return new Kh({check:"string_format",format:"uppercase",...P(e)})}function oa(e,t){return new Yh({check:"string_format",format:"includes",...P(t),includes:e})}function ia(e,t){return new Qh({check:"string_format",format:"starts_with",...P(t),prefix:e})}function aa(e,t){return new Xh({check:"string_format",format:"ends_with",...P(t),suffix:e})}function jl(e,t,r){return new eg({check:"property",property:e,schema:t,...P(r)})}function sa(e,t){return new tg({check:"mime_type",mime:e,...P(t)})}function Ht(e){return new rg({check:"overwrite",tx:e})}function ua(e){return Ht(t=>t.normalize(e))}function la(){return Ht(e=>e.trim())}function ca(){return Ht(e=>e.toLowerCase())}function da(){return Ht(e=>e.toUpperCase())}function pa(){return Ht(e=>Rm(e))}function ry(e,t,r){return new e({type:"array",element:t,...P(r)})}function $E(e,t,r){return new e({type:"union",options:t,...P(r)})}function SE(e,t,r){return new e({type:"union",options:t,inclusive:!1,...P(r)})}function IE(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...P(o)})}function kE(e,t,r){return new e({type:"intersection",left:t,right:r})}function EE(e,t,r,o){const n=r instanceof X,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...P(i)})}function TE(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...P(o)})}function OE(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...P(o)})}function NE(e,t,r){return new e({type:"set",valueType:t,...P(r)})}function PE(e,t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...P(r)})}function CE(e,t,r){return new e({type:"enum",entries:t,...P(r)})}function jE(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...P(r)})}function ny(e,t){return new e({type:"file",...P(t)})}function AE(e,t){return new e({type:"transform",transform:t})}function RE(e,t){return new e({type:"optional",innerType:t})}function zE(e,t){return new e({type:"nullable",innerType:t})}function ME(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Gi(r)}})}function DE(e,t,r){return new e({type:"nonoptional",innerType:t,...P(r)})}function UE(e,t){return new e({type:"success",innerType:t})}function LE(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function ZE(e,t,r){return new e({type:"pipe",in:t,out:r})}function FE(e,t){return new e({type:"readonly",innerType:t})}function qE(e,t,r){return new e({type:"template_literal",parts:t,...P(r)})}function VE(e,t){return new e({type:"lazy",getter:t})}function BE(e,t){return new e({type:"promise",innerType:t})}function oy(e,t,r){const o=P(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function iy(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function ay(e){const t=sy(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Hr(o,r.value,t._zod.def));else{const n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(Hr(n))}},e(r.value,r)));return t}function sy(e,t){const r=new Se({check:"custom",...P(t)});return r._zod.check=e,r}function uy(e){const t=new Se({check:"describe"});return t._zod.onattach=[r=>{const o=wt.get(r)??{};wt.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function ly(e){const t=new Se({check:"meta"});return t._zod.onattach=[r=>{const o=wt.get(r)??{};wt.add(r,{...o,...e})}],t._zod.check=()=>{},t}function cy(e,t){const r=P(t);let o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));const i=new Set(o),a=new Set(n),s=e.Codec??sl,l=e.Boolean??ol,u=e.String??so,c=new u({type:"string",error:r.error}),d=new l({type:"boolean",error:r.error}),f=new s({type:"pipe",in:c,out:d,transform:((p,g)=>{let h=p;return r.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:a.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((p,g)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f}function po(e,t,r,o={}){const n=P(o),i={...P(o),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Qr(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??wt,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 he(e,t,r={path:[],schemaPath:[]}){var o;const n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const c={...r,schemaPath:[...r.schemaPath,e],path:r.path},d=e._zod.parent;if(d)a.ref=d,he(d,t,c),t.seen.get(d).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,c);else{const f=a.schema,p=t.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(e,t,f,c)}}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),t.io==="input"&&Ve(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Xr(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=i=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const c=e.external.registry.get(i[0])?.id,d=e.external.uri??(p=>p);if(c)return{ref:d(c)};const f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${d("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};const l=`#/${a}/`,u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+u}},n=i=>{if(i[1].schema.$ref)return;const a=i[1],{ref:s,defId:l}=o(i);a.def={...a.schema},l&&(a.defId=l);const u=a.schema;for(const c in u)delete u[c];u.$ref=s};if(e.cycles==="throw")for(const i of e.seen.entries()){const a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
27
|
+
`)}p.write("payload.value = newResult;"),p.write("return payload;");const x=p.compile();return(S,b)=>x(f,S,b)};let o;const a=Kr,s=!Wa.jitless,l=s&&Hy.value,c=t.catchall;let d;e._zod.parse=(f,p)=>{d??(d=i.value);const g=f.value;return a(g)?s&&l&&p?.async===!1&&p.jitless!==!0?(o||(o=r(t.shape)),f=o(f,p),c?ew([],g,f,p,d,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f)}});function Dh(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=>!ur(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(a=>Ut(a,i,tt())))}),t)}const Fs=R("$ZodUnion",(e,t)=>{ce.init(e,t),ge(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ge(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ge(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ge(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=>zs(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 a=!1;const s=[];for(const u of t.options){const l=u._zod.run({value:r.value,issues:[]},o);if(l instanceof Promise)s.push(l),a=!0;else{if(l.issues.length===0)return l;s.push(l)}}return a?Promise.all(s).then(u=>Dh(u,r,e,o)):Dh(s,r,e,o)}});function Uh(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(a=>Ut(a,i,tt())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const rw=R("$ZodXor",(e,t)=>{Fs.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 a=!1;const s=[];for(const u of t.options){const l=u._zod.run({value:r.value,issues:[]},o);l instanceof Promise?(s.push(l),a=!0):s.push(l)}return a?Promise.all(s).then(u=>Uh(u,r,e,o)):Uh(s,r,e,o)}}),iw=R("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fs.init(e,t);const n=e._zod.parse;ge(e._zod,"propValues",()=>{const r={};for(const o of t.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const[s,u]of Object.entries(a)){r[s]||(r[s]=new Set);for(const l of u)r[s].add(l)}}return r});const i=vo(()=>{const r=t.options,o=new Map;for(const a of r){const s=a._zod.propValues?.[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const u of s){if(o.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,a)}}return o});e._zod.parse=(r,o)=>{const a=r.value;if(!Kr(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const s=i.value.get(a?.[t.discriminator]);return s?s._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r)}}),ow=R("$ZodIntersection",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>{const r=n.value,o=t.left._zod.run({value:r,issues:[]},i),a=t.right._zod.run({value:r,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([u,l])=>Lh(n,u,l)):Lh(n,o,a)}});function fc(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(mr(e)&&mr(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 a=fc(e[o],t[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r[o]=a.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],a=fc(r,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Lh(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),ur(e))return e;const i=fc(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 jd=R("$ZodTuple",(e,t)=>{ce.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 a=[],s=[...n].reverse().findIndex(c=>c._zod.optin!=="optional"),u=s===-1?0:n.length-s;if(!t.rest){const c=o.length>n.length,d=o.length<u-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 l=-1;for(const c of n){if(l++,l>=o.length&&l>=u)continue;const d=c._zod.run({value:o[l],issues:[]},r);d instanceof Promise?a.push(d.then(f=>ca(f,i,l))):ca(d,i,l)}if(t.rest){const c=o.slice(n.length);for(const d of c){l++;const f=t.rest._zod.run({value:d,issues:[]},r);f instanceof Promise?a.push(f.then(p=>ca(p,i,l))):ca(f,i,l)}}return a.length?Promise.all(a).then(()=>i):i}});function ca(e,t,n){e.issues.length&&t.issues.push(...Kt(n,e.issues)),t.value[n]=e.value}const aw=R("$ZodRecord",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!mr(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a){n.value={};const s=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){s.add(typeof l=="number"?l.toString():l);const c=t.valueType._zod.run({value:r[l],issues:[]},i);c instanceof Promise?o.push(c.then(d=>{d.issues.length&&n.issues.push(...Kt(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...Kt(l,c.issues)),n.value[l]=c.value)}let u;for(const l in r)s.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{n.value={};for(const s of Reflect.ownKeys(r)){if(s==="__proto__")continue;const u=t.keyType._zod.run({value:s,issues:[]},i);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){t.mode==="loose"?n.value[s]=r[s]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(c=>Ut(c,i,tt())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:r[s],issues:[]},i);l instanceof Promise?o.push(l.then(c=>{c.issues.length&&n.issues.push(...Kt(s,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...Kt(s,l.issues)),n.value[u.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),sw=R("$ZodMap",(e,t)=>{ce.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[a,s]of r){const u=t.keyType._zod.run({value:a,issues:[]},i),l=t.valueType._zod.run({value:s,issues:[]},i);u instanceof Promise||l instanceof Promise?o.push(Promise.all([u,l]).then(([c,d])=>{Fh(c,d,n,a,r,e,i)})):Fh(u,l,n,a,r,e,i)}return o.length?Promise.all(o).then(()=>n):n}});function Fh(e,t,n,i,r,o,a){e.issues.length&&(Ka.has(typeof i)?n.issues.push(...Kt(i,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:e.issues.map(s=>Ut(s,a,tt()))})),t.issues.length&&(Ka.has(typeof i)?n.issues.push(...Kt(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(s=>Ut(s,a,tt()))})),n.value.set(e.value,t.value)}const lw=R("$ZodSet",(e,t)=>{ce.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 a of r){const s=t.valueType._zod.run({value:a,issues:[]},i);s instanceof Promise?o.push(s.then(u=>Bh(u,n))):Bh(s,n)}return o.length?Promise.all(o).then(()=>n):n}});function Bh(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const uw=R("$ZodEnum",(e,t)=>{ce.init(e,t);const n=hd(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(r=>Ka.has(typeof r)).map(r=>typeof r=="string"?An(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const a=r.value;return i.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),cw=R("$ZodLiteral",(e,t)=>{if(ce.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"?An(i):i?An(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}}),dw=R("$ZodFile",(e,t)=>{ce.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}}),pw=R("$ZodTransform",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ms(e.constructor.name);const r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(a=>(n.value=a,n));if(r instanceof Promise)throw new fr;return n.value=r,n}});function Zh(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const fw=R("$ZodOptional",(e,t)=>{ce.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ge(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ge(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${zs(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=>Zh(o,n.value)):Zh(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),hw=R("$ZodNullable",(e,t)=>{ce.init(e,t),ge(e._zod,"optin",()=>t.innerType._zod.optin),ge(e._zod,"optout",()=>t.innerType._zod.optout),ge(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${zs(n.source)}|null)$`):void 0}),ge(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)}),mw=R("$ZodDefault",(e,t)=>{ce.init(e,t),e._zod.optin="optional",ge(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=>qh(o,t)):qh(r,t)}});function qh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const gw=R("$ZodPrefault",(e,t)=>{ce.init(e,t),e._zod.optin="optional",ge(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))}),vw=R("$ZodNonOptional",(e,t)=>{ce.init(e,t),ge(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=>Vh(o,e)):Vh(r,e)}});function Vh(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 yw=R("$ZodSuccess",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ms("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)}}),bw=R("$ZodCatch",(e,t)=>{ce.init(e,t),ge(e._zod,"optin",()=>t.innerType._zod.optin),ge(e._zod,"optout",()=>t.innerType._zod.optout),ge(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(a=>Ut(a,i,tt()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>Ut(o,i,tt()))},input:n.value}),n.issues=[]),n)}}),_w=R("$ZodNaN",(e,t)=>{ce.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)}),ww=R("$ZodPipe",(e,t)=>{ce.init(e,t),ge(e._zod,"values",()=>t.in._zod.values),ge(e._zod,"optin",()=>t.in._zod.optin),ge(e._zod,"optout",()=>t.out._zod.optout),ge(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(a=>da(a,t.in,i)):da(o,t.in,i)}const r=t.in._zod.run(n,i);return r instanceof Promise?r.then(o=>da(o,t.out,i)):da(r,t.out,i)}});function da(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Md=R("$ZodCodec",(e,t)=>{ce.init(e,t),ge(e._zod,"values",()=>t.in._zod.values),ge(e._zod,"optin",()=>t.in._zod.optin),ge(e._zod,"optout",()=>t.out._zod.optout),ge(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(a=>pa(a,t,i)):pa(o,t,i)}else{const o=t.out._zod.run(n,i);return o instanceof Promise?o.then(a=>pa(a,t,i)):pa(o,t,i)}}});function pa(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=>fa(e,o,t.out,n)):fa(e,r,t.out,n)}else{const r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(o=>fa(e,o,t.in,n)):fa(e,r,t.in,n)}}function fa(e,t,n,i){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},i)}const xw=R("$ZodReadonly",(e,t)=>{ce.init(e,t),ge(e._zod,"propValues",()=>t.innerType._zod.propValues),ge(e._zod,"values",()=>t.innerType._zod.values),ge(e._zod,"optin",()=>t.innerType?._zod?.optin),ge(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(Hh):Hh(r)}});function Hh(e){return e.value=Object.freeze(e.value),e}const Sw=R("$ZodTemplateLiteral",(e,t)=>{ce.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,a=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(o,a))}else if(i===null||Jy.has(typeof i))n.push(An(`${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)}),Iw=R("$ZodFunction",(e,t)=>(ce.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?dc(e._def.input,i):i,o=Reflect.apply(n,this,r);return e._def.output?dc(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 pc(e._def.input,i):i,o=await Reflect.apply(n,this,r);return e._def.output?await pc(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 jd({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)),kw=R("$ZodPromise",(e,t)=>{ce.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then(r=>t.innerType._zod.run({value:r,issues:[]},i))}),Ew=R("$ZodLazy",(e,t)=>{ce.init(e,t),ge(e._zod,"innerType",()=>t.getter()),ge(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ge(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ge(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ge(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,i)=>e._zod.innerType._zod.run(n,i)}),Tw=R("$ZodCustom",(e,t)=>{De.init(e,t),ce.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=>Jh(o,n,i,e));Jh(r,n,i,e)}});function Jh(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(Yr(r))}}const jP=()=>{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?`مدخلات غير مقبولة: يفترض إدخال ${oe(r.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?` أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()} ${a.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`أصغر من اللازم: يفترض لـ ${r.origin} أن يكون ${o} ${r.minimum.toString()} ${a.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 MP(){return{localeError:jP()}}const zP=()=>{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 ${oe(r.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Çox böyük: gözlənilən ${r.origin??"dəyər"} ${o}${r.maximum.toString()} ${a.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?">=":">",a=t(r.origin);return a?`Çox kiçik: gözlənilən ${r.origin} ${o}${r.minimum.toString()} ${a.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 DP(){return{localeError:zP()}}function Wh(e,t,n,i){const r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}const UP=()=>{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?`Няправільны ўвод: чакалася ${oe(r.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);if(a){const s=Number(r.maximum),u=Wh(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна ${a.verb} ${o}${r.maximum.toString()} ${u}`}return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна быць ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);if(a){const s=Number(r.minimum),u=Wh(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта малы: чакалася, што ${r.origin} павінна ${a.verb} ${o}${r.minimum.toString()} ${u}`}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 LP(){return{localeError:UP()}}const FP=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},BP=()=>{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}, получен ${FP(i.input)}`;case"invalid_value":return i.values.length===1?`Невалиден вход: очакван ${oe(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 ZP(){return{localeError:BP()}}const qP=()=>{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 ${oe(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",a=t(r.origin);return a?`Massa gran: s'esperava que ${r.origin??"el valor"} contingués ${o} ${r.maximum.toString()} ${a.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",a=t(r.origin);return a?`Massa petit: s'esperava que ${r.origin} contingués ${o} ${r.minimum.toString()} ${a.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 VP(){return{localeError:qP()}}const HP=()=>{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 ${oe(r.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Hodnota je příliš velká: ${r.origin??"hodnota"} musí mít ${o}${r.maximum.toString()} ${a.unit??"prvků"}`:`Hodnota je příliš velká: ${r.origin??"hodnota"} musí být ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Hodnota je příliš malá: ${r.origin??"hodnota"} musí mít ${o}${r.minimum.toString()} ${a.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 JP(){return{localeError:HP()}}const WP=()=>{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(a){return e[a]??null}function i(a){return t[a]??a}const r=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"tal";case"object":return Array.isArray(a)?"liste":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype&&a.constructor?a.constructor.name:"objekt"}return s},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 a=>{switch(a.code){case"invalid_type":return`Ugyldigt input: forventede ${i(a.expected)}, fik ${i(r(a.input))}`;case"invalid_value":return a.values.length===1?`Ugyldig værdi: forventede ${oe(a.values[0])}`:`Ugyldigt valg: forventede en af følgende ${q(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",u=n(a.origin),l=i(a.origin);return u?`For stor: forventede ${l??"value"} ${u.verb} ${s} ${a.maximum.toString()} ${u.unit??"elementer"}`:`For stor: forventede ${l??"value"} havde ${s} ${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",u=n(a.origin),l=i(a.origin);return u?`For lille: forventede ${l} ${u.verb} ${s} ${a.minimum.toString()} ${u.unit}`:`For lille: forventede ${l} havde ${s} ${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Ugyldig streng: skal starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: skal ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: skal indeholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: skal matche mønsteret ${s.pattern}`:`Ugyldig ${o[s.format]??a.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${q(a.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${a.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${a.origin}`;default:return"Ugyldigt input"}}};function GP(){return{localeError:WP()}}const KP=()=>{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 ${oe(r.values[0])}`:`Ungültige Option: erwartet eine von ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ist`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ${a.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 YP(){return{localeError:KP()}}const QP=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},XP=()=>{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 ${QP(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${oe(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 $w(){return{localeError:XP()}}const e1=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},t1=()=>{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 ${e1(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendiĝis ${oe(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 n1(){return{localeError:t1()}}const r1=()=>{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(a){return e[a]??null}function i(a){return t[a]??a}const r=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"number";case"object":return Array.isArray(a)?"array":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype?a.constructor.name:"object"}return s},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 a=>{switch(a.code){case"invalid_type":return`Entrada inválida: se esperaba ${i(a.expected)}, recibido ${i(r(a.input))}`;case"invalid_value":return a.values.length===1?`Entrada inválida: se esperaba ${oe(a.values[0])}`:`Opción inválida: se esperaba una de ${q(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",u=n(a.origin),l=i(a.origin);return u?`Demasiado grande: se esperaba que ${l??"valor"} tuviera ${s}${a.maximum.toString()} ${u.unit??"elementos"}`:`Demasiado grande: se esperaba que ${l??"valor"} fuera ${s}${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",u=n(a.origin),l=i(a.origin);return u?`Demasiado pequeño: se esperaba que ${l} tuviera ${s}${a.minimum.toString()} ${u.unit}`:`Demasiado pequeño: se esperaba que ${l} fuera ${s}${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Cadena inválida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inválida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inválida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inválida: debe coincidir con el patrón ${s.pattern}`:`Inválido ${o[s.format]??a.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${a.divisor}`;case"unrecognized_keys":return`Llave${a.keys.length>1?"s":""} desconocida${a.keys.length>1?"s":""}: ${q(a.keys,", ")}`;case"invalid_key":return`Llave inválida en ${i(a.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${i(a.origin)}`;default:return"Entrada inválida"}}};function i1(){return{localeError:r1()}}const o1=()=>{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?`ورودی نامعتبر: میبایست ${oe(r.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${q(r.values,"|")} میبود`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} ${a.unit??"عنصر"} باشد`:`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} باشد`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`خیلی کوچک: ${r.origin} باید ${o}${r.minimum.toString()} ${a.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 a1(){return{localeError:o1()}}const s1=()=>{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 ${oe(r.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Liian suuri: ${a.subject} täytyy olla ${o}${r.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon täytyy olla ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Liian pieni: ${a.subject} täytyy olla ${o}${r.minimum.toString()} ${a.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 l1(){return{localeError:s1()}}const u1=()=>{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 : ${oe(r.values[0])} attendu`:`Option invalide : une valeur parmi ${q(r.values,"|")} attendue`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Trop grand : ${r.origin??"valeur"} doit ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"élément(s)"}`:`Trop grand : ${r.origin??"valeur"} doit être ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Trop petit : ${r.origin} doit ${a.verb} ${o}${r.minimum.toString()} ${a.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 c1(){return{localeError:u1()}}const d1=()=>{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 ${oe(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"≤":"<",a=t(r.origin);return a?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${o}${r.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"≥":">",a=t(r.origin);return a?`Trop petit : attendu que ${r.origin} ait ${o}${r.minimum.toString()} ${a.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 p1(){return{localeError:d1()}}const f1=()=>{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=l=>l?e[l]:void 0,i=l=>{const c=n(l);return c?c.label:l??e.unknown.label},r=l=>`ה${i(l)}`,o=l=>(n(l)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",a=l=>l?t[l]??null:null,s=l=>{const c=typeof l;switch(c){case"number":return Number.isNaN(l)?"NaN":"number";case"object":return Array.isArray(l)?"array":l===null?"null":Object.getPrototypeOf(l)!==Object.prototype&&l.constructor?l.constructor.name:"object";default:return c}},u={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 l=>{switch(l.code){case"invalid_type":{const c=l.expected,d=i(c),f=s(l.input),p=e[f]?.label??f;return`קלט לא תקין: צריך להיות ${d}, התקבל ${p}`}case"invalid_value":{if(l.values.length===1)return`ערך לא תקין: הערך חייב להיות ${oe(l.values[0])}`;const c=l.values.map(p=>oe(p));if(l.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=a(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${c?.longLabel??"ארוך"} מדי: ${d} צריכה להכיל ${l.maximum.toString()} ${c?.unit??""} ${l.inclusive?"או פחות":"לכל היותר"}`.trim();if(l.origin==="number"){const g=l.inclusive?`קטן או שווה ל-${l.maximum}`:`קטן מ-${l.maximum}`;return`גדול מדי: ${d} צריך להיות ${g}`}if(l.origin==="array"||l.origin==="set"){const g=l.origin==="set"?"צריכה":"צריך",m=l.inclusive?`${l.maximum} ${c?.unit??""} או פחות`:`פחות מ-${l.maximum} ${c?.unit??""}`;return`גדול מדי: ${d} ${g} להכיל ${m}`.trim()}const f=l.inclusive?"<=":"<",p=o(l.origin??"value");return c?.unit?`${c.longLabel} מדי: ${d} ${p} ${f}${l.maximum.toString()} ${c.unit}`:`${c?.longLabel??"גדול"} מדי: ${d} ${p} ${f}${l.maximum.toString()}`}case"too_small":{const c=a(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${c?.shortLabel??"קצר"} מדי: ${d} צריכה להכיל ${l.minimum.toString()} ${c?.unit??""} ${l.inclusive?"או יותר":"לפחות"}`.trim();if(l.origin==="number"){const g=l.inclusive?`גדול או שווה ל-${l.minimum}`:`גדול מ-${l.minimum}`;return`קטן מדי: ${d} צריך להיות ${g}`}if(l.origin==="array"||l.origin==="set"){const g=l.origin==="set"?"צריכה":"צריך";if(l.minimum===1&&l.inclusive){const y=(l.origin==="set","לפחות פריט אחד");return`קטן מדי: ${d} ${g} להכיל ${y}`}const m=l.inclusive?`${l.minimum} ${c?.unit??""} או יותר`:`יותר מ-${l.minimum} ${c?.unit??""}`;return`קטן מדי: ${d} ${g} להכיל ${m}`.trim()}const f=l.inclusive?">=":">",p=o(l.origin??"value");return c?.unit?`${c.shortLabel} מדי: ${d} ${p} ${f}${l.minimum.toString()} ${c.unit}`:`${c?.shortLabel??"קטן"} מדי: ${d} ${p} ${f}${l.minimum.toString()}`}case"invalid_format":{const c=l;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=u[c.format],f=d?.label??c.format,g=(d?.gender??"m")==="f"?"תקינה":"תקין";return`${f} לא ${g}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${l.divisor}`;case"unrecognized_keys":return`מפתח${l.keys.length>1?"ות":""} לא מזוה${l.keys.length>1?"ים":"ה"}: ${q(l.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${r(l.origin??"array")}`;default:return"קלט לא תקין"}}};function h1(){return{localeError:f1()}}const m1=()=>{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 ${oe(r.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Túl nagy: ${r.origin??"érték"} mérete túl nagy ${o}${r.maximum.toString()} ${a.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?">=":">",a=t(r.origin);return a?`Túl kicsi: a bemeneti érték ${r.origin} mérete túl kicsi ${o}${r.minimum.toString()} ${a.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 g1(){return{localeError:m1()}}const v1=()=>{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 ${oe(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: diharapkan ${r.origin} memiliki ${o}${r.minimum.toString()} ${a.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 y1(){return{localeError:v1()}}const b1=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},_1=()=>{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 ${b1(i.input)} þar sem á að vera ${i.expected}`;case"invalid_value":return i.values.length===1?`Rangt gildi: gert ráð fyrir ${oe(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 w1(){return{localeError:_1()}}const x1=()=>{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 ${oe(r.values[0])}`:`Opzione non valida: atteso uno tra ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Troppo grande: ${r.origin??"valore"} deve avere ${o}${r.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Troppo piccolo: ${r.origin} deve avere ${o}${r.minimum.toString()} ${a.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 S1(){return{localeError:x1()}}const I1=()=>{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?`無効な入力: ${oe(r.values[0])}が期待されました`:`無効な選択: ${q(r.values,"、")}のいずれかである必要があります`;case"too_big":{const o=r.inclusive?"以下である":"より小さい",a=t(r.origin);return a?`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${a.unit??"要素"}${o}必要があります`:`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${o}必要があります`}case"too_small":{const o=r.inclusive?"以上である":"より大きい",a=t(r.origin);return a?`小さすぎる値: ${r.origin}は${r.minimum.toString()}${a.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 k1(){return{localeError:I1()}}const E1=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},T1=()=>{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}, მიღებული ${E1(i.input)}`;case"invalid_value":return i.values.length===1?`არასწორი შეყვანა: მოსალოდნელი ${oe(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 $1(){return{localeError:T1()}}const C1=()=>{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?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${oe(r.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()} ${a.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`តូចពេក៖ ត្រូវការ ${r.origin} ${o} ${r.minimum.toString()} ${a.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 Cw(){return{localeError:C1()}}function A1(){return Cw()}const P1=()=>{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?`잘못된 입력: 값은 ${oe(r.values[0])} 이어야 합니다`:`잘못된 옵션: ${q(r.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const o=r.inclusive?"이하":"미만",a=o==="미만"?"이어야 합니다":"여야 합니다",s=t(r.origin),u=s?.unit??"요소";return s?`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()}${u} ${o}${a}`:`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()} ${o}${a}`}case"too_small":{const o=r.inclusive?"이상":"초과",a=o==="이상"?"이어야 합니다":"여야 합니다",s=t(r.origin),u=s?.unit??"요소";return s?`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()}${u} ${o}${a}`:`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()} ${o}${a}`}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 R1(){return{localeError:P1()}}const O1=e=>Ai(typeof e,e),Ai=(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},wi=e=>e.charAt(0).toUpperCase()+e.slice(1);function Gh(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 N1=()=>{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,a){const s=e[i]??null;return s===null?s:{unit:s.unit[r],verb:s.verb[a][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 ${O1(i.input)}, o tikėtasi - ${Ai(i.expected)}`;case"invalid_value":return i.values.length===1?`Privalo būti ${oe(i.values[0])}`:`Privalo būti vienas iš ${q(i.values,"|")} pasirinkimų`;case"too_big":{const r=Ai(i.origin),o=t(i.origin,Gh(Number(i.maximum)),i.inclusive??!1,"smaller");if(o?.verb)return`${wi(r??i.origin??"reikšmė")} ${o.verb} ${i.maximum.toString()} ${o.unit??"elementų"}`;const a=i.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${wi(r??i.origin??"reikšmė")} turi būti ${a} ${i.maximum.toString()} ${o?.unit}`}case"too_small":{const r=Ai(i.origin),o=t(i.origin,Gh(Number(i.minimum)),i.inclusive??!1,"bigger");if(o?.verb)return`${wi(r??i.origin??"reikšmė")} ${o.verb} ${i.minimum.toString()} ${o.unit??"elementų"}`;const a=i.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${wi(r??i.origin??"reikšmė")} turi būti ${a} ${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=Ai(i.origin);return`${wi(r??i.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function j1(){return{localeError:N1()}}const M1=()=>{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 ${oe(r.values[0])}`:`Грешана опција: се очекува една ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Премногу голем: се очекува ${r.origin??"вредноста"} да има ${o}${r.maximum.toString()} ${a.unit??"елементи"}`:`Премногу голем: се очекува ${r.origin??"вредноста"} да биде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Премногу мал: се очекува ${r.origin} да има ${o}${r.minimum.toString()} ${a.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 z1(){return{localeError:M1()}}const D1=()=>{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 ${oe(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: dijangka ${r.origin??"nilai"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: dijangka ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.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 U1(){return{localeError:D1()}}const L1=()=>{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 ${oe(r.values[0])}`:`Ongeldige optie: verwacht één van ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Te groot: verwacht dat ${r.origin??"waarde"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"elementen"}`:`Te groot: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} is`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Te klein: verwacht dat ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.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 F1(){return{localeError:L1()}}const B1=()=>{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 ${oe(r.values[0])}`:`Ugyldig valg: forventet en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`For lite(n): forventet ${r.origin} til å ha ${o}${r.minimum.toString()} ${a.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 Z1(){return{localeError:B1()}}const q1=()=>{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 ${oe(r.values[0])}`:`Fâsit tercih: mûteberler ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Fazla büyük: ${r.origin??"value"}, ${o}${r.maximum.toString()} ${a.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?">=":">",a=t(r.origin);return a?`Fazla küçük: ${r.origin}, ${o}${r.minimum.toString()} ${a.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 V1(){return{localeError:q1()}}const H1=()=>{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?`ناسم ورودي: باید ${oe(r.values[0])} وای`:`ناسم انتخاب: باید یو له ${q(r.values,"|")} څخه وای`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} ${a.unit??"عنصرونه"} ولري`:`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} وي`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`ډیر کوچنی: ${r.origin} باید ${o}${r.minimum.toString()} ${a.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 J1(){return{localeError:H1()}}const W1=()=>{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 ${oe(r.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Za duża wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.maximum.toString()} ${a.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?">=":">",a=t(r.origin);return a?`Za mała wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.minimum.toString()} ${a.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 G1(){return{localeError:W1()}}const K1=()=>{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 ${oe(r.values[0])}`:`Opção inválida: esperada uma das ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${o}${r.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Muito pequeno: esperado que ${r.origin} tivesse ${o}${r.minimum.toString()} ${a.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 Y1(){return{localeError:K1()}}function Kh(e,t,n,i){const r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}const Q1=()=>{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?`Неверный ввод: ожидалось ${oe(r.values[0])}`:`Неверный вариант: ожидалось одно из ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);if(a){const s=Number(r.maximum),u=Kh(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет иметь ${o}${r.maximum.toString()} ${u}`}return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);if(a){const s=Number(r.minimum),u=Kh(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком маленькое значение: ожидалось, что ${r.origin} будет иметь ${o}${r.minimum.toString()} ${u}`}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 X1(){return{localeError:Q1()}}const eR=()=>{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 ${oe(r.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} imelo ${o}${r.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Premajhno: pričakovano, da bo ${r.origin} imelo ${o}${r.minimum.toString()} ${a.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 tR(){return{localeError:eR()}}const nR=()=>{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 ${oe(r.values[0])}`:`Ogiltigt val: förväntade en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`För stor(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.maximum.toString()} ${a.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?">=":">",a=t(r.origin);return a?`För lite(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.minimum.toString()} ${a.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 rR(){return{localeError:nR()}}const iR=()=>{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?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${oe(r.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${q(r.values,"|")} இல் ஒன்று`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ${a.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${r.origin} ${o}${r.minimum.toString()} ${a.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 oR(){return{localeError:iR()}}const aR=()=>{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?`ค่าไม่ถูกต้อง: ควรเป็น ${oe(r.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"ไม่เกิน":"น้อยกว่า",a=t(r.origin);return a?`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()} ${a.unit??"รายการ"}`:`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"อย่างน้อย":"มากกว่า",a=t(r.origin);return a?`น้อยกว่ากำหนด: ${r.origin} ควรมี${o} ${r.minimum.toString()} ${a.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 sR(){return{localeError:aR()}}const lR=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},uR=()=>{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 ${lR(i.input)}`;case"invalid_value":return i.values.length===1?`Geçersiz değer: beklenen ${oe(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 cR(){return{localeError:uR()}}const dR=()=>{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?`Неправильні вхідні дані: очікується ${oe(r.values[0])}`:`Неправильна опція: очікується одне з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Занадто велике: очікується, що ${r.origin??"значення"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"елементів"}`:`Занадто велике: очікується, що ${r.origin??"значення"} буде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Занадто мале: очікується, що ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.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 Aw(){return{localeError:dR()}}function pR(){return Aw()}const fR=()=>{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?`غلط ان پٹ: ${oe(r.values[0])} متوقع تھا`:`غلط آپشن: ${q(r.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`بہت بڑا: ${r.origin??"ویلیو"} کے ${o}${r.maximum.toString()} ${a.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${r.origin??"ویلیو"} کا ${o}${r.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`بہت چھوٹا: ${r.origin} کے ${o}${r.minimum.toString()} ${a.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 hR(){return{localeError:fR()}}const mR=()=>{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 ${oe(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?"<=":"<",a=t(r.origin);return a?`Quá lớn: mong đợi ${r.origin??"giá trị"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"phần tử"}`:`Quá lớn: mong đợi ${r.origin??"giá trị"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Quá nhỏ: mong đợi ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.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 gR(){return{localeError:mR()}}const vR=()=>{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?`无效输入:期望 ${oe(r.values[0])}`:`无效选项:期望以下之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()} ${a.unit??"个元素"}`:`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`数值过小:期望 ${r.origin} ${o}${r.minimum.toString()} ${a.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 yR(){return{localeError:vR()}}const bR=()=>{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?`無效的輸入值:預期為 ${oe(r.values[0])}`:`無效的選項:預期為以下其中之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()} ${a.unit??"個元素"}`:`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`數值過小:預期 ${r.origin} 應為 ${o}${r.minimum.toString()} ${a.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 _R(){return{localeError:bR()}}const wR=()=>{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 ${oe(r.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Tó pọ̀ jù: a ní láti jẹ́ pé ${r.origin??"iye"} ${a.verb} ${o}${r.maximum} ${a.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${o}${r.maximum}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Kéré ju: a ní láti jẹ́ pé ${r.origin} ${a.verb} ${o}${r.minimum} ${a.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 xR(){return{localeError:wR()}}const Pw=Object.freeze(Object.defineProperty({__proto__:null,ar:MP,az:DP,be:LP,bg:ZP,ca:VP,cs:JP,da:GP,de:YP,en:$w,eo:n1,es:i1,fa:a1,fi:l1,fr:c1,frCA:p1,he:h1,hu:g1,id:y1,is:w1,it:S1,ja:k1,ka:$1,kh:A1,km:Cw,ko:R1,lt:j1,mk:z1,ms:U1,nl:F1,no:Z1,ota:V1,pl:G1,ps:J1,pt:Y1,ru:X1,sl:tR,sv:rR,ta:oR,th:sR,tr:cR,ua:pR,uk:Aw,ur:hR,vi:gR,yo:xR,zhCN:yR,zhTW:_R},Symbol.toStringTag,{value:"Module"}));var Yh;const Rw=Symbol("ZodOutput"),Ow=Symbol("ZodInput");class Nw{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 zd(){return new Nw}(Yh=globalThis).__zod_globalRegistry??(Yh.__zod_globalRegistry=zd());const Yt=globalThis.__zod_globalRegistry;function jw(e,t){return new e({type:"string",...M(t)})}function Mw(e,t){return new e({type:"string",coerce:!0,...M(t)})}function Dd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function Qa(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function Ud(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ld(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Fd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Bd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function Bs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Zd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function qd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Vd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Hd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function Jd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Wd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Gd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Kd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Yd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function zw(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...M(t)})}function Qd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Xd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function ep(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function tp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function np(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function rp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}const Dw={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Uw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Lw(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Fw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Bw(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Zw(e,t){return new e({type:"number",checks:[],...M(t)})}function qw(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function Vw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function Hw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...M(t)})}function Jw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...M(t)})}function Ww(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...M(t)})}function Gw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...M(t)})}function Kw(e,t){return new e({type:"boolean",...M(t)})}function Yw(e,t){return new e({type:"boolean",coerce:!0,...M(t)})}function Qw(e,t){return new e({type:"bigint",...M(t)})}function Xw(e,t){return new e({type:"bigint",coerce:!0,...M(t)})}function ex(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...M(t)})}function tx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...M(t)})}function nx(e,t){return new e({type:"symbol",...M(t)})}function rx(e,t){return new e({type:"undefined",...M(t)})}function ix(e,t){return new e({type:"null",...M(t)})}function ox(e){return new e({type:"any"})}function ax(e){return new e({type:"unknown"})}function sx(e,t){return new e({type:"never",...M(t)})}function lx(e,t){return new e({type:"void",...M(t)})}function ux(e,t){return new e({type:"date",...M(t)})}function cx(e,t){return new e({type:"date",coerce:!0,...M(t)})}function dx(e,t){return new e({type:"nan",...M(t)})}function Kn(e,t){return new Cd({check:"less_than",...M(t),value:e,inclusive:!1})}function Dt(e,t){return new Cd({check:"less_than",...M(t),value:e,inclusive:!0})}function Yn(e,t){return new Ad({check:"greater_than",...M(t),value:e,inclusive:!1})}function ft(e,t){return new Ad({check:"greater_than",...M(t),value:e,inclusive:!0})}function ip(e){return Yn(0,e)}function op(e){return Kn(0,e)}function ap(e){return Dt(0,e)}function sp(e){return ft(0,e)}function Xr(e,t){return new Gb({check:"multiple_of",...M(t),value:e})}function Eo(e,t){return new Qb({check:"max_size",...M(t),maximum:e})}function ei(e,t){return new Xb({check:"min_size",...M(t),minimum:e})}function Zs(e,t){return new e_({check:"size_equals",...M(t),size:e})}function To(e,t){return new t_({check:"max_length",...M(t),maximum:e})}function gr(e,t){return new n_({check:"min_length",...M(t),minimum:e})}function $o(e,t){return new r_({check:"length_equals",...M(t),length:e})}function qs(e,t){return new i_({check:"string_format",format:"regex",...M(t),pattern:e})}function Vs(e){return new o_({check:"string_format",format:"lowercase",...M(e)})}function Hs(e){return new a_({check:"string_format",format:"uppercase",...M(e)})}function Js(e,t){return new s_({check:"string_format",format:"includes",...M(t),includes:e})}function Ws(e,t){return new l_({check:"string_format",format:"starts_with",...M(t),prefix:e})}function Gs(e,t){return new u_({check:"string_format",format:"ends_with",...M(t),suffix:e})}function lp(e,t,n){return new c_({check:"property",property:e,schema:t,...M(n)})}function Ks(e,t){return new d_({check:"mime_type",mime:e,...M(t)})}function jn(e){return new p_({check:"overwrite",tx:e})}function Ys(e){return jn(t=>t.normalize(e))}function Qs(){return jn(e=>e.trim())}function Xs(){return jn(e=>e.toLowerCase())}function el(){return jn(e=>e.toUpperCase())}function tl(){return jn(e=>Vy(e))}function px(e,t,n){return new e({type:"array",element:t,...M(n)})}function SR(e,t,n){return new e({type:"union",options:t,...M(n)})}function IR(e,t,n){return new e({type:"union",options:t,inclusive:!1,...M(n)})}function kR(e,t,n,i){return new e({type:"union",options:n,discriminator:t,...M(i)})}function ER(e,t,n){return new e({type:"intersection",left:t,right:n})}function TR(e,t,n,i){const r=n instanceof ce,o=r?i:n,a=r?n:null;return new e({type:"tuple",items:t,rest:a,...M(o)})}function $R(e,t,n,i){return new e({type:"record",keyType:t,valueType:n,...M(i)})}function CR(e,t,n,i){return new e({type:"map",keyType:t,valueType:n,...M(i)})}function AR(e,t,n){return new e({type:"set",valueType:t,...M(n)})}function PR(e,t,n){const i=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new e({type:"enum",entries:i,...M(n)})}function RR(e,t,n){return new e({type:"enum",entries:t,...M(n)})}function OR(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...M(n)})}function fx(e,t){return new e({type:"file",...M(t)})}function NR(e,t){return new e({type:"transform",transform:t})}function jR(e,t){return new e({type:"optional",innerType:t})}function MR(e,t){return new e({type:"nullable",innerType:t})}function zR(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Ds(n)}})}function DR(e,t,n){return new e({type:"nonoptional",innerType:t,...M(n)})}function UR(e,t){return new e({type:"success",innerType:t})}function LR(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:()=>n})}function FR(e,t,n){return new e({type:"pipe",in:t,out:n})}function BR(e,t){return new e({type:"readonly",innerType:t})}function ZR(e,t,n){return new e({type:"template_literal",parts:t,...M(n)})}function qR(e,t){return new e({type:"lazy",getter:t})}function VR(e,t){return new e({type:"promise",innerType:t})}function hx(e,t,n){const i=M(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function mx(e,t,n){return new e({type:"custom",check:"custom",fn:t,...M(n)})}function gx(e){const t=vx(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(Yr(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(Yr(r))}},e(n.value,n)));return t}function vx(e,t){const n=new De({check:"custom",...M(t)});return n._zod.check=e,n}function yx(e){const t=new De({check:"describe"});return t._zod.onattach=[n=>{const i=Yt.get(n)??{};Yt.add(n,{...i,description:e})}],t._zod.check=()=>{},t}function bx(e){const t=new De({check:"meta"});return t._zod.onattach=[n=>{const i=Yt.get(n)??{};Yt.add(n,{...i,...e})}],t._zod.check=()=>{},t}function _x(e,t){const n=M(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),a=new Set(r),s=e.Codec??Md,u=e.Boolean??Od,l=e.String??ko,c=new l({type:"string",error:n.error}),d=new u({type:"boolean",error:n.error}),f=new s({type:"pipe",in:c,out:d,transform:((p,g)=>{let m=p;return n.case!=="sensitive"&&(m=m.toLowerCase()),o.has(m)?!0:a.has(m)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((p,g)=>p===!0?i[0]||"true":r[0]||"false"),error:n.error});return f}function Co(e,t,n,i={}){const r=M(i),o={...M(i),check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:s=>n.test(s),...r};return n instanceof RegExp&&(o.pattern=n),new e(o)}function ti(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??Yt,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 $e(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 a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const c={...n,schemaPath:[...n.schemaPath,e],path:n.path},d=e._zod.parent;if(d)a.ref=d,$e(d,t,c),t.seen.get(d).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,c);else{const f=a.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,f,c)}}const u=t.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),t.io==="input"&<(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((i=a.schema).default??(i.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function ni(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 a=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")}#/${a}/${f}`}}if(o[1]===n)return{ref:"#"};const u=`#/${a}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},r=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:s,defId:u}=i(o);a.def={...a.schema},u&&(a.defId=u);const l=a.schema;for(const c in l)delete l[c];l.$ref=s};if(e.cycles==="throw")for(const o of e.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
28
28
|
|
|
29
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){n(i);continue}if(e.external){const l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){n(i);continue}}if(e.metadataRegistry.get(i[0])?.id){n(i);continue}if(a.cycle){n(i);continue}if(a.count>1&&e.reused==="ref"){n(i);continue}}}function en(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=a=>{const s=e.seen.get(a),l=s.def??s.schema,u={...l};if(s.ref===null)return;const c=s.ref;if(s.ref=null,c){o(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))}s.isParent||e.override({zodSchema:a,jsonSchema:l,path:s.path??[]})};for(const a of[...e.seen.entries()].reverse())o(a[0]);const n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);const i=e.external?.defs??{};for(const a of e.seen.entries()){const s=a[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{const a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Cn(t,"input"),output:Cn(t,"output")}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ve(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ve(o.element,r);if(o.type==="set")return Ve(o.valueType,r);if(o.type==="lazy")return Ve(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ve(o.innerType,r);if(o.type==="intersection")return Ve(o.left,r)||Ve(o.right,r);if(o.type==="record"||o.type==="map")return Ve(o.keyType,r)||Ve(o.valueType,r);if(o.type==="pipe")return Ve(o.in,r)||Ve(o.out,r);if(o.type==="object"){for(const n in o.shape)if(Ve(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(const n of o.options)if(Ve(n,r))return!0;return!1}if(o.type==="tuple"){for(const n of o.items)if(Ve(n,r))return!0;return!!(o.rest&&Ve(o.rest,r))}return!1}const dy=(e,t={})=>r=>{const o=Qr({...r,processors:t});return he(e,o),Xr(o,e),en(o,e)},Cn=(e,t)=>r=>{const{libraryOptions:o,target:n}=r??{},i=Qr({...o??{},target:n,io:t,processors:{}});return he(e,i),Xr(i,e),en(i,e)},JE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},py=(e,t,r,o)=>{const n=r;n.type="string";const{minimum:i,maximum:a,format:s,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=JE[s]??s,n.format===""&&delete n.format),u&&(n.contentEncoding=u),l&&l.size>0){const c=[...l];c.length===1?n.pattern=c[0].source:c.length>1&&(n.allOf=[...c.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},fy=(e,t,r,o)=>{const n=r,{minimum:i,maximum:a,format:s,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:c}=e._zod.bag;typeof s=="string"&&s.includes("int")?n.type="integer":n.type="number",typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(n.minimum=c,n.exclusiveMinimum=!0):n.exclusiveMinimum=c),typeof i=="number"&&(n.minimum=i,typeof c=="number"&&t.target!=="draft-04"&&(c>=i?delete n.minimum:delete n.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u),typeof a=="number"&&(n.maximum=a,typeof u=="number"&&t.target!=="draft-04"&&(u<=a?delete n.maximum:delete n.exclusiveMaximum)),typeof l=="number"&&(n.multipleOf=l)},my=(e,t,r,o)=>{r.type="boolean"},hy=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},gy=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},vy=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},yy=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},by=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},_y=(e,t,r,o)=>{r.not={}},wy=(e,t,r,o)=>{},xy=(e,t,r,o)=>{},$y=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Sy=(e,t,r,o)=>{const n=e._zod.def,i=Uu(n.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Iy=(e,t,r,o)=>{const n=e._zod.def,i=[];for(const a of n.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){const a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},ky=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Ey=(e,t,r,o)=>{const n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Ty=(e,t,r,o)=>{const n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:l}=e._zod.bag;a!==void 0&&(i.minLength=a),s!==void 0&&(i.maxLength=s),l?l.length===1?(i.contentMediaType=l[0],Object.assign(n,i)):n.anyOf=l.map(u=>({...i,contentMediaType:u})):Object.assign(n,i)},Oy=(e,t,r,o)=>{r.type="boolean"},Ny=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Py=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Cy=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},jy=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Ay=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Ry=(e,t,r,o)=>{const n=r,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=he(i.element,t,{...o,path:[...o.path,"items"]})},zy=(e,t,r,o)=>{const n=r,i=e._zod.def;n.type="object",n.properties={};const a=i.shape;for(const u in a)n.properties[u]=he(a[u],t,{...o,path:[...o.path,"properties",u]});const s=new Set(Object.keys(a)),l=new Set([...s].filter(u=>{const c=i.shape[u]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));l.size>0&&(n.required=Array.from(l)),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=he(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Al=(e,t,r,o)=>{const n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,l)=>he(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));i?r.oneOf=a:r.anyOf=a},My=(e,t,r,o)=>{const n=e._zod.def,i=he(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=he(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,l=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=l},Dy=(e,t,r,o)=>{const n=r,i=e._zod.def;n.type="array";const a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,p)=>he(f,t,{...o,path:[...o.path,a,p]})),u=i.rest?he(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(n.prefixItems=l,u&&(n.items=u)):t.target==="openapi-3.0"?(n.items={anyOf:l},u&&n.items.anyOf.push(u),n.minItems=l.length,u||(n.maxItems=l.length)):(n.items=l,u&&(n.additionalItems=u));const{minimum:c,maximum:d}=e._zod.bag;typeof c=="number"&&(n.minItems=c),typeof d=="number"&&(n.maxItems=d)},Uy=(e,t,r,o)=>{const n=r,i=e._zod.def;n.type="object",(t.target==="draft-07"||t.target==="draft-2020-12")&&(n.propertyNames=he(i.keyType,t,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=he(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})},Ly=(e,t,r,o)=>{const n=e._zod.def,i=he(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Zy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType},Fy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},qy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},Vy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},By=(e,t,r,o)=>{const n=e._zod.def,i=t.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;he(i,t,o);const a=t.seen.get(e);a.ref=i},Jy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Wy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType},Hy=(e,t,r,o)=>{const n=e._zod.def;he(n.innerType,t,o);const i=t.seen.get(e);i.ref=n.innerType},Gy=(e,t,r,o)=>{const n=e._zod.innerType;he(n,t,o);const i=t.seen.get(e);i.ref=n},tu={string:py,number:fy,boolean:my,bigint:hy,symbol:gy,null:vy,undefined:yy,void:by,never:_y,any:wy,unknown:xy,date:$y,enum:Sy,literal:Iy,nan:ky,template_literal:Ey,file:Ty,success:Oy,custom:Ny,function:Py,transform:Cy,map:jy,set:Ay,array:Ry,object:zy,union:Al,intersection:My,tuple:Dy,record:Uy,nullable:Ly,nonoptional:Zy,default:Fy,prefault:qy,catch:Vy,pipe:By,readonly:Jy,promise:Wy,optional:Hy,lazy:Gy};function fa(e,t){if("_idmap"in e){const o=e,n=Qr({...t,processors:tu}),i={};for(const l of o._idmap.entries()){const[u,c]=l;he(c,n)}const a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(const l of o._idmap.entries()){const[u,c]=l;Xr(n,c),a[u]=en(n,c)}if(Object.keys(i).length>0){const l=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[l]:i}}return{schemas:a}}const r=Qr({...t,processors:tu});return he(e,r),Xr(r,e),en(r,e)}class WE{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 r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Qr({processors:tu,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return he(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),Xr(this.ctx,t);const o=en(this.ctx,t),{"~standard":n,...i}=o;return i}}const HE=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),GE=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Mg,$ZodArray:Fg,$ZodAsyncError:vr,$ZodBase64:Ig,$ZodBase64URL:Eg,$ZodBigInt:il,$ZodBigIntFormat:jg,$ZodBoolean:ol,$ZodCIDRv4:$g,$ZodCIDRv6:Sg,$ZodCUID:dg,$ZodCUID2:pg,$ZodCatch:lv,$ZodCheck:Se,$ZodCheckBigIntFormat:Zh,$ZodCheckEndsWith:Xh,$ZodCheckGreaterThan:tl,$ZodCheckIncludes:Yh,$ZodCheckLengthEquals:Wh,$ZodCheckLessThan:el,$ZodCheckLowerCase:Gh,$ZodCheckMaxLength:Bh,$ZodCheckMaxSize:Fh,$ZodCheckMimeType:tg,$ZodCheckMinLength:Jh,$ZodCheckMinSize:qh,$ZodCheckMultipleOf:Uh,$ZodCheckNumberFormat:Lh,$ZodCheckOverwrite:rg,$ZodCheckProperty:eg,$ZodCheckRegex:Hh,$ZodCheckSizeEquals:Vh,$ZodCheckStartsWith:Qh,$ZodCheckStringFormat:ao,$ZodCheckUpperCase:Kh,$ZodCodec:sl,$ZodCustom:vv,$ZodCustomStringFormat:Pg,$ZodDate:Zg,$ZodDefault:iv,$ZodDiscriminatedUnion:Hg,$ZodE164:Tg,$ZodEmail:sg,$ZodEmoji:lg,$ZodEncodeError:Wi,$ZodEnum:Xg,$ZodError:Zu,$ZodFile:tv,$ZodFunction:mv,$ZodGUID:ig,$ZodIPv4:_g,$ZodIPv6:wg,$ZodISODate:vg,$ZodISODateTime:gg,$ZodISODuration:bg,$ZodISOTime:yg,$ZodIntersection:Gg,$ZodJWT:Ng,$ZodKSUID:hg,$ZodLazy:gv,$ZodLiteral:ev,$ZodMAC:xg,$ZodMap:Yg,$ZodNaN:cv,$ZodNanoID:cg,$ZodNever:Ug,$ZodNonOptional:sv,$ZodNull:zg,$ZodNullable:ov,$ZodNumber:nl,$ZodNumberFormat:Cg,$ZodObject:Bg,$ZodObjectJIT:Jg,$ZodOptional:nv,$ZodPipe:dv,$ZodPrefault:av,$ZodPromise:hv,$ZodReadonly:pv,$ZodRealError:nt,$ZodRecord:Kg,$ZodRegistry:Sv,$ZodSet:Qg,$ZodString:so,$ZodStringFormat:ge,$ZodSuccess:uv,$ZodSymbol:Ag,$ZodTemplateLiteral:fv,$ZodTransform:rv,$ZodTuple:al,$ZodType:X,$ZodULID:fg,$ZodURL:ug,$ZodUUID:ag,$ZodUndefined:Rg,$ZodUnion:Qi,$ZodUnknown:Dg,$ZodVoid:Lg,$ZodXID:mg,$ZodXor:Wg,$brand:jm,$constructor:S,$input:$v,$output:xv,Doc:ng,JSONSchema:HE,JSONSchemaGenerator:WE,NEVER:Du,TimePrecision:Tv,_any:Gv,_array:ry,_base64:Il,_base64url:kl,_bigint:Fv,_boolean:Lv,_catch:LE,_check:sy,_cidrv4:$l,_cidrv6:Sl,_coercedBigint:qv,_coercedBoolean:Zv,_coercedDate:ey,_coercedNumber:Av,_coercedString:kv,_cuid:gl,_cuid2:vl,_custom:oy,_date:Xv,_decode:Bu,_decodeAsync:Wu,_default:ME,_discriminatedUnion:IE,_e164:El,_email:ll,_emoji:ml,_encode:Vu,_encodeAsync:Ju,_endsWith:aa,_enum:PE,_file:ny,_float32:zv,_float64:Mv,_gt:ar,_gte:We,_guid:mi,_includes:oa,_int:Rv,_int32:Dv,_int64:Vv,_intersection:kE,_ipv4:wl,_ipv6:xl,_isoDate:Nv,_isoDateTime:Ov,_isoDuration:Cv,_isoTime:Pv,_jwt:Tl,_ksuid:_l,_lazy:VE,_length:co,_literal:jE,_lowercase:ra,_lt:ir,_lte:st,_mac:Ev,_map:OE,_max:st,_maxLength:lo,_maxSize:uo,_mime:sa,_min:We,_minLength:br,_minSize:Yr,_multipleOf:Kr,_nan:ty,_nanoid:hl,_nativeEnum:CE,_negative:Nl,_never:Yv,_nonnegative:Cl,_nonoptional:DE,_nonpositive:Pl,_normalize:ua,_null:Hv,_nullable:zE,_number:jv,_optional:RE,_overwrite:Ht,_parse:eo,_parseAsync:to,_pipe:ZE,_positive:Ol,_promise:BE,_property:jl,_readonly:FE,_record:TE,_refine:iy,_regex:ta,_safeDecode:Gu,_safeDecodeAsync:Yu,_safeEncode:Hu,_safeEncodeAsync:Ku,_safeParse:ro,_safeParseAsync:no,_set:NE,_size:ea,_slugify:pa,_startsWith:ia,_string:Iv,_stringFormat:po,_stringbool:cy,_success:UE,_superRefine:ay,_symbol:Jv,_templateLiteral:qE,_toLowerCase:ca,_toUpperCase:da,_transform:AE,_trim:la,_tuple:EE,_uint32:Uv,_uint64:Bv,_ulid:yl,_undefined:Wv,_union:$E,_unknown:Kv,_uppercase:na,_url:Xi,_uuid:cl,_uuidv4:dl,_uuidv6:pl,_uuidv7:fl,_void:Qv,_xid:bl,_xor:SE,clone:dt,config:De,createStandardJSONSchemaMethod:Cn,createToJSONSchemaMethod:dy,decode:oI,decodeAsync:aI,describe:uy,encode:nI,encodeAsync:iI,extractDefs:Xr,finalize:en,flattenError:Fu,formatError:qu,globalConfig:ci,globalRegistry:wt,initializeContext:Qr,isValidBase64:rl,isValidBase64URL:kg,isValidJWT:Og,locales:wv,meta:ly,parse:Qs,parseAsync:Xs,prettifyError:eh,process:he,regexes:Xu,registry:ul,safeDecode:uI,safeDecodeAsync:cI,safeEncode:sI,safeEncodeAsync:lI,safeParse:th,safeParseAsync:rh,toDotPath:Xm,toJSONSchema:fa,treeifyError:Qm,util:Km,version:og},Symbol.toStringTag,{value:"Module"})),KE=Object.freeze(Object.defineProperty({__proto__:null,endsWith:aa,gt:ar,gte:We,includes:oa,length:co,lowercase:ra,lt:ir,lte:st,maxLength:lo,maxSize:uo,mime:sa,minLength:br,minSize:Yr,multipleOf:Kr,negative:Nl,nonnegative:Cl,nonpositive:Pl,normalize:ua,overwrite:Ht,positive:Ol,property:jl,regex:ta,size:ea,slugify:pa,startsWith:ia,toLowerCase:ca,toUpperCase:da,trim:la,uppercase:na},Symbol.toStringTag,{value:"Module"})),Rl=S("ZodISODateTime",(e,t)=>{gg.init(e,t),ve.init(e,t)});function Ky(e){return Ov(Rl,e)}const zl=S("ZodISODate",(e,t)=>{vg.init(e,t),ve.init(e,t)});function Yy(e){return Nv(zl,e)}const Ml=S("ZodISOTime",(e,t)=>{yg.init(e,t),ve.init(e,t)});function Qy(e){return Pv(Ml,e)}const Dl=S("ZodISODuration",(e,t)=>{bg.init(e,t),ve.init(e,t)});function Xy(e){return Cv(Dl,e)}const eb=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:zl,ZodISODateTime:Rl,ZodISODuration:Dl,ZodISOTime:Ml,date:Yy,datetime:Ky,duration:Xy,time:Qy},Symbol.toStringTag,{value:"Module"})),tb=(e,t)=>{Zu.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>qu(e,r)},flatten:{value:r=>Fu(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,di,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,di,2)}},isEmpty:{get(){return e.issues.length===0}}})},YE=S("ZodError",tb),ot=S("ZodError",tb,{Parent:Error}),rb=eo(ot),nb=to(ot),ob=ro(ot),ma=no(ot),ib=Vu(ot),ab=Bu(ot),sb=Ju(ot),ub=Wu(ot),lb=Hu(ot),cb=Gu(ot),db=Ku(ot),pb=Yu(ot),re=S("ZodType",(e,t)=>(X.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Cn(e,"input"),output:Cn(e,"output")}}),e.toJSONSchema=dy(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(Wt(t,{checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]})),e.clone=(r,o)=>dt(e,r,o),e.brand=()=>e,e.register=((r,o)=>(r.add(e,o),e)),e.parse=(r,o)=>rb(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>ob(e,r,o),e.parseAsync=async(r,o)=>nb(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>ma(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>ib(e,r,o),e.decode=(r,o)=>ab(e,r,o),e.encodeAsync=async(r,o)=>sb(e,r,o),e.decodeAsync=async(r,o)=>ub(e,r,o),e.safeEncode=(r,o)=>lb(e,r,o),e.safeDecode=(r,o)=>cb(e,r,o),e.safeEncodeAsync=async(r,o)=>db(e,r,o),e.safeDecodeAsync=async(r,o)=>pb(e,r,o),e.refine=(r,o)=>e.check(wc(r,o)),e.superRefine=r=>e.check(xc(r)),e.overwrite=r=>e.check(Ht(r)),e.optional=()=>ee(e),e.nullable=()=>An(e),e.nullish=()=>ee(An(e)),e.nonoptional=r=>cc(e,r),e.array=()=>R(e),e.or=r=>G([e,r]),e.and=r=>Yl(e,r),e.transform=r=>Rn(e,Ma(r)),e.default=r=>sc(e,r),e.prefault=r=>lc(e,r),e.catch=r=>fc(e,r),e.pipe=r=>Rn(e,r),e.readonly=()=>gc(e),e.describe=r=>{const o=e.clone();return wt.add(o,{description:r}),o},Object.defineProperty(e,"description",{get(){return wt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return wt.get(e);const o=e.clone();return wt.add(o,r[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ha=S("_ZodString",(e,t)=>{so.init(e,t),re.init(e,t),e._zod.processJSONSchema=(o,n,i)=>py(e,o,n);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...o)=>e.check(ta(...o)),e.includes=(...o)=>e.check(oa(...o)),e.startsWith=(...o)=>e.check(ia(...o)),e.endsWith=(...o)=>e.check(aa(...o)),e.min=(...o)=>e.check(br(...o)),e.max=(...o)=>e.check(lo(...o)),e.length=(...o)=>e.check(co(...o)),e.nonempty=(...o)=>e.check(br(1,...o)),e.lowercase=o=>e.check(ra(o)),e.uppercase=o=>e.check(na(o)),e.trim=()=>e.check(la()),e.normalize=(...o)=>e.check(ua(...o)),e.toLowerCase=()=>e.check(ca()),e.toUpperCase=()=>e.check(da()),e.slugify=()=>e.check(pa())}),fo=S("ZodString",(e,t)=>{so.init(e,t),ha.init(e,t),e.email=r=>e.check(ll(ga,r)),e.url=r=>e.check(Xi(mo,r)),e.jwt=r=>e.check(Tl(Ca,r)),e.emoji=r=>e.check(ml(va,r)),e.guid=r=>e.check(mi(jn,r)),e.uuid=r=>e.check(cl(Ct,r)),e.uuidv4=r=>e.check(dl(Ct,r)),e.uuidv6=r=>e.check(pl(Ct,r)),e.uuidv7=r=>e.check(fl(Ct,r)),e.nanoid=r=>e.check(hl(ya,r)),e.guid=r=>e.check(mi(jn,r)),e.cuid=r=>e.check(gl(ba,r)),e.cuid2=r=>e.check(vl(_a,r)),e.ulid=r=>e.check(yl(wa,r)),e.base64=r=>e.check(Il(Ta,r)),e.base64url=r=>e.check(kl(Na,r)),e.xid=r=>e.check(bl(xa,r)),e.ksuid=r=>e.check(_l($a,r)),e.ipv4=r=>e.check(wl(Sa,r)),e.ipv6=r=>e.check(xl(Ia,r)),e.cidrv4=r=>e.check($l(ka,r)),e.cidrv6=r=>e.check(Sl(Ea,r)),e.e164=r=>e.check(El(Pa,r)),e.datetime=r=>e.check(Ky(r)),e.date=r=>e.check(Yy(r)),e.time=r=>e.check(Qy(r)),e.duration=r=>e.check(Xy(r))});function w(e){return Iv(fo,e)}const ve=S("ZodStringFormat",(e,t)=>{ge.init(e,t),ha.init(e,t)}),ga=S("ZodEmail",(e,t)=>{sg.init(e,t),ve.init(e,t)});function fb(e){return ll(ga,e)}const jn=S("ZodGUID",(e,t)=>{ig.init(e,t),ve.init(e,t)});function mb(e){return mi(jn,e)}const Ct=S("ZodUUID",(e,t)=>{ag.init(e,t),ve.init(e,t)});function hb(e){return cl(Ct,e)}function gb(e){return dl(Ct,e)}function vb(e){return pl(Ct,e)}function yb(e){return fl(Ct,e)}const mo=S("ZodURL",(e,t)=>{ug.init(e,t),ve.init(e,t)});function bb(e){return Xi(mo,e)}function _b(e){return Xi(mo,{protocol:/^https?$/,hostname:wh,...P(e)})}const va=S("ZodEmoji",(e,t)=>{lg.init(e,t),ve.init(e,t)});function wb(e){return ml(va,e)}const ya=S("ZodNanoID",(e,t)=>{cg.init(e,t),ve.init(e,t)});function xb(e){return hl(ya,e)}const ba=S("ZodCUID",(e,t)=>{dg.init(e,t),ve.init(e,t)});function $b(e){return gl(ba,e)}const _a=S("ZodCUID2",(e,t)=>{pg.init(e,t),ve.init(e,t)});function Sb(e){return vl(_a,e)}const wa=S("ZodULID",(e,t)=>{fg.init(e,t),ve.init(e,t)});function Ib(e){return yl(wa,e)}const xa=S("ZodXID",(e,t)=>{mg.init(e,t),ve.init(e,t)});function kb(e){return bl(xa,e)}const $a=S("ZodKSUID",(e,t)=>{hg.init(e,t),ve.init(e,t)});function Eb(e){return _l($a,e)}const Sa=S("ZodIPv4",(e,t)=>{_g.init(e,t),ve.init(e,t)});function Tb(e){return wl(Sa,e)}const Ul=S("ZodMAC",(e,t)=>{xg.init(e,t),ve.init(e,t)});function Ob(e){return Ev(Ul,e)}const Ia=S("ZodIPv6",(e,t)=>{wg.init(e,t),ve.init(e,t)});function Nb(e){return xl(Ia,e)}const ka=S("ZodCIDRv4",(e,t)=>{$g.init(e,t),ve.init(e,t)});function Pb(e){return $l(ka,e)}const Ea=S("ZodCIDRv6",(e,t)=>{Sg.init(e,t),ve.init(e,t)});function Cb(e){return Sl(Ea,e)}const Ta=S("ZodBase64",(e,t)=>{Ig.init(e,t),ve.init(e,t)});function Oa(e){return Il(Ta,e)}const Na=S("ZodBase64URL",(e,t)=>{Eg.init(e,t),ve.init(e,t)});function jb(e){return kl(Na,e)}const Pa=S("ZodE164",(e,t)=>{Tg.init(e,t),ve.init(e,t)});function Ab(e){return El(Pa,e)}const Ca=S("ZodJWT",(e,t)=>{Ng.init(e,t),ve.init(e,t)});function Rb(e){return Tl(Ca,e)}const un=S("ZodCustomStringFormat",(e,t)=>{Pg.init(e,t),ve.init(e,t)});function zb(e,t,r={}){return po(un,e,t,r)}function Mb(e){return po(un,"hostname",_h,e)}function Db(e){return po(un,"hex",Mh,e)}function Ub(e,t){const r=t?.enc??"hex",o=`${e}_${r}`,n=Xu[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return po(un,o,n,t)}const ho=S("ZodNumber",(e,t)=>{nl.init(e,t),re.init(e,t),e._zod.processJSONSchema=(o,n,i)=>fy(e,o,n),e.gt=(o,n)=>e.check(ar(o,n)),e.gte=(o,n)=>e.check(We(o,n)),e.min=(o,n)=>e.check(We(o,n)),e.lt=(o,n)=>e.check(ir(o,n)),e.lte=(o,n)=>e.check(st(o,n)),e.max=(o,n)=>e.check(st(o,n)),e.int=o=>e.check(hi(o)),e.safe=o=>e.check(hi(o)),e.positive=o=>e.check(ar(0,o)),e.nonnegative=o=>e.check(We(0,o)),e.negative=o=>e.check(ir(0,o)),e.nonpositive=o=>e.check(st(0,o)),e.multipleOf=(o,n)=>e.check(Kr(o,n)),e.step=(o,n)=>e.check(Kr(o,n)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function q(e){return jv(ho,e)}const Tr=S("ZodNumberFormat",(e,t)=>{Cg.init(e,t),ho.init(e,t)});function hi(e){return Rv(Tr,e)}function Lb(e){return zv(Tr,e)}function Zb(e){return Mv(Tr,e)}function Fb(e){return Dv(Tr,e)}function qb(e){return Uv(Tr,e)}const go=S("ZodBoolean",(e,t)=>{ol.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>my(e,r,o)});function pe(e){return Lv(go,e)}const vo=S("ZodBigInt",(e,t)=>{il.init(e,t),re.init(e,t),e._zod.processJSONSchema=(o,n,i)=>hy(e,o),e.gte=(o,n)=>e.check(We(o,n)),e.min=(o,n)=>e.check(We(o,n)),e.gt=(o,n)=>e.check(ar(o,n)),e.gte=(o,n)=>e.check(We(o,n)),e.min=(o,n)=>e.check(We(o,n)),e.lt=(o,n)=>e.check(ir(o,n)),e.lte=(o,n)=>e.check(st(o,n)),e.max=(o,n)=>e.check(st(o,n)),e.positive=o=>e.check(ar(BigInt(0),o)),e.negative=o=>e.check(ir(BigInt(0),o)),e.nonpositive=o=>e.check(st(BigInt(0),o)),e.nonnegative=o=>e.check(We(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(Kr(o,n));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function Vb(e){return Fv(vo,e)}const ja=S("ZodBigIntFormat",(e,t)=>{jg.init(e,t),vo.init(e,t)});function Bb(e){return Vv(ja,e)}function Jb(e){return Bv(ja,e)}const Ll=S("ZodSymbol",(e,t)=>{Ag.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gy(e,r)});function Wb(e){return Jv(Ll,e)}const Zl=S("ZodUndefined",(e,t)=>{Rg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yy(e,r)});function Hb(e){return Wv(Zl,e)}const Fl=S("ZodNull",(e,t)=>{zg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vy(e,r,o)});function yo(e){return Hv(Fl,e)}const ql=S("ZodAny",(e,t)=>{Mg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wy()});function Pe(){return Gv(ql)}const Vl=S("ZodUnknown",(e,t)=>{Dg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xy()});function $e(){return Kv(Vl)}const Bl=S("ZodNever",(e,t)=>{Ug.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_y(e,r,o)});function Aa(e){return Yv(Bl,e)}const Jl=S("ZodVoid",(e,t)=>{Lg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>by(e,r)});function Gb(e){return Qv(Jl,e)}const Ra=S("ZodDate",(e,t)=>{Zg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(o,n,i)=>$y(e,o),e.min=(o,n)=>e.check(We(o,n)),e.max=(o,n)=>e.check(st(o,n));const r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function Kb(e){return Xv(Ra,e)}const Wl=S("ZodArray",(e,t)=>{Fg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ry(e,r,o,n),e.element=t.element,e.min=(r,o)=>e.check(br(r,o)),e.nonempty=r=>e.check(br(1,r)),e.max=(r,o)=>e.check(lo(r,o)),e.length=(r,o)=>e.check(co(r,o)),e.unwrap=()=>e.element});function R(e,t){return ry(Wl,e,t)}function Yb(e){const t=e._zod.def.shape;return dr(Object.keys(t))}const bo=S("ZodObject",(e,t)=>{Jg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zy(e,r,o,n),ne(e,"shape",()=>t.shape),e.keyof=()=>dr(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:$e()}),e.loose=()=>e.clone({...e._zod.def,catchall:$e()}),e.strict=()=>e.clone({...e._zod.def,catchall:Aa()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>qm(e,r),e.safeExtend=r=>Vm(e,r),e.merge=r=>Bm(e,r),e.pick=r=>Zm(e,r),e.omit=r=>Fm(e,r),e.partial=(...r)=>Jm(Da,e,r[0]),e.required=(...r)=>Wm(Ua,e,r[0])});function E(e,t){const r={type:"object",shape:e??{},...P(t)};return new bo(r)}function _e(e,t){return new bo({type:"object",shape:e,catchall:Aa(),...P(t)})}function er(e,t){return new bo({type:"object",shape:e,catchall:$e(),...P(t)})}const _o=S("ZodUnion",(e,t)=>{Qi.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.options=t.options});function G(e,t){return new _o({type:"union",options:e,...P(t)})}const Hl=S("ZodXor",(e,t)=>{_o.init(e,t),Wg.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.options=t.options});function Qb(e,t){return new Hl({type:"union",options:e,inclusive:!1,...P(t)})}const Gl=S("ZodDiscriminatedUnion",(e,t)=>{_o.init(e,t),Hg.init(e,t)});function za(e,t,r){return new Gl({type:"union",options:t,discriminator:e,...P(r)})}const Kl=S("ZodIntersection",(e,t)=>{Gg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>My(e,r,o,n)});function Yl(e,t){return new Kl({type:"intersection",left:e,right:t})}const Ql=S("ZodTuple",(e,t)=>{al.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dy(e,r,o,n),e.rest=r=>e.clone({...e._zod.def,rest:r})});function Xl(e,t,r){const o=t instanceof X,n=o?r:t,i=o?t:null;return new Ql({type:"tuple",items:e,rest:i,...P(n)})}const wo=S("ZodRecord",(e,t)=>{Kg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Uy(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Xe(e,t,r){return new wo({type:"record",keyType:e,valueType:t,...P(r)})}function Xb(e,t,r){const o=dt(e);return o._zod.values=void 0,new wo({type:"record",keyType:o,valueType:t,...P(r)})}function e_(e,t,r){return new wo({type:"record",keyType:e,valueType:t,mode:"loose",...P(r)})}const ec=S("ZodMap",(e,t)=>{Yg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jy(e,r),e.keyType=t.keyType,e.valueType=t.valueType});function t_(e,t,r){return new ec({type:"map",keyType:e,valueType:t,...P(r)})}const tc=S("ZodSet",(e,t)=>{Qg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ay(e,r),e.min=(...r)=>e.check(Yr(...r)),e.nonempty=r=>e.check(Yr(1,r)),e.max=(...r)=>e.check(uo(...r)),e.size=(...r)=>e.check(ea(...r))});function r_(e,t){return new tc({type:"set",valueType:e,...P(t)})}const tn=S("ZodEnum",(e,t)=>{Xg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Sy(e,o,n),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{const i={};for(const a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new tn({...t,checks:[],...P(n),entries:i})},e.exclude=(o,n)=>{const i={...t.entries};for(const a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new tn({...t,checks:[],...P(n),entries:i})}});function dr(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new tn({type:"enum",entries:r,...P(t)})}function n_(e,t){return new tn({type:"enum",entries:e,...P(t)})}const rc=S("ZodLiteral",(e,t)=>{ev.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Iy(e,r,o),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 C(e,t){return new rc({type:"literal",values:Array.isArray(e)?e:[e],...P(t)})}const nc=S("ZodFile",(e,t)=>{tv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ty(e,r,o),e.min=(r,o)=>e.check(Yr(r,o)),e.max=(r,o)=>e.check(uo(r,o)),e.mime=(r,o)=>e.check(sa(Array.isArray(r)?r:[r],o))});function o_(e){return ny(nc,e)}const oc=S("ZodTransform",(e,t)=>{rv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cy(e,r),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Wi(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(Hr(i,r.value,t));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(Hr(a))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function Ma(e){return new oc({type:"transform",transform:e})}const Da=S("ZodOptional",(e,t)=>{nv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ee(e){return new Da({type:"optional",innerType:e})}const ic=S("ZodNullable",(e,t)=>{ov.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ly(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function An(e){return new ic({type:"nullable",innerType:e})}function i_(e){return ee(An(e))}const ac=S("ZodDefault",(e,t)=>{iv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sc(e,t){return new ac({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Gi(t)}})}const uc=S("ZodPrefault",(e,t)=>{av.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function lc(e,t){return new uc({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Gi(t)}})}const Ua=S("ZodNonOptional",(e,t)=>{sv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function cc(e,t){return new Ua({type:"nonoptional",innerType:e,...P(t)})}const dc=S("ZodSuccess",(e,t)=>{uv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Oy(e,r,o),e.unwrap=()=>e._zod.def.innerType});function a_(e){return new dc({type:"success",innerType:e})}const pc=S("ZodCatch",(e,t)=>{lv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function fc(e,t){return new pc({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const mc=S("ZodNaN",(e,t)=>{cv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ky(e,r)});function s_(e){return ty(mc,e)}const La=S("ZodPipe",(e,t)=>{dv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>By(e,r,o,n),e.in=t.in,e.out=t.out});function Rn(e,t){return new La({type:"pipe",in:e,out:t})}const Za=S("ZodCodec",(e,t)=>{La.init(e,t),sl.init(e,t)});function u_(e,t,r){return new Za({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}const hc=S("ZodReadonly",(e,t)=>{pv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gc(e){return new hc({type:"readonly",innerType:e})}const vc=S("ZodTemplateLiteral",(e,t)=>{fv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ey(e,r,o)});function l_(e,t){return new vc({type:"template_literal",parts:e,...P(t)})}const yc=S("ZodLazy",(e,t)=>{gv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gy(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function xo(e){return new yc({type:"lazy",getter:e})}const bc=S("ZodPromise",(e,t)=>{hv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wy(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function c_(e){return new bc({type:"promise",innerType:e})}const _c=S("ZodFunction",(e,t)=>{mv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Py(e,r)});function gi(e){return new _c({type:"function",input:Array.isArray(e?.input)?Xl(e?.input):e?.input??R($e()),output:e?.output??$e()})}const $o=S("ZodCustom",(e,t)=>{vv.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ny(e,r)});function d_(e){const t=new Se({check:"custom"});return t._zod.check=e,t}function So(e,t){return oy($o,e??(()=>!0),t)}function wc(e,t={}){return iy($o,e,t)}function xc(e){return ay(e)}const p_=uy,f_=ly;function Rt(e,t={error:`Input not instance of ${e.name}`}){const r=new $o({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...P(t)});return r._zod.bag.Class=e,r}const m_=(...e)=>cy({Codec:Za,Boolean:go,String:fo},...e);function h_(e){const t=xo(()=>G([w(e),q(),pe(),yo(),R(t),Xe(w(),t)]));return t}function g_(e,t){return Rn(Ma(e),t)}const QE=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:ql,ZodArray:Wl,ZodBase64:Ta,ZodBase64URL:Na,ZodBigInt:vo,ZodBigIntFormat:ja,ZodBoolean:go,ZodCIDRv4:ka,ZodCIDRv6:Ea,ZodCUID:ba,ZodCUID2:_a,ZodCatch:pc,ZodCodec:Za,ZodCustom:$o,ZodCustomStringFormat:un,ZodDate:Ra,ZodDefault:ac,ZodDiscriminatedUnion:Gl,ZodE164:Pa,ZodEmail:ga,ZodEmoji:va,ZodEnum:tn,ZodFile:nc,ZodFunction:_c,ZodGUID:jn,ZodIPv4:Sa,ZodIPv6:Ia,ZodIntersection:Kl,ZodJWT:Ca,ZodKSUID:$a,ZodLazy:yc,ZodLiteral:rc,ZodMAC:Ul,ZodMap:ec,ZodNaN:mc,ZodNanoID:ya,ZodNever:Bl,ZodNonOptional:Ua,ZodNull:Fl,ZodNullable:ic,ZodNumber:ho,ZodNumberFormat:Tr,ZodObject:bo,ZodOptional:Da,ZodPipe:La,ZodPrefault:uc,ZodPromise:bc,ZodReadonly:hc,ZodRecord:wo,ZodSet:tc,ZodString:fo,ZodStringFormat:ve,ZodSuccess:dc,ZodSymbol:Ll,ZodTemplateLiteral:vc,ZodTransform:oc,ZodTuple:Ql,ZodType:re,ZodULID:wa,ZodURL:mo,ZodUUID:Ct,ZodUndefined:Zl,ZodUnion:_o,ZodUnknown:Vl,ZodVoid:Jl,ZodXID:xa,ZodXor:Hl,_ZodString:ha,_default:sc,_function:gi,any:Pe,array:R,base64:Oa,base64url:jb,bigint:Vb,boolean:pe,catch:fc,check:d_,cidrv4:Pb,cidrv6:Cb,codec:u_,cuid:$b,cuid2:Sb,custom:So,date:Kb,describe:p_,discriminatedUnion:za,e164:Ab,email:fb,emoji:wb,enum:dr,file:o_,float32:Lb,float64:Zb,function:gi,guid:mb,hash:Ub,hex:Db,hostname:Mb,httpUrl:_b,instanceof:Rt,int:hi,int32:Fb,int64:Bb,intersection:Yl,ipv4:Tb,ipv6:Nb,json:h_,jwt:Rb,keyof:Yb,ksuid:Eb,lazy:xo,literal:C,looseObject:er,looseRecord:e_,mac:Ob,map:t_,meta:f_,nan:s_,nanoid:xb,nativeEnum:n_,never:Aa,nonoptional:cc,null:yo,nullable:An,nullish:i_,number:q,object:E,optional:ee,partialRecord:Xb,pipe:Rn,prefault:lc,preprocess:g_,promise:c_,readonly:gc,record:Xe,refine:wc,set:r_,strictObject:_e,string:w,stringFormat:zb,stringbool:m_,success:a_,superRefine:xc,symbol:Wb,templateLiteral:l_,transform:Ma,tuple:Xl,uint32:qb,uint64:Jb,ulid:Ib,undefined:Hb,union:G,unknown:$e,url:bb,uuid:hb,uuidv4:gb,uuidv6:vb,uuidv7:yb,void:Gb,xid:kb,xor:Qb},Symbol.toStringTag,{value:"Module"})),v_={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 XE(e){De({customError:e})}function eT(){return De().customError}var ru;ru||(ru={});const D={...QE,...KE,iso:eb};function tT(e,t){const r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function rT(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;const o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){const n=r[1];if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function y_(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return D.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 n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return D.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);const i=rT(n,t),a=Me(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){const n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return D.null();if(n.length===0)return D.never();if(n.length===1)return D.literal(n[0]);if(n.every(a=>typeof a=="string"))return D.enum(n);const i=n.map(a=>D.literal(a));return i.length<2?i[0]:D.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return D.literal(e.const);const r=e.type;if(Array.isArray(r)){const n=r.map(i=>{const a={...e,type:i};return y_(a,t)});return n.length===0?D.never():n.length===1?n[0]:D.union(n)}if(!r)return D.any();let o;switch(r){case"string":{let n=D.string();if(e.format){const i=e.format;i==="email"?n=n.check(D.email()):i==="uri"||i==="uri-reference"?n=n.check(D.url()):i==="uuid"||i==="guid"?n=n.check(D.uuid()):i==="date-time"?n=n.check(D.iso.datetime()):i==="date"?n=n.check(D.iso.date()):i==="time"?n=n.check(D.iso.time()):i==="duration"?n=n.check(D.iso.duration()):i==="ipv4"?n=n.check(D.ipv4()):i==="ipv6"?n=n.check(D.ipv6()):i==="mac"?n=n.check(D.mac()):i==="cidr"?n=n.check(D.cidrv4()):i==="cidr-v6"?n=n.check(D.cidrv6()):i==="base64"?n=n.check(D.base64()):i==="base64url"?n=n.check(D.base64url()):i==="e164"?n=n.check(D.e164()):i==="jwt"?n=n.check(D.jwt()):i==="emoji"?n=n.check(D.emoji()):i==="nanoid"?n=n.check(D.nanoid()):i==="cuid"?n=n.check(D.cuid()):i==="cuid2"?n=n.check(D.cuid2()):i==="ulid"?n=n.check(D.ulid()):i==="xid"?n=n.check(D.xid()):i==="ksuid"&&(n=n.check(D.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?D.number().int():D.number();typeof e.minimum=="number"&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=D.boolean();break}case"null":{o=D.null();break}case"object":{const n={},i=e.properties||{},a=new Set(e.required||[]);for(const[l,u]of Object.entries(i)){const c=Me(u,t);n[l]=a.has(l)?c:c.optional()}if(e.propertyNames){const l=Me(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties=="object"?Me(e.additionalProperties,t):D.any();if(Object.keys(n).length===0){o=D.record(l,u);break}const c=D.object(n).passthrough(),d=D.looseRecord(l,u);o=D.intersection(c,d);break}if(e.patternProperties){const l=e.patternProperties,u=Object.keys(l),c=[];for(const f of u){const p=Me(l[f],t),g=D.string().regex(new RegExp(f));c.push(D.looseRecord(g,p))}const d=[];if(Object.keys(n).length>0&&d.push(D.object(n).passthrough()),d.push(...c),d.length===0)o=D.object({}).passthrough();else if(d.length===1)o=d[0];else{let f=D.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)f=D.intersection(f,d[p]);o=f}break}const s=D.object(n);e.additionalProperties===!1?o=s.strict():typeof e.additionalProperties=="object"?o=s.catchall(Me(e.additionalProperties,t)):o=s.passthrough();break}case"array":{const n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){const a=n.map(l=>Me(l,t)),s=i&&typeof i=="object"&&!Array.isArray(i)?Me(i,t):void 0;s?o=D.tuple(a).rest(s):o=D.tuple(a),typeof e.minItems=="number"&&(o=o.check(D.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(D.maxLength(e.maxItems)))}else if(Array.isArray(i)){const a=i.map(l=>Me(l,t)),s=e.additionalItems&&typeof e.additionalItems=="object"?Me(e.additionalItems,t):void 0;s?o=D.tuple(a).rest(s):o=D.tuple(a),typeof e.minItems=="number"&&(o=o.check(D.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(D.maxLength(e.maxItems)))}else if(i!==void 0){const a=Me(i,t);let s=D.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=D.array(D.any());break}default:throw new Error(`Unsupported type: ${r}`)}return e.description&&(o=o.describe(e.description)),e.default!==void 0&&(o=o.default(e.default)),o}function Me(e,t){if(typeof e=="boolean")return e?D.any():D.never();let r=y_(e,t);const o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const n=e.anyOf.map(a=>Me(a,t)),i=D.union(n);r=o?D.intersection(r,i):i}if(e.oneOf&&Array.isArray(e.oneOf)){const n=e.oneOf.map(a=>Me(a,t)),i=D.xor(n);r=o?D.intersection(r,i):i}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:D.any();else{let n=o?r:Me(e.allOf[0],t);const i=o?0:1;for(let a=i;a<e.allOf.length;a++)n=D.intersection(n,Me(e.allOf[a],t));r=n}return e.nullable===!0&&t.version==="openapi-3.0"&&(r=D.nullable(r)),e.readOnly===!0&&(r=D.readonly(r)),r}function nT(e,t){if(typeof e=="boolean")return e?D.any():D.never();const r=tT(e,t?.defaultTarget),o=e.$defs||e.definitions||{};return Me(e,{version:r,defs:o,refs:new Map,processing:new Set,rootSchema:e})}function oT(e){return kv(fo,e)}function iT(e){return Av(ho,e)}function aT(e){return Zv(go,e)}function sT(e){return qv(vo,e)}function uT(e){return ey(Ra,e)}const lT=Object.freeze(Object.defineProperty({__proto__:null,bigint:sT,boolean:aT,date:uT,number:iT,string:oT},Symbol.toStringTag,{value:"Module"}));De(yv());const vi=Object.freeze(Object.defineProperty({__proto__:null,$brand:jm,$input:$v,$output:xv,NEVER:Du,TimePrecision:Tv,ZodAny:ql,ZodArray:Wl,ZodBase64:Ta,ZodBase64URL:Na,ZodBigInt:vo,ZodBigIntFormat:ja,ZodBoolean:go,ZodCIDRv4:ka,ZodCIDRv6:Ea,ZodCUID:ba,ZodCUID2:_a,ZodCatch:pc,ZodCodec:Za,ZodCustom:$o,ZodCustomStringFormat:un,ZodDate:Ra,ZodDefault:ac,ZodDiscriminatedUnion:Gl,ZodE164:Pa,ZodEmail:ga,ZodEmoji:va,ZodEnum:tn,ZodError:YE,ZodFile:nc,get ZodFirstPartyTypeKind(){return ru},ZodFunction:_c,ZodGUID:jn,ZodIPv4:Sa,ZodIPv6:Ia,ZodISODate:zl,ZodISODateTime:Rl,ZodISODuration:Dl,ZodISOTime:Ml,ZodIntersection:Kl,ZodIssueCode:v_,ZodJWT:Ca,ZodKSUID:$a,ZodLazy:yc,ZodLiteral:rc,ZodMAC:Ul,ZodMap:ec,ZodNaN:mc,ZodNanoID:ya,ZodNever:Bl,ZodNonOptional:Ua,ZodNull:Fl,ZodNullable:ic,ZodNumber:ho,ZodNumberFormat:Tr,ZodObject:bo,ZodOptional:Da,ZodPipe:La,ZodPrefault:uc,ZodPromise:bc,ZodReadonly:hc,ZodRealError:ot,ZodRecord:wo,ZodSet:tc,ZodString:fo,ZodStringFormat:ve,ZodSuccess:dc,ZodSymbol:Ll,ZodTemplateLiteral:vc,ZodTransform:oc,ZodTuple:Ql,ZodType:re,ZodULID:wa,ZodURL:mo,ZodUUID:Ct,ZodUndefined:Zl,ZodUnion:_o,ZodUnknown:Vl,ZodVoid:Jl,ZodXID:xa,ZodXor:Hl,_ZodString:ha,_default:sc,_function:gi,any:Pe,array:R,base64:Oa,base64url:jb,bigint:Vb,boolean:pe,catch:fc,check:d_,cidrv4:Pb,cidrv6:Cb,clone:dt,codec:u_,coerce:lT,config:De,core:GE,cuid:$b,cuid2:Sb,custom:So,date:Kb,decode:ab,decodeAsync:ub,describe:p_,discriminatedUnion:za,e164:Ab,email:fb,emoji:wb,encode:ib,encodeAsync:sb,endsWith:aa,enum:dr,file:o_,flattenError:Fu,float32:Lb,float64:Zb,formatError:qu,fromJSONSchema:nT,function:gi,getErrorMap:eT,globalRegistry:wt,gt:ar,gte:We,guid:mb,hash:Ub,hex:Db,hostname:Mb,httpUrl:_b,includes:oa,instanceof:Rt,int:hi,int32:Fb,int64:Bb,intersection:Yl,ipv4:Tb,ipv6:Nb,iso:eb,json:h_,jwt:Rb,keyof:Yb,ksuid:Eb,lazy:xo,length:co,literal:C,locales:wv,looseObject:er,looseRecord:e_,lowercase:ra,lt:ir,lte:st,mac:Ob,map:t_,maxLength:lo,maxSize:uo,meta:f_,mime:sa,minLength:br,minSize:Yr,multipleOf:Kr,nan:s_,nanoid:xb,nativeEnum:n_,negative:Nl,never:Aa,nonnegative:Cl,nonoptional:cc,nonpositive:Pl,normalize:ua,null:yo,nullable:An,nullish:i_,number:q,object:E,optional:ee,overwrite:Ht,parse:rb,parseAsync:nb,partialRecord:Xb,pipe:Rn,positive:Ol,prefault:lc,preprocess:g_,prettifyError:eh,promise:c_,property:jl,readonly:gc,record:Xe,refine:wc,regex:ta,regexes:Xu,registry:ul,safeDecode:cb,safeDecodeAsync:pb,safeEncode:lb,safeEncodeAsync:db,safeParse:ob,safeParseAsync:ma,set:r_,setErrorMap:XE,size:ea,slugify:pa,startsWith:ia,strictObject:_e,string:w,stringFormat:zb,stringbool:m_,success:a_,superRefine:xc,symbol:Wb,templateLiteral:l_,toJSONSchema:fa,toLowerCase:ca,toUpperCase:da,transform:Ma,treeifyError:Qm,trim:la,tuple:Xl,uint32:qb,uint64:Jb,ulid:Ib,undefined:Hb,union:G,unknown:$e,uppercase:na,url:bb,util:Km,uuid:hb,uuidv4:gb,uuidv6:vb,uuidv7:yb,void:Gb,xid:kb,xor:Qb},Symbol.toStringTag,{value:"Module"}));var zn;(function(e){e.assertEqual=n=>{};function t(n){}e.assertIs=t;function r(n){throw new Error}e.assertNever=r,e.arrayToEnum=n=>{const i={};for(const a of n)i[a]=a;return i},e.getValidEnumValues=n=>{const i=e.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),a={};for(const s of i)a[s]=n[s];return e.objectValues(a)},e.objectValues=n=>e.objectKeys(n).map(function(i){return n[i]}),e.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},e.find=(n,i)=>{for(const a of n)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=o,e.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(zn||(zn={}));var Xd;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Xd||(Xd={}));zn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);zn.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 yi extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(i){return i.message},o={_errors:[]},n=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)o._errors.push(r(a));else{let s=o,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(r(a))):s[u]=s[u]||{_errors:[]},s=s[u],l++}}};return n(this),o}static assert(t){if(!(t instanceof yi))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,zn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r=Object.create(null),o=[];for(const n of this.issues)if(n.path.length>0){const i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else o.push(t(n));return{formErrors:o,fieldErrors:r}}get formErrors(){return this.flatten()}}yi.create=e=>new yi(e);var ep;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ep||(ep={}));var A;(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"})(A||(A={}));var cT=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const n=()=>{const i=r.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=r[Math.random()*i|0];return a.join("")};if(e==null)return n;if(r.includes(o))throw new Ji({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${r}".`});return()=>`${e}${o}${n()}`};cT();function b_(e=globalThis){var t,r,o;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(r=e.process)==null?void 0:r.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function dT(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,o)=>{t[o.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,o]of e)o!=null&&(t[r.toLowerCase()]=o)}return t}function __(e,...t){const r=new Headers(dT(e)),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var pT=Symbol.for("vercel.ai.validator");function fT(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var mT=Symbol.for("vercel.ai.schema");function hT(e,{validate:t}={}){return{[mT]:!0,_type:void 0,[pT]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let $c;$c=globalThis.crypto;async function gT(e){return(await $c).getRandomValues(new Uint8Array(e))}async function vT(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const o=await gT(e);for(let n=0;n<e;n++){const i=o[n]%t.length;r+=t[i]}return r}async function yT(e){return await vT(e)}async function bT(e){const t=await(await $c).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function _T(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await yT(e),r=await bT(t);return{code_verifier:t,code_challenge:r}}var wT="AI_MCPClientError",w_=`vercel.ai.error.${wT}`,xT=Symbol.for(w_),tp,rp,se=class extends(rp=Y,tp=xT,rp){constructor({name:e="MCPClientError",message:t,cause:r,data:o,code:n}){super({name:e,message:t,cause:r}),this[tp]=!0,this.data=o,this.code=n}static isInstance(e){return Y.hasMarker(e,w_)}},ln="2025-06-18",$T=[ln,"2025-03-26","2024-11-05"],ST=er({name:w(),version:w()}),Fa=er({_meta:ee(E({}).loose())}),Vt=Fa,x_=E({method:w(),params:ee(Fa)}),$_=E({applyDefaults:ee(pe())}).loose(),IT=er({experimental:ee(E({}).loose()),logging:ee(E({}).loose()),prompts:ee(er({listChanged:ee(pe())})),resources:ee(er({subscribe:ee(pe()),listChanged:ee(pe())})),tools:ee(er({listChanged:ee(pe())})),elicitation:ee($_)});E({elicitation:ee($_)}).loose();var kT=Vt.extend({protocolVersion:w(),capabilities:IT,serverInfo:ST,instructions:ee(w())}),Sc=Vt.extend({nextCursor:ee(w())}),ET=E({name:w(),description:ee(w()),inputSchema:E({type:C("object"),properties:ee(E({}).loose())}).loose()}).loose(),TT=Sc.extend({tools:R(ET)}),S_=E({type:C("text"),text:w()}).loose(),I_=E({type:C("image"),data:Oa(),mimeType:w()}).loose(),OT=E({uri:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w()),size:ee(q())}).loose(),NT=Sc.extend({resources:R(OT)}),k_=E({uri:w(),name:ee(w()),title:ee(w()),mimeType:ee(w())}).loose(),E_=k_.extend({text:w()}),T_=k_.extend({blob:Oa()}),O_=E({type:C("resource"),resource:G([E_,T_])}).loose(),PT=Vt.extend({content:R(G([S_,I_,O_])),isError:pe().default(!1).optional()}).or(Vt.extend({toolResult:$e()})),CT=E({uriTemplate:w(),name:w(),title:ee(w()),description:ee(w()),mimeType:ee(w())}).loose(),jT=Vt.extend({resourceTemplates:R(CT)}),AT=Vt.extend({contents:R(G([E_,T_]))}),RT=E({name:w(),description:ee(w()),required:ee(pe())}).loose(),zT=E({name:w(),title:ee(w()),description:ee(w()),arguments:ee(R(RT))}).loose(),MT=Sc.extend({prompts:R(zT)}),DT=E({role:G([C("user"),C("assistant")]),content:G([S_,I_,O_])}).loose(),UT=Vt.extend({description:ee(w()),messages:R(DT)}),LT=Fa.extend({message:w(),requestedSchema:$e()}),np=x_.extend({method:C("elicitation/create"),params:LT}),ZT=Vt.extend({action:G([C("accept"),C("decline"),C("cancel")]),content:ee(Xe(w(),$e()))}),qa="2.0",FT=E({jsonrpc:C(qa),id:G([w(),q().int()])}).merge(x_).strict(),qT=E({jsonrpc:C(qa),id:G([w(),q().int()]),result:Vt}).strict(),VT=E({jsonrpc:C(qa),id:G([w(),q().int()]),error:E({code:q().int(),message:w(),data:ee($e())})}).strict(),BT=E({jsonrpc:C(qa)}).merge(E({method:w(),params:ee(Fa)})).strict(),In=G([FT,BT,qT,VT]),N_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",P_=E({access_token:w(),id_token:w().optional(),token_type:w(),expires_in:q().optional(),scope:w().optional(),refresh_token:w().optional()}).strip(),He=w().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:v_.custom,message:"URL must be parseable",fatal:!0}),Du}).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"}),JT=E({resource:w().url(),authorization_servers:R(He).optional(),jwks_uri:w().url().optional(),scopes_supported:R(w()).optional(),bearer_methods_supported:R(w()).optional(),resource_signing_alg_values_supported:R(w()).optional(),resource_name:w().optional(),resource_documentation:w().optional(),resource_policy_uri:w().url().optional(),resource_tos_uri:w().url().optional(),tls_client_certificate_bound_access_tokens:pe().optional(),authorization_details_types_supported:R(w()).optional(),dpop_signing_alg_values_supported:R(w()).optional(),dpop_bound_access_tokens_required:pe().optional()}).passthrough(),C_=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),code_challenge_methods_supported:R(w()),token_endpoint_auth_methods_supported:R(w()).optional(),token_endpoint_auth_signing_alg_values_supported:R(w()).optional()}).passthrough(),WT=E({issuer:w(),authorization_endpoint:He,token_endpoint:He,userinfo_endpoint:He.optional(),jwks_uri:He,registration_endpoint:He.optional(),scopes_supported:R(w()).optional(),response_types_supported:R(w()),grant_types_supported:R(w()).optional(),subject_types_supported:R(w()),id_token_signing_alg_values_supported:R(w()),claims_supported:R(w()).optional(),token_endpoint_auth_methods_supported:R(w()).optional()}).passthrough(),HT=WT.merge(C_.pick({code_challenge_methods_supported:!0})),GT=E({client_id:w(),client_secret:w().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),KT=E({redirect_uris:R(He),token_endpoint_auth_method:w().optional(),grant_types:R(w()).optional(),response_types:R(w()).optional(),client_name:w().optional(),client_uri:He.optional(),logo_uri:He.optional(),scope:w().optional(),contacts:R(w()).optional(),tos_uri:He.optional(),policy_uri:w().optional(),jwks_uri:He.optional(),jwks:Pe().optional(),software_id:w().optional(),software_version:w().optional(),software_statement:w().optional()}).strip(),YT=E({error:w(),error_description:w().optional(),error_uri:w().optional()}),QT=KT.merge(GT),XT="AI_MCPClientOAuthError",j_=`vercel.ai.error.${XT}`,eO=Symbol.for(j_),op,ip,Io=class extends(ip=Y,op=eO,ip){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[op]=!0}static isInstance(e){return Y.hasMarker(e,j_)}},rn=class extends Io{};rn.errorCode="server_error";var bi=class extends Io{};bi.errorCode="invalid_client";var _i=class extends Io{};_i.errorCode="invalid_grant";var wi=class extends Io{};wi.errorCode="unauthorized_client";var tO={[rn.errorCode]:rn,[bi.errorCode]:bi,[_i.errorCode]:_i,[wi.errorCode]:wi};function rO(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function nO({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var xi=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function $i(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[o,n]=r.split(" ");if(o.toLowerCase()!=="bearer"||!n)return;const i=/resource_metadata="([^"]*)"/,a=r.match(i);if(a)try{return new URL(a[1])}catch{return}}function oO(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ic(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Ic(e,void 0,r):void 0;throw o}}async function ap(e,t,r=fetch){return await Ic(e,{"MCP-Protocol-Version":t},r)}function iO(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function aO(e,t,r,o){var n,i;const a=new URL(e),s=(n=o?.protocolVersion)!=null?n:ln;let l;if(o?.metadataUrl)l=new URL(o.metadataUrl);else{const c=oO(t,a.pathname);l=new URL(c,(i=o?.metadataServerUrl)!=null?i:a),l.search=a.search}let u=await ap(l,s,r);if(!o?.metadataUrl&&iO(u,a.pathname)){const c=new URL(`/.well-known/${t}`,a);u=await ap(c,s,r)}return u}async function sO(e,t,r=fetch){const o=await aO(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return JT.parse(await o.json())}function uO(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function lO(e,{fetchFn:t=fetch,protocolVersion:r=ln}={}){var o;const n={"MCP-Protocol-Version":r},i=uO(e);for(const{url:a,type:s}of i){const l=await Ic(a,n,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return C_.parse(await l.json());{const u=HT.parse(await l.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function cO(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:a}){const s="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);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 _T(),d=c.code_verifier,f=c.code_challenge;return u.searchParams.set("response_type",s),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",f),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(o)),i&&u.searchParams.set("state",i),n&&u.searchParams.set("scope",n),n?.includes("offline_access")&&u.searchParams.append("prompt","consent"),a&&u.searchParams.set("resource",a.href),{authorizationUrl:u,codeVerifier:d}}function A_(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function R_(e,t,r,o){const{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":dO(n,i,r);return;case"client_secret_post":pO(n,i,o);return;case"none":fO(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function dO(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function pO(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function fO(e,t){t.set("client_id",e)}async function kc(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const o=YT.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:a}=o,s=tO[n]||rn;return new s({message:i||"",cause:a})}catch(o){const n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new rn({message:n})}}async function mO(e,{metadata:t,clientInformation:r,authorizationCode:o,codeVerifier:n,redirectUri:i,resource:a,addClientAuthentication:s,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:o,code_verifier:n,redirect_uri:String(i)});if(s)s(f,p,e,t);else{const h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],b=A_(r,h);R_(b,r,f,p)}a&&p.set("resource",a.href);const g=await(l??fetch)(d,{method:"POST",headers:f,body:p});if(!g.ok)throw await kc(g);return P_.parse(await g.json())}async function hO(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:a}){var s;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:o});if(i)i(c,d,e,t);else{const p=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],g=A_(r,p);R_(g,r,c,d)}n&&d.set("resource",n.href);const f=await(a??fetch)(u,{method:"POST",headers:c,body:d});if(!f.ok)throw await kc(f);return P_.parse({refresh_token:o,...await f.json()})}async function gO(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const i=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw await kc(i);return QT.parse(await i.json())}async function Si(e,t){var r,o;try{return await ys(e,t)}catch(n){if(n instanceof bi||n instanceof wi)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await ys(e,t);if(n instanceof _i)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await ys(e,t);throw n}}async function vO(e,t,r){const o=rO(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!nO({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}async function ys(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let a,s;try{a=await sO(t,{resourceMetadataUrl:n},i),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=t);const l=await vO(t,e,a),u=await lO(s,{fetchFn:i});let c=await Promise.resolve(e.clientInformation());if(!c){if(r!==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 gO(s,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(h),c=h}if(r!==void 0){const h=await e.codeVerifier(),b=await mO(s,{metadata:u,clientInformation:c,authorizationCode:r,codeVerifier:h,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const h=await hO(s,{metadata:u,clientInformation:c,refreshToken:d.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(h),"AUTHORIZED"}catch(h){if(!(!(h instanceof Io)||h instanceof rn))throw h}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:g}=await cO(s,{metadata:u,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(p),"REDIRECT"}var yO=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":ln};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return __(t,`ai-sdk/${N_}`,b_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(o=!1)=>{var n,i,a,s,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:u,signal:(n=this.abortController)==null?void 0:n.signal});if(c.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=$i(c);try{if(await Si(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new xi;return(i=this.onerror)==null||i.call(this,h),t(h)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return r(!0)}if(!c.ok||!c.body){let g=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const h=new se({message:g});return(s=this.onerror)==null||s.call(this,h),t(h)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b;try{for(;;){const{done:y,value:x}=await f.read();if(y){if(this.connected)throw this.connected=!1,new se({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:$,data:v}=x;if($==="endpoint"){if(this.endpoint=new URL(v,this.url),this.endpoint.origin!==this.url.origin)throw new se({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if($==="message")try{const k=In.parse(JSON.parse(v));(g=this.onmessage)==null||g.call(this,k)}catch(k){const N=new se({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(h=this.onerror)==null||h.call(this,N)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(b=this.onerror)==null||b.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)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new se({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(o=!1)=>{var n,i,a,s,l;try{const c={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},d=await fetch(t,c);if(d.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=$i(d);try{if(await Si(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new xi;(i=this.onerror)==null||i.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return r(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new se({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(s=this.onerror)==null||s.call(this,p);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await r()}},bO=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":ln};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return __(t,`ai-sdk/${N_}`,b_())}async start(){if(this.abortController)throw new se({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,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var o,n,i,a,s,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:(o=this.abortController)==null?void 0:o.signal},f=await fetch(this.url,d),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=$i(f);try{if(await Si(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new xi}catch(b){throw(n=this.onerror)==null||n.call(this,b),b}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const b=await f.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${b}`;f.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const x=new se({message:y});throw(i=this.onerror)==null||i.call(this,x),x}const g=f.headers.get("content-type")||"";if(g.includes("application/json")){const b=await f.json(),y=Array.isArray(b)?b.map(x=>In.parse(x)):[In.parse(b)];for(const x of y)(a=this.onmessage)==null||a.call(this,x);return}if(g.includes("text/event-stream")){if(!f.body){const $=new se({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(s=this.onerror)==null||s.call(this,$),$}const y=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader();(async()=>{var $,v,k;try{for(;;){const{done:N,value:I}=await y.read();if(N)return;const{event:O,data:M}=I;if(O==="message")try{const F=In.parse(JSON.parse(M));($=this.onmessage)==null||$.call(this,F)}catch(F){const te=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(v=this.onerror)==null||v.call(this,te)}}}catch(N){if(N instanceof Error&&N.name==="AbortError")return;(k=this.onerror)==null||k.call(this,N)}})();return}const h=new se({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});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:r,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new se({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,o,n,i,a,s;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:(r=this.abortController)==null?void 0:r.signal}),c=u.headers.get("mcp-session-id");if(c&&(this.sessionId=c),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=$i(u);try{if(await Si(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new xi;(o=this.onerror)==null||o.call(this,h);return}}catch(g){(n=this.onerror)==null||n.call(this,g);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const g=new se({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(i=this.onerror)==null||i.call(this,g);return}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).getReader(),p=async()=>{var g,h,b,y;try{for(;;){const{done:x,value:$}=await f.read();if(x)return;const{event:v,data:k,id:N}=$;if(N&&(this.lastInboundEventId=N),v==="message")try{const I=In.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,I)}catch(I){const O=new se({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(h=this.onerror)==null||h.call(this,O)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(b=this.onerror)==null||b.call(this,x),(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;(a=this.onerror)==null||a.call(this,l),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function _O(e){switch(e.type){case"sse":return new yO(e);case"http":return new bO(e);default:throw new se({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function wO(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var xO="1.0.0";async function $O(e){const t=new SO(e);return await t.init(),t}var SO=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=xO,onUncaughtError:o,capabilities:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=n??{},wO(e)?this.transport=e:this.transport=_O(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new se({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:ln,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:kT});if(e===void 0)throw new se({message:"Server sent invalid initialize result"});if(!$T.includes(e.protocolVersion))throw new se({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 se({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new se({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new se({message:"Server does not support prompts"});break;default:throw new se({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((o,n)=>{if(this.isClosed)return n(new se({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const i=r?.signal;i?.throwIfAborted();const a=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(i?.aborted)return n(new se({message:"Request was aborted",cause:i.reason}));if(u instanceof Error)return n(u);try{const c=t.parse(u.result);o(c)}catch(c){const d=new se({message:"Failed to parse server response",cause:c});n(d)}}),this.transport.send(s).catch(u=>{l(),n(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:TT,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:PT,options:{signal:r?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:NT,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:AT,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:jT,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:MT,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:UT,options:r})}catch(o){throw o}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const r={};try{const o=await this.listTools();for(const{name:n,description:i,inputSchema:a}of o.tools){if(e!=="automatic"&&!(n in e))continue;const s=this,l=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),s.callTool({name:n,args:c,options:d})},u=e==="automatic"?fT({description:i,inputSchema:hT({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:i,inputSchema:e[n].inputSchema,execute:l};r[n]=u}return r}catch(o){throw o}}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:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==np)throw new se({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=np.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 r=await this.elicitationRequestHandler(t.data),o=ZT.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new se({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),r=this.responseHandlers.get(t);if(r===void 0)throw new se({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new se({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},ko=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(){}},IO={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},kO=class{#e=IO;#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)}},hr=new kO;function EO(e){setTimeout(e,0)}var _r=typeof window>"u"||"Deno"in globalThis;function Je(){}function TO(e,t){return typeof e=="function"?e(t):e}function nu(e){return typeof e=="number"&&e>=0&&e!==1/0}function z_(e,t){return Math.max(e+(t||0)-Date.now(),0)}function rr(e,t){return typeof e=="function"?e(t):e}function at(e,t){return typeof e=="function"?e(t):e}function sp(e,t){const{type:r="all",exact:o,fetchStatus:n,predicate:i,queryKey:a,stale:s}=e;if(a){if(o){if(t.queryHash!==Ec(a,t.options))return!1}else if(!Dn(t.queryKey,a))return!1}if(r!=="all"){const l=t.isActive();if(r==="active"&&!l||r==="inactive"&&l)return!1}return!(typeof s=="boolean"&&t.isStale()!==s||n&&n!==t.state.fetchStatus||i&&!i(t))}function up(e,t){const{exact:r,status:o,predicate:n,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(r){if(Mn(t.options.mutationKey)!==Mn(i))return!1}else if(!Dn(t.options.mutationKey,i))return!1}return!(o&&t.state.status!==o||n&&!n(t))}function Ec(e,t){return(t?.queryKeyHashFn||Mn)(e)}function Mn(e){return JSON.stringify(e,(t,r)=>au(r)?Object.keys(r).sort().reduce((o,n)=>(o[n]=r[n],o),{}):r)}function Dn(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(r=>Dn(e[r],t[r])):!1}var OO=Object.prototype.hasOwnProperty;function ou(e,t){if(e===t)return e;const r=lp(e)&&lp(t);if(!r&&!(au(e)&&au(t)))return t;const n=(r?e:Object.keys(e)).length,i=r?t:Object.keys(t),a=i.length,s=r?new Array(a):{};let l=0;for(let u=0;u<a;u++){const c=r?u:i[u],d=e[c],f=t[c];if(d===f){s[c]=d,(r?u<n:OO.call(e,c))&&l++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){s[c]=f;continue}const p=ou(d,f);s[c]=p,p===d&&l++}return n===a&&l===n?e:s}function iu(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}function lp(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function au(e){if(!cp(e))return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(!cp(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function cp(e){return Object.prototype.toString.call(e)==="[object Object]"}function NO(e){return new Promise(t=>{hr.setTimeout(t,e)})}function su(e,t,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(e,t);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return ou(e,t)}catch(o){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. [${r.queryHash}]: ${o}`),o}return ou(e,t)}return t}function PO(e,t,r=0){const o=[...e,t];return r&&o.length>r?o.slice(1):o}function CO(e,t,r=0){const o=[t,...e];return r&&o.length>r?o.slice(0,-1):o}var Ii=Symbol();function M_(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ii&&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===Ii?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function jO(e,t){return typeof e=="function"?e(...t):!!e}var AO=class extends ko{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!_r&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=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"}},Tc=new AO;function uu(){let e,t;const r=new Promise((n,i)=>{e=n,t=i});r.status="pending",r.catch(()=>{});function o(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{o({status:"fulfilled",value:n}),e(n)},r.reject=n=>{o({status:"rejected",reason:n}),t(n)},r}var RO=EO;function zO(){let e=[],t=0,r=s=>{s()},o=s=>{s()},n=RO;const i=s=>{t?e.push(s):n(()=>{r(s)})},a=()=>{const s=e;e=[],s.length&&n(()=>{o(()=>{s.forEach(l=>{r(l)})})})};return{batch:s=>{let l;t++;try{l=s()}finally{t--,t||a()}return l},batchCalls:s=>(...l)=>{i(()=>{s(...l)})},schedule:i,setNotifyFunction:s=>{r=s},setBatchNotifyFunction:s=>{o=s},setScheduler:s=>{n=s}}}var ze=zO(),MO=class extends ko{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!_r&&window.addEventListener){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(r=>{r(e)}))}isOnline(){return this.#e}},ki=new MO;function DO(e){return Math.min(1e3*2**e,3e4)}function D_(e){return(e??"online")==="online"?ki.isOnline():!0}var lu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function U_(e){let t=!1,r=0,o;const n=uu(),i=()=>n.status!=="pending",a=h=>{if(!i()){const b=new lu(h);f(b),e.onCancel?.(b)}},s=()=>{t=!0},l=()=>{t=!1},u=()=>Tc.isFocused()&&(e.networkMode==="always"||ki.isOnline())&&e.canRun(),c=()=>D_(e.networkMode)&&e.canRun(),d=h=>{i()||(o?.(),n.resolve(h))},f=h=>{i()||(o?.(),n.reject(h))},p=()=>new Promise(h=>{o=b=>{(i()||u())&&h(b)},e.onPause?.()}).then(()=>{o=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let h;const b=r===0?e.initialPromise:void 0;try{h=b??e.fn()}catch(y){h=Promise.reject(y)}Promise.resolve(h).then(d).catch(y=>{if(i())return;const x=e.retry??(_r?0:3),$=e.retryDelay??DO,v=typeof $=="function"?$(r,y):$,k=x===!0||typeof x=="number"&&r<x||typeof x=="function"&&x(r,y);if(t||!k){f(y);return}r++,e.onFail?.(r,y),NO(v).then(()=>u()?void 0:p()).then(()=>{t?f(y):g()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(o?.(),n),cancelRetry:s,continueRetry:l,canStart:c,start:()=>(c()?g():p().then(g),n)}}var L_=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),nu(this.gcTime)&&(this.#e=hr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(_r?1/0:300*1e3))}clearGcTimeout(){this.#e&&(hr.clearTimeout(this.#e),this.#e=void 0)}},UO=class extends L_{#e;#t;#r;#o;#n;#s;#a;constructor(e){super(),this.#a=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#r=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=pp(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){if(this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=pp(this.options);t.data!==void 0&&(this.setState(dp(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const r=su(this.state.data,e,this.options);return this.#i({data:r,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),r}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(Je).catch(Je):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>at(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ii||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>rr(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:!z_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.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.#n&&(this.#a?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#n?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){const s=this.observers.find(l=>l.options.queryFn);s&&this.setOptions(s.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 r=new AbortController,o=s=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#a=!0,r.signal)})},n=()=>{const s=M_(this.options,t),u=(()=>{const c={client:this.#o,queryKey:this.queryKey,meta:this.meta};return o(c),c})();return this.#a=!1,this.options.persister?this.options.persister(s,u,this):s(u)},a=(()=>{const s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:n};return o(s),s})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#i({type:"fetch",meta:a.fetchOptions?.meta}),this.#n=U_({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:s=>{s instanceof lu&&s.revert&&this.setState({...this.#t,fetchStatus:"idle"}),r.abort()},onFail:(s,l)=>{this.#i({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{const s=await this.#n.start();if(s===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(s),this.#r.config.onSuccess?.(s,this),this.#r.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof lu){if(s.silent)return this.#n.promise;if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#i({type:"error",error:s}),this.#r.config.onError?.(s,this),this.#r.config.onSettled?.(this.state.data,s,this),s}finally{this.scheduleGc()}}#i(e){const t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Z_(r.data,this.options),fetchMeta:e.meta??null};case"success":const o={...r,...dp(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?o:void 0,o;case"error":const n=e.error;return{...r,error:n,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),ze.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Z_(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:D_(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dp(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function pp(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,r=t!==void 0,o=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?o??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var LO=class extends ko{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#a=uu(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#r=void 0;#o=void 0;#n;#s;#a;#i;#h;#p;#f;#l;#c;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),fp(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return cu(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return cu(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,r=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 at(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&&!iu(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const o=this.hasListeners();o&&mp(this.#t,r,this.options,t)&&this.#d(),this.updateResult(),o&&(this.#t!==r||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||rr(this.options.staleTime,this.#t)!==rr(t.staleTime,this.#t))&&this.#g();const n=this.#v();o&&(this.#t!==r||at(this.options.enabled,this.#t)!==at(t.enabled,this.#t)||n!==this.#u)&&this.#y(n)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),r=this.createResult(t,e);return FO(this,r)&&(this.#o=r,this.#s=this.options,this.#n=this.#t.state),r}getCurrentResult(){return this.#o}trackResult(e,t){return new Proxy(e,{get:(r,o)=>(this.trackProp(o),t?.(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),r=this.#e.getQueryCache().build(this.#e,t);return r.fetch().then(()=>this.createResult(r,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#o))}#d(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Je)),t}#g(){this.#_();const e=rr(this.options.staleTime,this.#t);if(_r||this.#o.isStale||!nu(e))return;const r=z_(this.#o.dataUpdatedAt,e)+1;this.#l=hr.setTimeout(()=>{this.#o.isStale||this.updateResult()},r)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#u=e,!(_r||at(this.options.enabled,this.#t)===!1||!nu(this.#u)||this.#u===0)&&(this.#c=hr.setInterval(()=>{(this.options.refetchIntervalInBackground||Tc.isFocused())&&this.#d()},this.#u))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#l&&(hr.clearTimeout(this.#l),this.#l=void 0)}#w(){this.#c&&(hr.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const r=this.#t,o=this.options,n=this.#o,i=this.#n,a=this.#s,l=e!==r?e.state:this.#r,{state:u}=e;let c={...u},d=!1,f;if(t._optimisticResults){const O=this.hasListeners(),M=!O&&fp(e,t),F=O&&mp(e,r,t,o);(M||F)&&(c={...c,...Z_(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:h}=c;f=c.data;let b=!1;if(t.placeholderData!==void 0&&f===void 0&&h==="pending"){let O;n?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(O=n.data,b=!0):O=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,O!==void 0&&(h="success",f=su(n?.data,O,t),d=!0)}if(t.select&&f!==void 0&&!b)if(n&&f===i?.data&&t.select===this.#h)f=this.#p;else try{this.#h=t.select,f=t.select(f),f=su(n?.data,f,t),this.#p=f,this.#i=null}catch(O){this.#i=O}this.#i&&(p=this.#i,f=this.#p,g=Date.now(),h="error");const y=c.fetchStatus==="fetching",x=h==="pending",$=h==="error",v=x&&y,k=f!==void 0,I={status:h,fetchStatus:c.fetchStatus,isPending:x,isSuccess:h==="success",isError:$,isInitialLoading:v,isLoading:v,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:g,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&&!x,isLoadingError:$&&!k,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:$&&k,isStale:Oc(e,t),refetch:this.refetch,promise:this.#a,isEnabled:at(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const O=te=>{I.status==="error"?te.reject(I.error):I.data!==void 0&&te.resolve(I.data)},M=()=>{const te=this.#a=I.promise=uu();O(te)},F=this.#a;switch(F.status){case"pending":e.queryHash===r.queryHash&&O(F);break;case"fulfilled":(I.status==="error"||I.data!==F.value)&&M();break;case"rejected":(I.status!=="error"||I.error!==F.reason)&&M();break}}return I}updateResult(){const e=this.#o,t=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#s=this.options,this.#n.data!==void 0&&(this.#f=this.#t),iu(t,e))return;this.#o=t;const r=()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,n=typeof o=="function"?o():o;if(n==="all"||!n&&!this.#m.size)return!0;const i=new Set(n??this.#m);return this.options.throwOnError&&i.add("error"),Object.keys(this.#o).some(a=>{const s=a;return this.#o[s]!==e[s]&&i.has(s)})};this.#$({listeners:r()})}#x(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#r=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#$(e){ze.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#o)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ZO(e,t){return at(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function fp(e,t){return ZO(e,t)||e.state.data!==void 0&&cu(e,t,t.refetchOnMount)}function cu(e,t,r){if(at(t.enabled,e)!==!1&&rr(t.staleTime,e)!=="static"){const o=typeof r=="function"?r(e):r;return o==="always"||o!==!1&&Oc(e,t)}return!1}function mp(e,t,r,o){return(e!==t||at(o.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Oc(e,r)}function Oc(e,t){return at(t.enabled,e)!==!1&&e.isStaleByTime(rr(t.staleTime,e))}function FO(e,t){return!iu(e.getCurrentResult(),t)}function hp(e){return{onFetch:(t,r)=>{const o=t.options,n=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let s={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=M_(t.options,t.fetchOptions),p=async(g,h,b)=>{if(c)return Promise.reject();if(h==null&&g.pages.length)return Promise.resolve(g);const x=(()=>{const N={client:t.client,queryKey:t.queryKey,pageParam:h,direction:b?"backward":"forward",meta:t.options.meta};return d(N),N})(),$=await f(x),{maxPages:v}=t.options,k=b?CO:PO;return{pages:k(g.pages,$,v),pageParams:k(g.pageParams,h,v)}};if(n&&i.length){const g=n==="backward",h=g?qO:gp,b={pages:i,pageParams:a},y=h(o,b);s=await p(b,y,g)}else{const g=e??i.length;do{const h=l===0?a[0]??o.initialPageParam:gp(o,s);if(l>0&&h==null)break;s=await p(s,h),l++}while(l<g)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r):t.fetchFn=u}}}function gp(e,{pages:t,pageParams:r}){const o=t.length-1;return t.length>0?e.getNextPageParam(t[o],t,r[o],r):void 0}function qO(e,{pages:t,pageParams:r}){return t.length>0?e.getPreviousPageParam?.(t[0],t,r[0],r):void 0}var VO=class extends L_{#e;#t;#r;#o;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#r=e.mutationCache,this.#t=[],this.state=e.state||BO(),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.#r.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#o?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#n({type:"continue"})},r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#o=U_({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(i,a)=>{this.#n({type:"failed",failureCount:i,error:a})},onPause:()=>{this.#n({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)});const o=this.state.status==="pending",n=!this.#o.canStart();try{if(o)t();else{this.#n({type:"pending",variables:e,isPaused:n}),await this.#r.config.onMutate?.(e,this,r);const a=await this.options.onMutate?.(e,r);a!==this.state.context&&this.#n({type:"pending",context:a,variables:e,isPaused:n})}const i=await this.#o.start();return await this.#r.config.onSuccess?.(i,e,this.state.context,this,r),await this.options.onSuccess?.(i,e,this.state.context,r),await this.#r.config.onSettled?.(i,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(i,null,e,this.state.context,r),this.#n({type:"success",data:i}),i}catch(i){try{throw await this.#r.config.onError?.(i,e,this.state.context,this,r),await this.options.onError?.(i,e,this.state.context,r),await this.#r.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(void 0,i,e,this.state.context,r),i}finally{this.#n({type:"error",error:i})}}finally{this.#r.runNext(this)}}#n(e){const t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,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{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ze.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(e)}),this.#r.notify({mutation:this,type:"updated",action:e})})}};function BO(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var JO=class extends ko{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(e,t,r){const o=new VO({client:e,mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:r});return this.add(o),o}add(e){this.#e.add(e);const t=qo(e);if(typeof t=="string"){const r=this.#t.get(t);r?r.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=qo(e);if(typeof t=="string"){const r=this.#t.get(t);if(r)if(r.length>1){const o=r.indexOf(e);o!==-1&&r.splice(o,1)}else r[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=qo(e);if(typeof t=="string"){const o=this.#t.get(t)?.find(n=>n.state.status==="pending");return!o||o===e}else return!0}runNext(e){const t=qo(e);return typeof t=="string"?this.#t.get(t)?.find(o=>o!==e&&o.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ze.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(r=>up(t,r))}findAll(e={}){return this.getAll().filter(t=>up(e,t))}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ze.batch(()=>Promise.all(e.map(t=>t.continue().catch(Je))))}};function qo(e){return e.options.scope?.id}var WO=class extends ko{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,r){const o=t.queryKey,n=t.queryHash??Ec(o,t);let i=this.get(n);return i||(i=new UO({client:e,queryKey:o,queryHash:n,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(o)}),this.add(i)),i}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(){ze.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(r=>sp(t,r))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(r=>sp(e,r)):t}notify(e){ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ze.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ze.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},HO=class{#e;#t;#r;#o;#n;#s;#a;#i;constructor(e={}){this.#e=e.queryCache||new WO,this.#t=e.mutationCache||new JO,this.#r=e.defaultOptions||{},this.#o=new Map,this.#n=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#a=Tc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=ki.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#a?.(),this.#a=void 0,this.#i?.(),this.#i=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),r=this.#e.build(this,t),o=r.state.data;return o===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(rr(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(o))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:r})=>{const o=r.data;return[t,o]})}setQueryData(e,t,r){const o=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(o.queryHash)?.state.data,a=TO(t,i);if(a!==void 0)return this.#e.build(this,o).setData(a,{...r,manual:!0})}setQueriesData(e,t,r){return ze.batch(()=>this.#e.findAll(e).map(({queryKey:o})=>[o,this.setQueryData(o,t,r)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;ze.batch(()=>{t.findAll(e).forEach(r=>{t.remove(r)})})}resetQueries(e,t){const r=this.#e;return ze.batch(()=>(r.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const r={revert:!0,...t},o=ze.batch(()=>this.#e.findAll(e).map(n=>n.cancel(r)));return Promise.all(o).then(Je).catch(Je)}invalidateQueries(e,t={}){return ze.batch(()=>(this.#e.findAll(e).forEach(r=>{r.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const r={...t,cancelRefetch:t.cancelRefetch??!0},o=ze.batch(()=>this.#e.findAll(e).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(Je)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(o).then(Je)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const r=this.#e.build(this,t);return r.isStaleByTime(rr(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Je).catch(Je)}fetchInfiniteQuery(e){return e.behavior=hp(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Je).catch(Je)}ensureInfiniteQueryData(e){return e.behavior=hp(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ki.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#o.set(Mn(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#o.values()],r={};return t.forEach(o=>{Dn(e,o.queryKey)&&Object.assign(r,o.defaultOptions)}),r}setMutationDefaults(e,t){this.#n.set(Mn(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#n.values()],r={};return t.forEach(o=>{Dn(e,o.mutationKey)&&Object.assign(r,o.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ec(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===Ii&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},F_=_.createContext(void 0),q_=e=>{const t=_.useContext(F_);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},GO=({client:e,children:t})=>(_.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),m.jsx(F_.Provider,{value:e,children:t})),V_=_.createContext(!1),KO=()=>_.useContext(V_);V_.Provider;function YO(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var QO=_.createContext(YO()),XO=()=>_.useContext(QO),eN=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},tN=e=>{_.useEffect(()=>{e.clearReset()},[e])},rN=({result:e,errorResetBoundary:t,throwOnError:r,query:o,suspense:n})=>e.isError&&!t.isReset()&&!e.isFetching&&o&&(n&&e.data===void 0||jO(r,[e.error,o])),nN=e=>{if(e.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),o=e.staleTime;e.staleTime=typeof o=="function"?(...n)=>r(o(...n)):r(o),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},oN=(e,t)=>e.isLoading&&e.isFetching&&!t,iN=(e,t)=>e?.suspense&&t.isPending,vp=(e,t,r)=>t.fetchOptimistic(e).catch(()=>{r.clearReset()});function aN(e,t,r){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 o=KO(),n=XO(),i=q_(),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a),process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.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`)),a._optimisticResults=o?"isRestoring":"optimistic",nN(a),eN(a,n),tN(n);const s=!i.getQueryCache().get(a.queryHash),[l]=_.useState(()=>new t(i,a)),u=l.getOptimisticResult(a),c=!o&&e.subscribed!==!1;if(_.useSyncExternalStore(_.useCallback(d=>{const f=c?l.subscribe(ze.batchCalls(d)):Je;return l.updateResult(),f},[l,c]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),_.useEffect(()=>{l.setOptions(a)},[a,l]),iN(a,u))throw vp(a,l,n);if(rN({result:u,errorResetBoundary:n,throwOnError:a.throwOnError,query:i.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw u.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,u),a.experimental_prefetchInRender&&!_r&&oN(u,o)&&(s?vp(a,l,n):i.getQueryCache().get(a.queryHash)?.promise)?.catch(Je).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?u:l.trackResult(u)}function B_(e,t){return aN(e,LO)}function sN({auth:e,mcp:t,environment:r}){const o=Object.entries(e.headers??{}).map((i,a)=>`${i}:${a}`);return B_({queryKey:["mcpTools",t,...o],queryFn:async()=>(T.assert(!e.isLoading,"No auth found"),T.assert(t,"No MCP URL found"),await(await $O({name:"gram-elements-mcp-client",transport:{type:"http",url:t,headers:{...uN(r??{}),...e.headers}}})).tools()),enabled:!e.isLoading&&!!t,staleTime:1/0,gcTime:1/0})}const yp="MCP-";function uN(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[r,o])=>{const n=r.replace(/_/g,"-"),i=n.startsWith(yp)?n:`${yp}${n}`;return t[i]=o,t},{})}const J_=()=>{const e=z.useContext(T.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e};function lN(e){return(e.api?.url||""||"https://app.getgram.ai").replace(/\/+$/,"")}const Nc=["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"],cN=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{...r.description?{description:r.description}:void 0,parameters:r.parameters instanceof vi.ZodType?vi.toJSONSchema(r.parameters):r.parameters}])),dN=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let Ei=null;function pN(e,t){Ei={helpers:e,toolsRequiringApproval:new Set(t)}}function fN(){Ei=null}const mN=(e,t)=>L.makeAssistantTool({...e,execute:async(r,o)=>{if(Ei?.toolsRequiringApproval.has(t)){const{helpers:n}=Ei,i=o.toolCallId??"";if(!n.isToolApproved(t)&&!await n.requestApproval(t,i,r))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?.(r,o)},toolName:t});function hN(e,t,r){if(!t||t.length===0)return e;const o=new Set(t);return Object.fromEntries(Object.entries(e).map(([n,i])=>{if(!o.has(n))return[n,i];const a=i.execute;return a?[n,{...i,execute:async(s,l)=>{const u=l??{},c=u.toolCallId??"";return r.isToolApproved(n)||await r.requestApproval(n,c,s)?a(s,u):{content:[{type:"text",text:`Tool "${n}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}}]:[n,i]}))}const gN=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],vN=T.createLucideIcon("arrow-down",gN);const yN=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],bN=T.createLucideIcon("arrow-up",yN);const _N=[["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"}]],wN=T.createLucideIcon("brain",_N);const xN=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],nr=T.createLucideIcon("check",xN);const $N=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ti=T.createLucideIcon("chevron-down",$N);const SN=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],IN=T.createLucideIcon("chevron-left",SN);const kN=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],W_=T.createLucideIcon("chevron-right",kN);const EN=[["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"}]],Pc=T.createLucideIcon("copy",EN);const TN=[["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"}]],ON=T.createLucideIcon("file-text",TN);const NN=[["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"}]],Oi=T.createLucideIcon("loader",NN);const PN=[["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"}]],CN=T.createLucideIcon("maximize",PN);const jN=[["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"}]],AN=T.createLucideIcon("message-circle",jN);const RN=[["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"}]],zN=T.createLucideIcon("minimize",RN);const MN=[["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"}]],DN=T.createLucideIcon("panel-right-close",MN);const UN=[["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"}]],LN=T.createLucideIcon("panel-right-open",UN);const ZN=[["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"}]],FN=T.createLucideIcon("pencil",ZN);const qN=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],VN=T.createLucideIcon("plus",qN);const BN=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],JN=T.createLucideIcon("refresh-cw",BN);const WN=[["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"}]],HN=T.createLucideIcon("settings-2",WN);const GN=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],KN=T.createLucideIcon("square",GN);const YN=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Eo=T.createLucideIcon("x",YN);var To=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const n=()=>{const i=r.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=r[Math.random()*i|0];return a.join("")};if(e==null)return n;if(r.includes(o))throw new Ji({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${r}".`});return()=>`${e}${o}${n()}`},H_=To();function bp(e=globalThis){var t,r,o;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(r=e.process)==null?void 0:r.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fr(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,o)=>{t[o.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,o]of e)o!=null&&(t[r.toLowerCase()]=o)}return t}function _p(e,...t){const r=new Headers(fr(e)),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var QN=/"__proto__"\s*:/,XN=/"constructor"\s*:/;function wp(e){const t=JSON.parse(e);return t===null||typeof t!="object"||QN.test(e)===!1&&XN.test(e)===!1?t:eP(t)}function eP(e){let t=[e];for(;t.length;){const r=t;t=[];for(const o of r){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in o){const i=o[n];i&&typeof i=="object"&&t.push(i)}}}return e}function tP(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return wp(e)}try{return wp(e)}finally{Error.stackTraceLimit=t}}var Ni=Symbol.for("vercel.ai.validator");function rP(e){return{[Ni]:!0,validate:e}}function nP(e){return typeof e=="object"&&e!==null&&Ni in e&&e[Ni]===!0&&"validate"in e}function oP(e){let t;return()=>(t==null&&(t=e()),t)}function iP(e){return nP(e)?e:typeof e=="function"?e():aP(e)}function aP(e){return rP(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Ft({value:t,cause:r.issues})}})}async function xp({value:e,schema:t}){const r=await Cc({value:e,schema:t});if(!r.success)throw Ft.wrap({value:e,cause:r.error});return r.value}async function Cc({value:e,schema:t}){const r=iP(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:Ft.wrap({value:e,cause:o.error}),rawValue:e}}catch(o){return{success:!1,error:Ft.wrap({value:e,cause:o}),rawValue:e}}}async function Pi({text:e,schema:t}){try{const r=tP(e);return t==null?{success:!0,value:r,rawValue:r}:await Cc({value:r,schema:t})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:e,cause:r}),rawValue:void 0}}}function sP({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).pipeThrough(new TransformStream({async transform({data:r},o){r!=="[DONE]"&&o.enqueue(await Pi({text:r,schema:t}))}}))}async function Ar(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}function ri(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const r in t)t[r]=ri(t[r])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>ri(t)):e.items=ri(e.items)),e}var uP=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},lP=Symbol("Let zodToJsonSchema decide on which parser to use"),$p={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"},cP=e=>typeof e=="string"?{...$p,name:e}:{...$p,...e};function et(){return{}}function dP(e,t){var r,o,n;const i={type:"array"};return(r=e.type)!=null&&r._def&&((n=(o=e.type)==null?void 0:o._def)==null?void 0:n.typeName)!==A.ZodAny&&(i.items=le(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}function pP(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function fP(){return{type:"boolean"}}function G_(e,t){return le(e.type._def,t)}var mP=(e,t)=>le(e.innerType._def,t);function K_(e,t,r){const o=r??t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>K_(e,t,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return hP(e)}}var hP=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function gP(e,t){return{...le(e.innerType._def,t),default:e.defaultValue()}}function vP(e,t){return t.effectStrategy==="input"?le(e.schema._def,t):et()}function yP(e){return{type:"string",enum:Array.from(e.values)}}var bP=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function _P(e,t){const r=[le(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),le(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(n=>!!n),o=[];return r.forEach(n=>{if(bP(n))o.push(...n.allOf);else{let i=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:a,...s}=n;i=s}o.push(i)}}),o.length?{allOf:o}:void 0}function wP(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 bs=void 0,ht={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:()=>(bs===void 0&&(bs=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),bs),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 Y_(e,t){const r={type:"string"};if(e.checks)for(const o of e.checks)switch(o.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value;break;case"email":switch(t.emailStrategy){case"format:email":gt(r,"email",o.message,t);break;case"format:idn-email":gt(r,"idn-email",o.message,t);break;case"pattern:zod":Fe(r,ht.email,o.message,t);break}break;case"url":gt(r,"uri",o.message,t);break;case"uuid":gt(r,"uuid",o.message,t);break;case"regex":Fe(r,o.regex,o.message,t);break;case"cuid":Fe(r,ht.cuid,o.message,t);break;case"cuid2":Fe(r,ht.cuid2,o.message,t);break;case"startsWith":Fe(r,RegExp(`^${_s(o.value,t)}`),o.message,t);break;case"endsWith":Fe(r,RegExp(`${_s(o.value,t)}$`),o.message,t);break;case"datetime":gt(r,"date-time",o.message,t);break;case"date":gt(r,"date",o.message,t);break;case"time":gt(r,"time",o.message,t);break;case"duration":gt(r,"duration",o.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value;break;case"includes":{Fe(r,RegExp(_s(o.value,t)),o.message,t);break}case"ip":{o.version!=="v6"&>(r,"ipv4",o.message,t),o.version!=="v4"&>(r,"ipv6",o.message,t);break}case"base64url":Fe(r,ht.base64url,o.message,t);break;case"jwt":Fe(r,ht.jwt,o.message,t);break;case"cidr":{o.version!=="v6"&&Fe(r,ht.ipv4Cidr,o.message,t),o.version!=="v4"&&Fe(r,ht.ipv6Cidr,o.message,t);break}case"emoji":Fe(r,ht.emoji(),o.message,t);break;case"ulid":{Fe(r,ht.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{gt(r,"binary",o.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Fe(r,ht.base64,o.message,t);break}}break}case"nanoid":Fe(r,ht.nanoid,o.message,t)}return r}function _s(e,t){return t.patternStrategy==="escape"?$P(e):e}var xP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $P(e){let t="";for(let r=0;r<e.length;r++)xP.has(e[r])||(t+="\\"),t+=e[r];return t}function gt(e,t,r,o){var n;e.format||(n=e.anyOf)!=null&&n.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&o.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function Fe(e,t,r,o){var n;e.pattern||(n=e.allOf)!=null&&n.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Sp(t,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Sp(t,o)}function Sp(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const o={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=o.i?e.source.toLowerCase():e.source;let i="",a=!1,s=!1,l=!1;for(let u=0;u<n.length;u++){if(a){i+=n[u],a=!1;continue}if(o.i){if(s){if(n[u].match(/[a-z]/)){l?(i+=n[u],i+=`${n[u-2]}-${n[u]}`.toUpperCase(),l=!1):n[u+1]==="-"&&((r=n[u+2])!=null&&r.match(/[a-z]/))?(i+=n[u],l=!0):i+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){i+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(o.m){if(n[u]==="^"){i+=`(^|(?<=[\r
|
|
30
|
-
|
|
31
|
-
]))`;continue}}if(o.s&&n[u]==="."){i+=s?`${n[u]}\r
|
|
32
|
-
|
|
33
|
-
]`;continue}i+=n[u],n[u]==="\\"?a=!0:s&&n[u]==="]"?s=!1:!s&&n[u]==="["&&(s=!0)}try{new RegExp(i)}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 i}function Q_(e,t){var r,o,n,i,a,s;const l={type:"object",additionalProperties:(r=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((o=e.keyType)==null?void 0:o._def.typeName)===A.ZodString&&((n=e.keyType._def.checks)!=null&&n.length)){const{type:u,...c}=Y_(e.keyType._def,t);return{...l,propertyNames:c}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===A.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===A.ZodBranded&&e.keyType._def.type._def.typeName===A.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:u,...c}=G_(e.keyType._def,t);return{...l,propertyNames:c}}}return l}function SP(e,t){if(t.mapStrategy==="record")return Q_(e,t);const r=le(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||et(),o=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||et();return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function IP(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function kP(){return{not:et()}}function EP(){return{type:"null"}}var du={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function TP(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in du&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=du[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return OP(e,t)}var OP=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>le(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function NP(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[du[e.innerType._def.typeName],"null"]};const r=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function PP(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function CP(e,t){const r={type:"object",properties:{}},o=[],n=e.shape();for(const a in n){let s=n[a];if(s===void 0||s._def===void 0)continue;const l=AP(s),u=le(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,l||o.push(a))}o.length&&(r.required=o);const i=jP(e,t);return i!==void 0&&(r.additionalProperties=i),r}function jP(e,t){if(e.catchall._def.typeName!=="ZodNever")return le(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 AP(e){try{return e.isOptional()}catch{return!0}}var RP=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return le(e.innerType._def,t);const o=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return o?{anyOf:[{not:et()},o]}:et()},zP=(e,t)=>{if(t.pipeStrategy==="input")return le(e.in._def,t);if(t.pipeStrategy==="output")return le(e.out._def,t);const r=le(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=le(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function MP(e,t){return le(e.type._def,t)}function DP(e,t){const o={type:"array",uniqueItems:!0,items:le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(o.minItems=e.minSize.value),e.maxSize&&(o.maxItems=e.maxSize.value),o}function UP(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>le(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:le(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>le(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function LP(){return{not:et()}}function ZP(){return et()}var FP=(e,t)=>le(e.innerType._def,t),qP=(e,t,r)=>{switch(t){case A.ZodString:return Y_(e,r);case A.ZodNumber:return PP(e);case A.ZodObject:return CP(e,r);case A.ZodBigInt:return pP(e);case A.ZodBoolean:return fP();case A.ZodDate:return K_(e,r);case A.ZodUndefined:return LP();case A.ZodNull:return EP();case A.ZodArray:return dP(e,r);case A.ZodUnion:case A.ZodDiscriminatedUnion:return TP(e,r);case A.ZodIntersection:return _P(e,r);case A.ZodTuple:return UP(e,r);case A.ZodRecord:return Q_(e,r);case A.ZodLiteral:return wP(e);case A.ZodEnum:return yP(e);case A.ZodNativeEnum:return IP(e);case A.ZodNullable:return NP(e,r);case A.ZodOptional:return RP(e,r);case A.ZodMap:return SP(e,r);case A.ZodSet:return DP(e,r);case A.ZodLazy:return()=>e.getter()._def;case A.ZodPromise:return MP(e,r);case A.ZodNaN:case A.ZodNever:return kP();case A.ZodEffects:return vP(e,r);case A.ZodAny:return et();case A.ZodUnknown:return ZP();case A.ZodDefault:return gP(e,r);case A.ZodBranded:return G_(e,r);case A.ZodReadonly:return FP(e,r);case A.ZodCatch:return mP(e,r);case A.ZodPipeline:return zP(e,r);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(o=>{})()}};function le(e,t,r=!1){var o;const n=t.seen.get(e);if(t.override){const l=(o=t.override)==null?void 0:o.call(t,e,t,n,r);if(l!==lP)return l}if(n&&!r){const l=VP(n,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=qP(e,e.typeName,t),s=typeof a=="function"?le(a(),t):a;if(s&&BP(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return i.jsonSchema=s,l}return i.jsonSchema=s,s}var VP=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:uP(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),et()):t.$refStrategy==="seen"?et():void 0}},BP=(e,t,r)=>(e.description&&(r.description=e.description),r),JP=e=>{const t=cP(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([o,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,o],jsonSchema:void 0}]))}},WP=(e,t)=>{var r;const o=JP(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,d])=>{var f;return{...u,[c]:(f=le(d._def,{...o,currentPath:[...o.basePath,o.definitionPath,c]},!0))!=null?f:et()}},{}):void 0;const i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=le(e._def,i===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,i]},!1))!=null?r:et(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const l=i===void 0?n?{...a,[o.definitionPath]:n}:a:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,i].join("/"),[o.definitionPath]:{...n,[i]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},HP=WP;function GP(e,t){var r;const o=(r=void 0)!=null?r:!1;return Va(()=>HP(e,{$refStrategy:o?"root":"none"}),{validate:async n=>{const i=await e.safeParseAsync(n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function KP(e,t){var r;const o=(r=void 0)!=null?r:!1;return Va(()=>ri(fa(e,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async n=>{const i=await ma(e,n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function YP(e){return"_zod"in e}function X_(e,t){return YP(e)?KP(e):GP(e)}var pu=Symbol.for("vercel.ai.schema");function Va(e,{validate:t}={}){return{[pu]:!0,_type:void 0,[Ni]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function QP(e){return typeof e=="object"&&e!==null&&pu in e&&e[pu]===!0&&"jsonSchema"in e&&"validate"in e}function XP(e){return e==null?Va({properties:{},additionalProperties:!1}):QP(e)?e:typeof e=="function"?e():X_(e)}function eC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tC=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},gr="1.9.0",Ip=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function rC(e){var t=new Set([e]),r=new Set,o=e.match(Ip);if(!o)return function(){return!1};var n={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(n.prerelease!=null)return function(l){return l===e};function i(s){return r.add(s),!1}function a(s){return t.add(s),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var u=l.match(Ip);if(!u)return i(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||n.major!==c.major?i(l):n.major===0?n.minor===c.minor&&n.patch<=c.patch?a(l):i(l):n.minor<=c.minor?a(l):i(l)}}var nC=rC(gr),oC=gr.split(".")[0],Un=Symbol.for("opentelemetry.js.api."+oC),Ln=tC;function jc(e,t,r,o){var n;o===void 0&&(o=!1);var i=Ln[Un]=(n=Ln[Un])!==null&&n!==void 0?n:{version:gr};if(!o&&i[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(i.version!==gr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+gr);return r.error(a.stack||a.message),!1}return i[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+gr+"."),!0}function Zn(e){var t,r,o=(t=Ln[Un])===null||t===void 0?void 0:t.version;if(!(!o||!nC(o)))return(r=Ln[Un])===null||r===void 0?void 0:r[e]}function Ac(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+gr+".");var r=Ln[Un];r&&delete r[e]}var iC=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(s){a={error:s}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return i},aC=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},sC=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return _n("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return _n("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return _n("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return _n("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return _n("verbose",this._namespace,t)},e})();function _n(e,t,r){var o=Zn("diag");if(o)return r.unshift(t),o[e].apply(o,aC([],iC(r),!1))}var Ke;(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"})(Ke||(Ke={}));function uC(e,t){e<Ke.NONE?e=Ke.NONE:e>Ke.ALL&&(e=Ke.ALL),t=t||{};function r(o,n){var i=t[o];return typeof i=="function"&&e>=n?i.bind(t):function(){}}return{error:r("error",Ke.ERROR),warn:r("warn",Ke.WARN),info:r("info",Ke.INFO),debug:r("debug",Ke.DEBUG),verbose:r("verbose",Ke.VERBOSE)}}var lC=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(s){a={error:s}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return i},cC=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},dC="diag",Ci=(function(){function e(){function t(n){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Zn("diag");if(s)return s[n].apply(s,cC([],lC(i),!1))}}var r=this,o=function(n,i){var a,s,l;if(i===void 0&&(i={logLevel:Ke.INFO}),n===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=u.stack)!==null&&a!==void 0?a:u.message),!1}typeof i=="number"&&(i={logLevel:i});var c=Zn("diag"),d=uC((s=i.logLevel)!==null&&s!==void 0?s:Ke.INFO,n);if(c&&!i.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 jc("diag",d,r,!0)};r.setLogger=o,r.disable=function(){Ac(dC,r)},r.createComponentLogger=function(n){return new sC(n)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function pC(e){return Symbol.for(e)}var fC=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(o){return r._currentContext.get(o)},r.setValue=function(o,n){var i=new e(r._currentContext);return i._currentContext.set(o,n),i},r.deleteValue=function(o){var n=new e(r._currentContext);return n._currentContext.delete(o),n}}return e})(),mC=new fC,hC=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(s){a={error:s}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return i},gC=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},vC=(function(){function e(){}return e.prototype.active=function(){return mC},e.prototype.with=function(t,r,o){for(var n=[],i=3;i<arguments.length;i++)n[i-3]=arguments[i];return r.call.apply(r,gC([o],hC(n),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),yC=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(s){a={error:s}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return i},bC=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},ws="context",_C=new vC,ew=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return jc(ws,t,Ci.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,o){for(var n,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(n=this._getContextManager()).with.apply(n,bC([t,r,o],yC(i),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Zn(ws)||_C},e.prototype.disable=function(){this._getContextManager().disable(),Ac(ws,Ci.instance())},e})(),fu;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(fu||(fu={}));var tw="0000000000000000",rw="00000000000000000000000000000000",wC={traceId:rw,spanId:tw,traceFlags:fu.NONE},On=(function(){function e(t){t===void 0&&(t=wC),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){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,r){},e})(),Rc=pC("OpenTelemetry Context Key SPAN");function zc(e){return e.getValue(Rc)||void 0}function xC(){return zc(ew.getInstance().active())}function Mc(e,t){return e.setValue(Rc,t)}function $C(e){return e.deleteValue(Rc)}function SC(e,t){return Mc(e,new On(t))}function nw(e){var t;return(t=zc(e))===null||t===void 0?void 0:t.spanContext()}var IC=/^([0-9a-f]{32})$/i,kC=/^[0-9a-f]{16}$/i;function EC(e){return IC.test(e)&&e!==rw}function TC(e){return kC.test(e)&&e!==tw}function ow(e){return EC(e.traceId)&&TC(e.spanId)}function OC(e){return new On(e)}var xs=ew.getInstance(),iw=(function(){function e(){}return e.prototype.startSpan=function(t,r,o){o===void 0&&(o=xs.active());var n=!!r?.root;if(n)return new On;var i=o&&nw(o);return NC(i)&&ow(i)?new On(i):new On},e.prototype.startActiveSpan=function(t,r,o,n){var i,a,s;if(!(arguments.length<2)){arguments.length===2?s=r:arguments.length===3?(i=r,s=o):(i=r,a=o,s=n);var l=a??xs.active(),u=this.startSpan(t,i,l),c=Mc(l,u);return xs.with(c,s,void 0,u)}},e})();function NC(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var PC=new iw,CC=(function(){function e(t,r,o,n){this._provider=t,this.name=r,this.version=o,this.options=n}return e.prototype.startSpan=function(t,r,o){return this._getTracer().startSpan(t,r,o)},e.prototype.startActiveSpan=function(t,r,o,n){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,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):PC},e})(),jC=(function(){function e(){}return e.prototype.getTracer=function(t,r,o){return new iw},e})(),AC=new jC,kp=(function(){function e(){}return e.prototype.getTracer=function(t,r,o){var n;return(n=this.getDelegateTracer(t,r,o))!==null&&n!==void 0?n:new CC(this,t,r,o)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:AC},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,o){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,r,o)},e})(),ji;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ji||(ji={}));var $s="trace",RC=(function(){function e(){this._proxyTracerProvider=new kp,this.wrapSpanContext=OC,this.isSpanContextValid=ow,this.deleteSpan=$C,this.getSpan=zc,this.getActiveSpan=xC,this.getSpanContext=nw,this.setSpan=Mc,this.setSpanContext=SC}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=jc($s,this._proxyTracerProvider,Ci.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Zn($s)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ac($s,Ci.instance()),this._proxyTracerProvider=new kp},e})(),zC=RC.getInstance(),MC=Object.defineProperty,DC=(e,t)=>{for(var r in t)MC(e,r,{get:t[r],enumerable:!0})},aw="AI_NoObjectGeneratedError",sw=`vercel.ai.error.${aw}`,UC=Symbol.for(sw),uw,Ep=class extends Y{constructor({message:t="No object generated.",cause:r,text:o,response:n,usage:i,finishReason:a}){super({name:aw,message:t,cause:r}),this[uw]=!0,this.text=o,this.response=n,this.usage=i,this.finishReason=a}static isInstance(t){return Y.hasMarker(t,sw)}};uw=UC;var Tp="5.0.116",lw=G([w(),Rt(Uint8Array),Rt(ArrayBuffer),So(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]),Fn=xo(()=>G([yo(),w(),q(),pe(),Xe(w(),Fn),R(Fn)])),ke=Xe(w(),Xe(w(),Fn)),cw=E({type:C("text"),text:w(),providerOptions:ke.optional()}),LC=E({type:C("image"),image:G([lw,Rt(URL)]),mediaType:w().optional(),providerOptions:ke.optional()}),dw=E({type:C("file"),data:G([lw,Rt(URL)]),filename:w().optional(),mediaType:w(),providerOptions:ke.optional()}),ZC=E({type:C("reasoning"),text:w(),providerOptions:ke.optional()}),FC=E({type:C("tool-call"),toolCallId:w(),toolName:w(),input:$e(),providerOptions:ke.optional(),providerExecuted:pe().optional()}),qC=za("type",[E({type:C("text"),value:w()}),E({type:C("json"),value:Fn}),E({type:C("error-text"),value:w()}),E({type:C("error-json"),value:Fn}),E({type:C("content"),value:R(G([E({type:C("text"),text:w()}),E({type:C("media"),data:w(),mediaType:w()})]))})]),pw=E({type:C("tool-result"),toolCallId:w(),toolName:w(),output:qC,providerOptions:ke.optional()}),VC=E({role:C("system"),content:w(),providerOptions:ke.optional()}),BC=E({role:C("user"),content:G([w(),R(G([cw,LC,dw]))]),providerOptions:ke.optional()}),JC=E({role:C("assistant"),content:G([w(),R(G([cw,dw,ZC,FC,pw]))]),providerOptions:ke.optional()}),WC=E({role:C("tool"),content:R(pw),providerOptions:ke.optional()});G([VC,BC,JC,WC]);To({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
29
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const a=o[1];if(t===o[0]){r(o);continue}if(e.external){const u=e.external.registry.get(o[0])?.id;if(t!==o[0]&&u){r(o);continue}}if(e.metadataRegistry.get(o[0])?.id){r(o);continue}if(a.cycle){r(o);continue}if(a.count>1&&e.reused==="ref"){r(o);continue}}}function ri(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=a=>{const s=e.seen.get(a),u=s.def??s.schema,l={...u};if(s.ref===null)return;const c=s.ref;if(s.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")?(u.allOf=u.allOf??[],u.allOf.push(d)):(Object.assign(u,d),Object.assign(u,l))}s.isParent||e.override({zodSchema:a,jsonSchema:u,path:s.path??[]})};for(const a of[...e.seen.entries()].reverse())i(a[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 a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const a of e.seen.entries()){const s=a[1];s.def&&s.defId&&(o[s.defId]=s.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Zi(t,"input"),output:Zi(t,"output")}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function lt(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 lt(i.element,n);if(i.type==="set")return lt(i.valueType,n);if(i.type==="lazy")return lt(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 lt(i.innerType,n);if(i.type==="intersection")return lt(i.left,n)||lt(i.right,n);if(i.type==="record"||i.type==="map")return lt(i.keyType,n)||lt(i.valueType,n);if(i.type==="pipe")return lt(i.in,n)||lt(i.out,n);if(i.type==="object"){for(const r in i.shape)if(lt(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(const r of i.options)if(lt(r,n))return!0;return!1}if(i.type==="tuple"){for(const r of i.items)if(lt(r,n))return!0;return!!(i.rest&<(i.rest,n))}return!1}const wx=(e,t={})=>n=>{const i=ti({...n,processors:t});return $e(e,i),ni(i,e),ri(i,e)},Zi=(e,t)=>n=>{const{libraryOptions:i,target:r}=n??{},o=ti({...i??{},target:r,io:t,processors:{}});return $e(e,o),ni(o,e),ri(o,e)},HR={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},xx=(e,t,n,i)=>{const r=n;r.type="string";const{minimum:o,maximum:a,format:s,patterns:u,contentEncoding:l}=e._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof a=="number"&&(r.maxLength=a),s&&(r.format=HR[s]??s,r.format===""&&delete r.format),l&&(r.contentEncoding=l),u&&u.size>0){const c=[...u];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}))])}},Sx=(e,t,n,i)=>{const r=n,{minimum:o,maximum:a,format:s,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;typeof s=="string"&&s.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 l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof a=="number"&&(r.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof u=="number"&&(r.multipleOf=u)},Ix=(e,t,n,i)=>{n.type="boolean"},kx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Ex=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Tx=(e,t,n,i)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},$x=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Cx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Ax=(e,t,n,i)=>{n.not={}},Px=(e,t,n,i)=>{},Rx=(e,t,n,i)=>{},Ox=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Nx=(e,t,n,i)=>{const r=e._zod.def,o=hd(r.entries);o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),n.enum=o},jx=(e,t,n,i)=>{const r=e._zod.def,o=[];for(const a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){const a=o[0];n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[a]:n.const=a}else o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),o.every(a=>typeof a=="boolean")&&(n.type="boolean"),o.every(a=>a===null)&&(n.type="null"),n.enum=o},Mx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},zx=(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},Dx=(e,t,n,i)=>{const r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:u}=e._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),u?u.length===1?(o.contentMediaType=u[0],Object.assign(r,o)):r.anyOf=u.map(l=>({...o,contentMediaType:l})):Object.assign(r,o)},Ux=(e,t,n,i)=>{n.type="boolean"},Lx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Fx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Bx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Zx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},qx=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Vx=(e,t,n,i)=>{const r=n,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(r.minItems=a),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=$e(o.element,t,{...i,path:[...i.path,"items"]})},Hx=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const a=o.shape;for(const l in a)r.properties[l]=$e(a[l],t,{...i,path:[...i.path,"properties",l]});const s=new Set(Object.keys(a)),u=new Set([...s].filter(l=>{const c=o.shape[l]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));u.size>0&&(r.required=Array.from(u)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=$e(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},up=(e,t,n,i)=>{const r=e._zod.def,o=r.inclusive===!1,a=r.options.map((s,u)=>$e(s,t,{...i,path:[...i.path,o?"oneOf":"anyOf",u]}));o?n.oneOf=a:n.anyOf=a},Jx=(e,t,n,i)=>{const r=e._zod.def,o=$e(r.left,t,{...i,path:[...i.path,"allOf",0]}),a=$e(r.right,t,{...i,path:[...i.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=u},Wx=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="array";const a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((f,p)=>$e(f,t,{...i,path:[...i.path,a,p]})),l=o.rest?$e(o.rest,t,{...i,path:[...i.path,s,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=u,l&&(r.items=l)):t.target==="openapi-3.0"?(r.items={anyOf:u},l&&r.items.anyOf.push(l),r.minItems=u.length,l||(r.maxItems=u.length)):(r.items=u,l&&(r.additionalItems=l));const{minimum:c,maximum:d}=e._zod.bag;typeof c=="number"&&(r.minItems=c),typeof d=="number"&&(r.maxItems=d)},Gx=(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=$e(o.keyType,t,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=$e(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})},Kx=(e,t,n,i)=>{const r=e._zod.def,o=$e(r.innerType,t,i),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Yx=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},Qx=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Xx=(e,t,n,i)=>{const r=e._zod.def;$e(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)))},eS=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},tS=(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;$e(o,t,i);const a=t.seen.get(e);a.ref=o},nS=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},rS=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},iS=(e,t,n,i)=>{const r=e._zod.def;$e(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},oS=(e,t,n,i)=>{const r=e._zod.innerType;$e(r,t,i);const o=t.seen.get(e);o.ref=r},hc={string:xx,number:Sx,boolean:Ix,bigint:kx,symbol:Ex,null:Tx,undefined:$x,void:Cx,never:Ax,any:Px,unknown:Rx,date:Ox,enum:Nx,literal:jx,nan:Mx,template_literal:zx,file:Dx,success:Ux,custom:Lx,function:Fx,transform:Bx,map:Zx,set:qx,array:Vx,object:Hx,union:up,intersection:Jx,tuple:Wx,record:Gx,nullable:Kx,nonoptional:Yx,default:Qx,prefault:Xx,catch:eS,pipe:tS,readonly:nS,promise:rS,optional:iS,lazy:oS};function nl(e,t){if("_idmap"in e){const i=e,r=ti({...t,processors:hc}),o={};for(const u of i._idmap.entries()){const[l,c]=u;$e(c,r)}const a={},s={registry:i,uri:t?.uri,defs:o};r.external=s;for(const u of i._idmap.entries()){const[l,c]=u;ni(r,c),a[l]=ri(r,c)}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:o}}return{schemas:a}}const n=ti({...t,processors:hc});return $e(e,n),ni(n,e),ri(n,e)}class JR{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=ti({processors:hc,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 $e(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)),ni(this.ctx,t);const i=ri(this.ctx,t),{"~standard":r,...o}=i;return o}}const WR=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),GR=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:J_,$ZodArray:Q_,$ZodAsyncError:fr,$ZodBase64:j_,$ZodBase64URL:z_,$ZodBigInt:Nd,$ZodBigIntFormat:Z_,$ZodBoolean:Od,$ZodCIDRv4:O_,$ZodCIDRv6:N_,$ZodCUID:w_,$ZodCUID2:x_,$ZodCatch:bw,$ZodCheck:De,$ZodCheckBigIntFormat:Yb,$ZodCheckEndsWith:u_,$ZodCheckGreaterThan:Ad,$ZodCheckIncludes:s_,$ZodCheckLengthEquals:r_,$ZodCheckLessThan:Cd,$ZodCheckLowerCase:o_,$ZodCheckMaxLength:t_,$ZodCheckMaxSize:Qb,$ZodCheckMimeType:d_,$ZodCheckMinLength:n_,$ZodCheckMinSize:Xb,$ZodCheckMultipleOf:Gb,$ZodCheckNumberFormat:Kb,$ZodCheckOverwrite:p_,$ZodCheckProperty:c_,$ZodCheckRegex:i_,$ZodCheckSizeEquals:e_,$ZodCheckStartsWith:l_,$ZodCheckStringFormat:Io,$ZodCheckUpperCase:a_,$ZodCodec:Md,$ZodCustom:Tw,$ZodCustomStringFormat:F_,$ZodDate:Y_,$ZodDefault:mw,$ZodDiscriminatedUnion:iw,$ZodE164:D_,$ZodEmail:v_,$ZodEmoji:b_,$ZodEncodeError:Ms,$ZodEnum:uw,$ZodError:gd,$ZodFile:dw,$ZodFunction:Iw,$ZodGUID:m_,$ZodIPv4:A_,$ZodIPv6:P_,$ZodISODate:T_,$ZodISODateTime:E_,$ZodISODuration:C_,$ZodISOTime:$_,$ZodIntersection:ow,$ZodJWT:L_,$ZodKSUID:k_,$ZodLazy:Ew,$ZodLiteral:cw,$ZodMAC:R_,$ZodMap:sw,$ZodNaN:_w,$ZodNanoID:__,$ZodNever:G_,$ZodNonOptional:vw,$ZodNull:H_,$ZodNullable:hw,$ZodNumber:Rd,$ZodNumberFormat:B_,$ZodObject:tw,$ZodObjectJIT:nw,$ZodOptional:fw,$ZodPipe:ww,$ZodPrefault:gw,$ZodPromise:kw,$ZodReadonly:xw,$ZodRealError:At,$ZodRecord:aw,$ZodRegistry:Nw,$ZodSet:lw,$ZodString:ko,$ZodStringFormat:Ce,$ZodSuccess:yw,$ZodSymbol:q_,$ZodTemplateLiteral:Sw,$ZodTransform:pw,$ZodTuple:jd,$ZodType:ce,$ZodULID:S_,$ZodURL:y_,$ZodUUID:g_,$ZodUndefined:V_,$ZodUnion:Fs,$ZodUnknown:W_,$ZodVoid:K_,$ZodXID:I_,$ZodXor:rw,$brand:Zy,$constructor:R,$input:Ow,$output:Rw,Doc:f_,JSONSchema:WR,JSONSchemaGenerator:JR,NEVER:fd,TimePrecision:Dw,_any:ox,_array:px,_base64:ep,_base64url:tp,_bigint:Qw,_boolean:Kw,_catch:LR,_check:vx,_cidrv4:Qd,_cidrv6:Xd,_coercedBigint:Xw,_coercedBoolean:Yw,_coercedDate:cx,_coercedNumber:qw,_coercedString:Mw,_cuid:Vd,_cuid2:Hd,_custom:hx,_date:ux,_decode:_d,_decodeAsync:xd,_default:zR,_discriminatedUnion:kR,_e164:np,_email:Dd,_emoji:Zd,_encode:bd,_encodeAsync:wd,_endsWith:Gs,_enum:PR,_file:fx,_float32:Hw,_float64:Jw,_gt:Yn,_gte:ft,_guid:Qa,_includes:Js,_int:Vw,_int32:Ww,_int64:ex,_intersection:ER,_ipv4:Kd,_ipv6:Yd,_isoDate:Lw,_isoDateTime:Uw,_isoDuration:Bw,_isoTime:Fw,_jwt:rp,_ksuid:Gd,_lazy:qR,_length:$o,_literal:OR,_lowercase:Vs,_lt:Kn,_lte:Dt,_mac:zw,_map:CR,_max:Dt,_maxLength:To,_maxSize:Eo,_mime:Ks,_min:ft,_minLength:gr,_minSize:ei,_multipleOf:Xr,_nan:dx,_nanoid:qd,_nativeEnum:RR,_negative:op,_never:sx,_nonnegative:sp,_nonoptional:DR,_nonpositive:ap,_normalize:Ys,_null:ix,_nullable:MR,_number:Zw,_optional:jR,_overwrite:jn,_parse:yo,_parseAsync:bo,_pipe:FR,_positive:ip,_promise:VR,_property:lp,_readonly:BR,_record:$R,_refine:mx,_regex:qs,_safeDecode:Id,_safeDecodeAsync:Ed,_safeEncode:Sd,_safeEncodeAsync:kd,_safeParse:_o,_safeParseAsync:wo,_set:AR,_size:Zs,_slugify:tl,_startsWith:Ws,_string:jw,_stringFormat:Co,_stringbool:_x,_success:UR,_superRefine:gx,_symbol:nx,_templateLiteral:ZR,_toLowerCase:Xs,_toUpperCase:el,_transform:NR,_trim:Qs,_tuple:TR,_uint32:Gw,_uint64:tx,_ulid:Jd,_undefined:rx,_union:SR,_unknown:ax,_uppercase:Hs,_url:Bs,_uuid:Ud,_uuidv4:Ld,_uuidv6:Fd,_uuidv7:Bd,_void:lx,_xid:Wd,_xor:IR,clone:Bt,config:tt,createStandardJSONSchemaMethod:Zi,createToJSONSchemaMethod:wx,decode:iP,decodeAsync:aP,describe:yx,encode:rP,encodeAsync:oP,extractDefs:ni,finalize:ri,flattenError:vd,formatError:yd,globalConfig:Wa,globalRegistry:Yt,initializeContext:ti,isValidBase64:Pd,isValidBase64URL:M_,isValidJWT:U_,locales:Pw,meta:bx,parse:dc,parseAsync:pc,prettifyError:cb,process:$e,regexes:$d,registry:zd,safeDecode:lP,safeDecodeAsync:cP,safeEncode:sP,safeEncodeAsync:uP,safeParse:db,safeParseAsync:pb,toDotPath:ub,toJSONSchema:nl,treeifyError:lb,util:ab,version:h_},Symbol.toStringTag,{value:"Module"})),KR=Object.freeze(Object.defineProperty({__proto__:null,endsWith:Gs,gt:Yn,gte:ft,includes:Js,length:$o,lowercase:Vs,lt:Kn,lte:Dt,maxLength:To,maxSize:Eo,mime:Ks,minLength:gr,minSize:ei,multipleOf:Xr,negative:op,nonnegative:sp,nonpositive:ap,normalize:Ys,overwrite:jn,positive:ip,property:lp,regex:qs,size:Zs,slugify:tl,startsWith:Ws,toLowerCase:Xs,toUpperCase:el,trim:Qs,uppercase:Hs},Symbol.toStringTag,{value:"Module"})),cp=R("ZodISODateTime",(e,t)=>{E_.init(e,t),Ae.init(e,t)});function aS(e){return Uw(cp,e)}const dp=R("ZodISODate",(e,t)=>{T_.init(e,t),Ae.init(e,t)});function sS(e){return Lw(dp,e)}const pp=R("ZodISOTime",(e,t)=>{$_.init(e,t),Ae.init(e,t)});function lS(e){return Fw(pp,e)}const fp=R("ZodISODuration",(e,t)=>{C_.init(e,t),Ae.init(e,t)});function uS(e){return Bw(fp,e)}const cS=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:dp,ZodISODateTime:cp,ZodISODuration:fp,ZodISOTime:pp,date:sS,datetime:aS,duration:uS,time:lS},Symbol.toStringTag,{value:"Module"})),dS=(e,t)=>{gd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>yd(e,n)},flatten:{value:n=>vd(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ga,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ga,2)}},isEmpty:{get(){return e.issues.length===0}}})},YR=R("ZodError",dS),Pt=R("ZodError",dS,{Parent:Error}),pS=yo(Pt),fS=bo(Pt),hS=_o(Pt),rl=wo(Pt),mS=bd(Pt),gS=_d(Pt),vS=wd(Pt),yS=xd(Pt),bS=Sd(Pt),_S=Id(Pt),wS=kd(Pt),xS=Ed(Pt),fe=R("ZodType",(e,t)=>(ce.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Zi(e,"input"),output:Zi(e,"output")}}),e.toJSONSchema=wx(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Nn(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]})),e.clone=(n,i)=>Bt(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>pS(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>hS(e,n,i),e.parseAsync=async(n,i)=>fS(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>rl(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>mS(e,n,i),e.decode=(n,i)=>gS(e,n,i),e.encodeAsync=async(n,i)=>vS(e,n,i),e.decodeAsync=async(n,i)=>yS(e,n,i),e.safeEncode=(n,i)=>bS(e,n,i),e.safeDecode=(n,i)=>_S(e,n,i),e.safeEncodeAsync=async(n,i)=>wS(e,n,i),e.safeDecodeAsync=async(n,i)=>xS(e,n,i),e.refine=(n,i)=>e.check(Kp(n,i)),e.superRefine=n=>e.check(Yp(n)),e.overwrite=n=>e.check(jn(n)),e.optional=()=>de(e),e.nullable=()=>Vi(e),e.nullish=()=>de(Vi(e)),e.nonoptional=n=>Up(e,n),e.array=()=>W(e),e.or=n=>ae([e,n]),e.and=n=>Ep(e,n),e.transform=n=>Hi(e,El(n)),e.default=n=>Mp(e,n),e.prefault=n=>Dp(e,n),e.catch=n=>Bp(e,n),e.pipe=n=>Hi(e,n),e.readonly=()=>Vp(e),e.describe=n=>{const i=e.clone();return Yt.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Yt.get(e);const i=e.clone();return Yt.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),il=R("_ZodString",(e,t)=>{ko.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(i,r,o)=>xx(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(qs(...i)),e.includes=(...i)=>e.check(Js(...i)),e.startsWith=(...i)=>e.check(Ws(...i)),e.endsWith=(...i)=>e.check(Gs(...i)),e.min=(...i)=>e.check(gr(...i)),e.max=(...i)=>e.check(To(...i)),e.length=(...i)=>e.check($o(...i)),e.nonempty=(...i)=>e.check(gr(1,...i)),e.lowercase=i=>e.check(Vs(i)),e.uppercase=i=>e.check(Hs(i)),e.trim=()=>e.check(Qs()),e.normalize=(...i)=>e.check(Ys(...i)),e.toLowerCase=()=>e.check(Xs()),e.toUpperCase=()=>e.check(el()),e.slugify=()=>e.check(tl())}),Ao=R("ZodString",(e,t)=>{ko.init(e,t),il.init(e,t),e.email=n=>e.check(Dd(ol,n)),e.url=n=>e.check(Bs(Po,n)),e.jwt=n=>e.check(rp(wl,n)),e.emoji=n=>e.check(Zd(al,n)),e.guid=n=>e.check(Qa(qi,n)),e.uuid=n=>e.check(Ud(hn,n)),e.uuidv4=n=>e.check(Ld(hn,n)),e.uuidv6=n=>e.check(Fd(hn,n)),e.uuidv7=n=>e.check(Bd(hn,n)),e.nanoid=n=>e.check(qd(sl,n)),e.guid=n=>e.check(Qa(qi,n)),e.cuid=n=>e.check(Vd(ll,n)),e.cuid2=n=>e.check(Hd(ul,n)),e.ulid=n=>e.check(Jd(cl,n)),e.base64=n=>e.check(ep(vl,n)),e.base64url=n=>e.check(tp(bl,n)),e.xid=n=>e.check(Wd(dl,n)),e.ksuid=n=>e.check(Gd(pl,n)),e.ipv4=n=>e.check(Kd(fl,n)),e.ipv6=n=>e.check(Yd(hl,n)),e.cidrv4=n=>e.check(Qd(ml,n)),e.cidrv6=n=>e.check(Xd(gl,n)),e.e164=n=>e.check(np(_l,n)),e.datetime=n=>e.check(aS(n)),e.date=n=>e.check(sS(n)),e.time=n=>e.check(lS(n)),e.duration=n=>e.check(uS(n))});function k(e){return jw(Ao,e)}const Ae=R("ZodStringFormat",(e,t)=>{Ce.init(e,t),il.init(e,t)}),ol=R("ZodEmail",(e,t)=>{v_.init(e,t),Ae.init(e,t)});function SS(e){return Dd(ol,e)}const qi=R("ZodGUID",(e,t)=>{m_.init(e,t),Ae.init(e,t)});function IS(e){return Qa(qi,e)}const hn=R("ZodUUID",(e,t)=>{g_.init(e,t),Ae.init(e,t)});function kS(e){return Ud(hn,e)}function ES(e){return Ld(hn,e)}function TS(e){return Fd(hn,e)}function $S(e){return Bd(hn,e)}const Po=R("ZodURL",(e,t)=>{y_.init(e,t),Ae.init(e,t)});function CS(e){return Bs(Po,e)}function AS(e){return Bs(Po,{protocol:/^https?$/,hostname:Pb,...M(e)})}const al=R("ZodEmoji",(e,t)=>{b_.init(e,t),Ae.init(e,t)});function PS(e){return Zd(al,e)}const sl=R("ZodNanoID",(e,t)=>{__.init(e,t),Ae.init(e,t)});function RS(e){return qd(sl,e)}const ll=R("ZodCUID",(e,t)=>{w_.init(e,t),Ae.init(e,t)});function OS(e){return Vd(ll,e)}const ul=R("ZodCUID2",(e,t)=>{x_.init(e,t),Ae.init(e,t)});function NS(e){return Hd(ul,e)}const cl=R("ZodULID",(e,t)=>{S_.init(e,t),Ae.init(e,t)});function jS(e){return Jd(cl,e)}const dl=R("ZodXID",(e,t)=>{I_.init(e,t),Ae.init(e,t)});function MS(e){return Wd(dl,e)}const pl=R("ZodKSUID",(e,t)=>{k_.init(e,t),Ae.init(e,t)});function zS(e){return Gd(pl,e)}const fl=R("ZodIPv4",(e,t)=>{A_.init(e,t),Ae.init(e,t)});function DS(e){return Kd(fl,e)}const hp=R("ZodMAC",(e,t)=>{R_.init(e,t),Ae.init(e,t)});function US(e){return zw(hp,e)}const hl=R("ZodIPv6",(e,t)=>{P_.init(e,t),Ae.init(e,t)});function LS(e){return Yd(hl,e)}const ml=R("ZodCIDRv4",(e,t)=>{O_.init(e,t),Ae.init(e,t)});function FS(e){return Qd(ml,e)}const gl=R("ZodCIDRv6",(e,t)=>{N_.init(e,t),Ae.init(e,t)});function BS(e){return Xd(gl,e)}const vl=R("ZodBase64",(e,t)=>{j_.init(e,t),Ae.init(e,t)});function yl(e){return ep(vl,e)}const bl=R("ZodBase64URL",(e,t)=>{z_.init(e,t),Ae.init(e,t)});function ZS(e){return tp(bl,e)}const _l=R("ZodE164",(e,t)=>{D_.init(e,t),Ae.init(e,t)});function qS(e){return np(_l,e)}const wl=R("ZodJWT",(e,t)=>{L_.init(e,t),Ae.init(e,t)});function VS(e){return rp(wl,e)}const di=R("ZodCustomStringFormat",(e,t)=>{F_.init(e,t),Ae.init(e,t)});function HS(e,t,n={}){return Co(di,e,t,n)}function JS(e){return Co(di,"hostname",Ab,e)}function WS(e){return Co(di,"hex",Jb,e)}function GS(e,t){const n=t?.enc??"hex",i=`${e}_${n}`,r=$d[i];if(!r)throw new Error(`Unrecognized hash format: ${i}`);return Co(di,i,r,t)}const Ro=R("ZodNumber",(e,t)=>{Rd.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Sx(e,i,r),e.gt=(i,r)=>e.check(Yn(i,r)),e.gte=(i,r)=>e.check(ft(i,r)),e.min=(i,r)=>e.check(ft(i,r)),e.lt=(i,r)=>e.check(Kn(i,r)),e.lte=(i,r)=>e.check(Dt(i,r)),e.max=(i,r)=>e.check(Dt(i,r)),e.int=i=>e.check(Xa(i)),e.safe=i=>e.check(Xa(i)),e.positive=i=>e.check(Yn(0,i)),e.nonnegative=i=>e.check(ft(0,i)),e.negative=i=>e.check(Kn(0,i)),e.nonpositive=i=>e.check(Dt(0,i)),e.multipleOf=(i,r)=>e.check(Xr(i,r)),e.step=(i,r)=>e.check(Xr(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 Zw(Ro,e)}const Ir=R("ZodNumberFormat",(e,t)=>{B_.init(e,t),Ro.init(e,t)});function Xa(e){return Vw(Ir,e)}function KS(e){return Hw(Ir,e)}function YS(e){return Jw(Ir,e)}function QS(e){return Ww(Ir,e)}function XS(e){return Gw(Ir,e)}const Oo=R("ZodBoolean",(e,t)=>{Od.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ix(e,n,i)});function Ee(e){return Kw(Oo,e)}const No=R("ZodBigInt",(e,t)=>{Nd.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(i,r,o)=>kx(e,i),e.gte=(i,r)=>e.check(ft(i,r)),e.min=(i,r)=>e.check(ft(i,r)),e.gt=(i,r)=>e.check(Yn(i,r)),e.gte=(i,r)=>e.check(ft(i,r)),e.min=(i,r)=>e.check(ft(i,r)),e.lt=(i,r)=>e.check(Kn(i,r)),e.lte=(i,r)=>e.check(Dt(i,r)),e.max=(i,r)=>e.check(Dt(i,r)),e.positive=i=>e.check(Yn(BigInt(0),i)),e.negative=i=>e.check(Kn(BigInt(0),i)),e.nonpositive=i=>e.check(Dt(BigInt(0),i)),e.nonnegative=i=>e.check(ft(BigInt(0),i)),e.multipleOf=(i,r)=>e.check(Xr(i,r));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function eI(e){return Qw(No,e)}const xl=R("ZodBigIntFormat",(e,t)=>{Z_.init(e,t),No.init(e,t)});function tI(e){return ex(xl,e)}function nI(e){return tx(xl,e)}const mp=R("ZodSymbol",(e,t)=>{q_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ex(e,n)});function rI(e){return nx(mp,e)}const gp=R("ZodUndefined",(e,t)=>{V_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>$x(e,n)});function iI(e){return rx(gp,e)}const vp=R("ZodNull",(e,t)=>{H_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Tx(e,n,i)});function jo(e){return ix(vp,e)}const yp=R("ZodAny",(e,t)=>{J_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Px()});function Je(){return ox(yp)}const bp=R("ZodUnknown",(e,t)=>{W_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Rx()});function ze(){return ax(bp)}const _p=R("ZodNever",(e,t)=>{G_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ax(e,n,i)});function Sl(e){return sx(_p,e)}const wp=R("ZodVoid",(e,t)=>{K_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Cx(e,n)});function oI(e){return lx(wp,e)}const Il=R("ZodDate",(e,t)=>{Y_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Ox(e,i),e.min=(i,r)=>e.check(ft(i,r)),e.max=(i,r)=>e.check(Dt(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 aI(e){return ux(Il,e)}const xp=R("ZodArray",(e,t)=>{Q_.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Vx(e,n,i,r),e.element=t.element,e.min=(n,i)=>e.check(gr(n,i)),e.nonempty=n=>e.check(gr(1,n)),e.max=(n,i)=>e.check(To(n,i)),e.length=(n,i)=>e.check($o(n,i)),e.unwrap=()=>e.element});function W(e,t){return px(xp,e,t)}function sI(e){const t=e._zod.def.shape;return nr(Object.keys(t))}const Mo=R("ZodObject",(e,t)=>{nw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Hx(e,n,i,r),ge(e,"shape",()=>t.shape),e.keyof=()=>nr(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ze()}),e.loose=()=>e.clone({...e._zod.def,catchall:ze()}),e.strict=()=>e.clone({...e._zod.def,catchall:Sl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Xy(e,n),e.safeExtend=n=>eb(e,n),e.merge=n=>tb(e,n),e.pick=n=>Yy(e,n),e.omit=n=>Qy(e,n),e.partial=(...n)=>nb(Tl,e,n[0]),e.required=(...n)=>rb($l,e,n[0])});function O(e,t){const n={type:"object",shape:e??{},...M(t)};return new Mo(n)}function je(e,t){return new Mo({type:"object",shape:e,catchall:Sl(),...M(t)})}function Vn(e,t){return new Mo({type:"object",shape:e,catchall:ze(),...M(t)})}const zo=R("ZodUnion",(e,t)=>{Fs.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>up(e,n,i,r),e.options=t.options});function ae(e,t){return new zo({type:"union",options:e,...M(t)})}const Sp=R("ZodXor",(e,t)=>{zo.init(e,t),rw.init(e,t),e._zod.processJSONSchema=(n,i,r)=>up(e,n,i,r),e.options=t.options});function lI(e,t){return new Sp({type:"union",options:e,inclusive:!1,...M(t)})}const Ip=R("ZodDiscriminatedUnion",(e,t)=>{zo.init(e,t),iw.init(e,t)});function kl(e,t,n){return new Ip({type:"union",options:t,discriminator:e,...M(n)})}const kp=R("ZodIntersection",(e,t)=>{ow.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Jx(e,n,i,r)});function Ep(e,t){return new kp({type:"intersection",left:e,right:t})}const Tp=R("ZodTuple",(e,t)=>{jd.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Wx(e,n,i,r),e.rest=n=>e.clone({...e._zod.def,rest:n})});function $p(e,t,n){const i=t instanceof ce,r=i?n:t,o=i?t:null;return new Tp({type:"tuple",items:e,rest:o,...M(r)})}const Do=R("ZodRecord",(e,t)=>{aw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Gx(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function kt(e,t,n){return new Do({type:"record",keyType:e,valueType:t,...M(n)})}function uI(e,t,n){const i=Bt(e);return i._zod.values=void 0,new Do({type:"record",keyType:i,valueType:t,...M(n)})}function cI(e,t,n){return new Do({type:"record",keyType:e,valueType:t,mode:"loose",...M(n)})}const Cp=R("ZodMap",(e,t)=>{sw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Zx(e,n),e.keyType=t.keyType,e.valueType=t.valueType});function dI(e,t,n){return new Cp({type:"map",keyType:e,valueType:t,...M(n)})}const Ap=R("ZodSet",(e,t)=>{lw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>qx(e,n),e.min=(...n)=>e.check(ei(...n)),e.nonempty=n=>e.check(ei(1,n)),e.max=(...n)=>e.check(Eo(...n)),e.size=(...n)=>e.check(Zs(...n))});function pI(e,t){return new Ap({type:"set",valueType:e,...M(t)})}const ii=R("ZodEnum",(e,t)=>{uw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Nx(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 a of i)if(n.has(a))o[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new ii({...t,checks:[],...M(r),entries:o})},e.exclude=(i,r)=>{const o={...t.entries};for(const a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new ii({...t,checks:[],...M(r),entries:o})}});function nr(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new ii({type:"enum",entries:n,...M(t)})}function fI(e,t){return new ii({type:"enum",entries:e,...M(t)})}const Pp=R("ZodLiteral",(e,t)=>{cw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>jx(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 L(e,t){return new Pp({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}const Rp=R("ZodFile",(e,t)=>{dw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Dx(e,n,i),e.min=(n,i)=>e.check(ei(n,i)),e.max=(n,i)=>e.check(Eo(n,i)),e.mime=(n,i)=>e.check(Ks(Array.isArray(n)?n:[n],i))});function hI(e){return fx(Rp,e)}const Op=R("ZodTransform",(e,t)=>{pw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Bx(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ms(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(Yr(o,n.value,t));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),n.issues.push(Yr(a))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function El(e){return new Op({type:"transform",transform:e})}const Tl=R("ZodOptional",(e,t)=>{fw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>iS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function de(e){return new Tl({type:"optional",innerType:e})}const Np=R("ZodNullable",(e,t)=>{hw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Kx(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Vi(e){return new Np({type:"nullable",innerType:e})}function mI(e){return de(Vi(e))}const jp=R("ZodDefault",(e,t)=>{mw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Qx(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mp(e,t){return new jp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ds(t)}})}const zp=R("ZodPrefault",(e,t)=>{gw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Xx(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Dp(e,t){return new zp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ds(t)}})}const $l=R("ZodNonOptional",(e,t)=>{vw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Yx(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Up(e,t){return new $l({type:"nonoptional",innerType:e,...M(t)})}const Lp=R("ZodSuccess",(e,t)=>{yw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ux(e,n,i),e.unwrap=()=>e._zod.def.innerType});function gI(e){return new Lp({type:"success",innerType:e})}const Fp=R("ZodCatch",(e,t)=>{bw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>eS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Bp(e,t){return new Fp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Zp=R("ZodNaN",(e,t)=>{_w.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mx(e,n)});function vI(e){return dx(Zp,e)}const Cl=R("ZodPipe",(e,t)=>{ww.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>tS(e,n,i,r),e.in=t.in,e.out=t.out});function Hi(e,t){return new Cl({type:"pipe",in:e,out:t})}const Al=R("ZodCodec",(e,t)=>{Cl.init(e,t),Md.init(e,t)});function yI(e,t,n){return new Al({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const qp=R("ZodReadonly",(e,t)=>{xw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>nS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Vp(e){return new qp({type:"readonly",innerType:e})}const Hp=R("ZodTemplateLiteral",(e,t)=>{Sw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zx(e,n,i)});function bI(e,t){return new Hp({type:"template_literal",parts:e,...M(t)})}const Jp=R("ZodLazy",(e,t)=>{Ew.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>oS(e,n,i,r),e.unwrap=()=>e._zod.def.getter()});function Uo(e){return new Jp({type:"lazy",getter:e})}const Wp=R("ZodPromise",(e,t)=>{kw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>rS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function _I(e){return new Wp({type:"promise",innerType:e})}const Gp=R("ZodFunction",(e,t)=>{Iw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Fx(e,n)});function es(e){return new Gp({type:"function",input:Array.isArray(e?.input)?$p(e?.input):e?.input??W(ze()),output:e?.output??ze()})}const Lo=R("ZodCustom",(e,t)=>{Tw.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Lx(e,n)});function wI(e){const t=new De({check:"custom"});return t._zod.check=e,t}function Fo(e,t){return hx(Lo,e??(()=>!0),t)}function Kp(e,t={}){return mx(Lo,e,t)}function Yp(e){return gx(e)}const xI=yx,SI=bx;function vn(e,t={error:`Input not instance of ${e.name}`}){const n=new Lo({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...M(t)});return n._zod.bag.Class=e,n}const II=(...e)=>_x({Codec:Al,Boolean:Oo,String:Ao},...e);function kI(e){const t=Uo(()=>ae([k(e),ee(),Ee(),jo(),W(t),kt(k(),t)]));return t}function EI(e,t){return Hi(El(e),t)}const QR=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:yp,ZodArray:xp,ZodBase64:vl,ZodBase64URL:bl,ZodBigInt:No,ZodBigIntFormat:xl,ZodBoolean:Oo,ZodCIDRv4:ml,ZodCIDRv6:gl,ZodCUID:ll,ZodCUID2:ul,ZodCatch:Fp,ZodCodec:Al,ZodCustom:Lo,ZodCustomStringFormat:di,ZodDate:Il,ZodDefault:jp,ZodDiscriminatedUnion:Ip,ZodE164:_l,ZodEmail:ol,ZodEmoji:al,ZodEnum:ii,ZodFile:Rp,ZodFunction:Gp,ZodGUID:qi,ZodIPv4:fl,ZodIPv6:hl,ZodIntersection:kp,ZodJWT:wl,ZodKSUID:pl,ZodLazy:Jp,ZodLiteral:Pp,ZodMAC:hp,ZodMap:Cp,ZodNaN:Zp,ZodNanoID:sl,ZodNever:_p,ZodNonOptional:$l,ZodNull:vp,ZodNullable:Np,ZodNumber:Ro,ZodNumberFormat:Ir,ZodObject:Mo,ZodOptional:Tl,ZodPipe:Cl,ZodPrefault:zp,ZodPromise:Wp,ZodReadonly:qp,ZodRecord:Do,ZodSet:Ap,ZodString:Ao,ZodStringFormat:Ae,ZodSuccess:Lp,ZodSymbol:mp,ZodTemplateLiteral:Hp,ZodTransform:Op,ZodTuple:Tp,ZodType:fe,ZodULID:cl,ZodURL:Po,ZodUUID:hn,ZodUndefined:gp,ZodUnion:zo,ZodUnknown:bp,ZodVoid:wp,ZodXID:dl,ZodXor:Sp,_ZodString:il,_default:Mp,_function:es,any:Je,array:W,base64:yl,base64url:ZS,bigint:eI,boolean:Ee,catch:Bp,check:wI,cidrv4:FS,cidrv6:BS,codec:yI,cuid:OS,cuid2:NS,custom:Fo,date:aI,describe:xI,discriminatedUnion:kl,e164:qS,email:SS,emoji:PS,enum:nr,file:hI,float32:KS,float64:YS,function:es,guid:IS,hash:GS,hex:WS,hostname:JS,httpUrl:AS,instanceof:vn,int:Xa,int32:QS,int64:tI,intersection:Ep,ipv4:DS,ipv6:LS,json:kI,jwt:VS,keyof:sI,ksuid:zS,lazy:Uo,literal:L,looseObject:Vn,looseRecord:cI,mac:US,map:dI,meta:SI,nan:vI,nanoid:RS,nativeEnum:fI,never:Sl,nonoptional:Up,null:jo,nullable:Vi,nullish:mI,number:ee,object:O,optional:de,partialRecord:uI,pipe:Hi,prefault:Dp,preprocess:EI,promise:_I,readonly:Vp,record:kt,refine:Kp,set:pI,strictObject:je,string:k,stringFormat:HS,stringbool:II,success:gI,superRefine:Yp,symbol:rI,templateLiteral:bI,transform:El,tuple:$p,uint32:XS,uint64:nI,ulid:jS,undefined:iI,union:ae,unknown:ze,url:CS,uuid:kS,uuidv4:ES,uuidv6:TS,uuidv7:$S,void:oI,xid:MS,xor:lI},Symbol.toStringTag,{value:"Module"})),TI={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 XR(e){tt({customError:e})}function eO(){return tt().customError}var mc;mc||(mc={});const K={...QR,...KR,iso:cS};function tO(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 nO(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 $I(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=nO(r,t),a=et(o,t);return t.refs.set(r,a),t.processing.delete(r),a}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(a=>typeof a=="string"))return K.enum(r);const o=r.map(a=>K.literal(a));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 a={...e,type:o};return $I(a,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||{},a=new Set(e.required||[]);for(const[u,l]of Object.entries(o)){const c=et(l,t);r[u]=a.has(u)?c:c.optional()}if(e.propertyNames){const u=et(e.propertyNames,t),l=e.additionalProperties&&typeof e.additionalProperties=="object"?et(e.additionalProperties,t):K.any();if(Object.keys(r).length===0){i=K.record(u,l);break}const c=K.object(r).passthrough(),d=K.looseRecord(u,l);i=K.intersection(c,d);break}if(e.patternProperties){const u=e.patternProperties,l=Object.keys(u),c=[];for(const f of l){const p=et(u[f],t),g=K.string().regex(new RegExp(f));c.push(K.looseRecord(g,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 s=K.object(r);e.additionalProperties===!1?i=s.strict():typeof e.additionalProperties=="object"?i=s.catchall(et(e.additionalProperties,t)):i=s.passthrough();break}case"array":{const r=e.prefixItems,o=e.items;if(r&&Array.isArray(r)){const a=r.map(u=>et(u,t)),s=o&&typeof o=="object"&&!Array.isArray(o)?et(o,t):void 0;s?i=K.tuple(a).rest(s):i=K.tuple(a),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 a=o.map(u=>et(u,t)),s=e.additionalItems&&typeof e.additionalItems=="object"?et(e.additionalItems,t):void 0;s?i=K.tuple(a).rest(s):i=K.tuple(a),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 a=et(o,t);let s=K.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),i=s}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 et(e,t){if(typeof e=="boolean")return e?K.any():K.never();let n=$I(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(a=>et(a,t)),o=K.union(r);n=i?K.intersection(n,o):o}if(e.oneOf&&Array.isArray(e.oneOf)){const r=e.oneOf.map(a=>et(a,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:et(e.allOf[0],t);const o=i?0:1;for(let a=o;a<e.allOf.length;a++)r=K.intersection(r,et(e.allOf[a],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 rO(e,t){if(typeof e=="boolean")return e?K.any():K.never();const n=tO(e,t?.defaultTarget),i=e.$defs||e.definitions||{};return et(e,{version:n,defs:i,refs:new Map,processing:new Set,rootSchema:e})}function iO(e){return Mw(Ao,e)}function oO(e){return qw(Ro,e)}function aO(e){return Yw(Oo,e)}function sO(e){return Xw(No,e)}function lO(e){return cx(Il,e)}const uO=Object.freeze(Object.defineProperty({__proto__:null,bigint:sO,boolean:aO,date:lO,number:oO,string:iO},Symbol.toStringTag,{value:"Module"}));tt($w());const ts=Object.freeze(Object.defineProperty({__proto__:null,$brand:Zy,$input:Ow,$output:Rw,NEVER:fd,TimePrecision:Dw,ZodAny:yp,ZodArray:xp,ZodBase64:vl,ZodBase64URL:bl,ZodBigInt:No,ZodBigIntFormat:xl,ZodBoolean:Oo,ZodCIDRv4:ml,ZodCIDRv6:gl,ZodCUID:ll,ZodCUID2:ul,ZodCatch:Fp,ZodCodec:Al,ZodCustom:Lo,ZodCustomStringFormat:di,ZodDate:Il,ZodDefault:jp,ZodDiscriminatedUnion:Ip,ZodE164:_l,ZodEmail:ol,ZodEmoji:al,ZodEnum:ii,ZodError:YR,ZodFile:Rp,get ZodFirstPartyTypeKind(){return mc},ZodFunction:Gp,ZodGUID:qi,ZodIPv4:fl,ZodIPv6:hl,ZodISODate:dp,ZodISODateTime:cp,ZodISODuration:fp,ZodISOTime:pp,ZodIntersection:kp,ZodIssueCode:TI,ZodJWT:wl,ZodKSUID:pl,ZodLazy:Jp,ZodLiteral:Pp,ZodMAC:hp,ZodMap:Cp,ZodNaN:Zp,ZodNanoID:sl,ZodNever:_p,ZodNonOptional:$l,ZodNull:vp,ZodNullable:Np,ZodNumber:Ro,ZodNumberFormat:Ir,ZodObject:Mo,ZodOptional:Tl,ZodPipe:Cl,ZodPrefault:zp,ZodPromise:Wp,ZodReadonly:qp,ZodRealError:Pt,ZodRecord:Do,ZodSet:Ap,ZodString:Ao,ZodStringFormat:Ae,ZodSuccess:Lp,ZodSymbol:mp,ZodTemplateLiteral:Hp,ZodTransform:Op,ZodTuple:Tp,ZodType:fe,ZodULID:cl,ZodURL:Po,ZodUUID:hn,ZodUndefined:gp,ZodUnion:zo,ZodUnknown:bp,ZodVoid:wp,ZodXID:dl,ZodXor:Sp,_ZodString:il,_default:Mp,_function:es,any:Je,array:W,base64:yl,base64url:ZS,bigint:eI,boolean:Ee,catch:Bp,check:wI,cidrv4:FS,cidrv6:BS,clone:Bt,codec:yI,coerce:uO,config:tt,core:GR,cuid:OS,cuid2:NS,custom:Fo,date:aI,decode:gS,decodeAsync:yS,describe:xI,discriminatedUnion:kl,e164:qS,email:SS,emoji:PS,encode:mS,encodeAsync:vS,endsWith:Gs,enum:nr,file:hI,flattenError:vd,float32:KS,float64:YS,formatError:yd,fromJSONSchema:rO,function:es,getErrorMap:eO,globalRegistry:Yt,gt:Yn,gte:ft,guid:IS,hash:GS,hex:WS,hostname:JS,httpUrl:AS,includes:Js,instanceof:vn,int:Xa,int32:QS,int64:tI,intersection:Ep,ipv4:DS,ipv6:LS,iso:cS,json:kI,jwt:VS,keyof:sI,ksuid:zS,lazy:Uo,length:$o,literal:L,locales:Pw,looseObject:Vn,looseRecord:cI,lowercase:Vs,lt:Kn,lte:Dt,mac:US,map:dI,maxLength:To,maxSize:Eo,meta:SI,mime:Ks,minLength:gr,minSize:ei,multipleOf:Xr,nan:vI,nanoid:RS,nativeEnum:fI,negative:op,never:Sl,nonnegative:sp,nonoptional:Up,nonpositive:ap,normalize:Ys,null:jo,nullable:Vi,nullish:mI,number:ee,object:O,optional:de,overwrite:jn,parse:pS,parseAsync:fS,partialRecord:uI,pipe:Hi,positive:ip,prefault:Dp,preprocess:EI,prettifyError:cb,promise:_I,property:lp,readonly:Vp,record:kt,refine:Kp,regex:qs,regexes:$d,registry:zd,safeDecode:_S,safeDecodeAsync:xS,safeEncode:bS,safeEncodeAsync:wS,safeParse:hS,safeParseAsync:rl,set:pI,setErrorMap:XR,size:Zs,slugify:tl,startsWith:Ws,strictObject:je,string:k,stringFormat:HS,stringbool:II,success:gI,superRefine:Yp,symbol:rI,templateLiteral:bI,toJSONSchema:nl,toLowerCase:Xs,toUpperCase:el,transform:El,treeifyError:lb,trim:Qs,tuple:$p,uint32:XS,uint64:nI,ulid:jS,undefined:iI,union:ae,unknown:ze,uppercase:Hs,url:CS,util:ab,uuid:kS,uuidv4:ES,uuidv6:TS,uuidv7:$S,void:oI,xid:MS,xor:lI},Symbol.toStringTag,{value:"Module"}));var Ji;(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 a of r)o[a]=a;return o},e.getValidEnumValues=r=>{const o=e.objectKeys(r).filter(s=>typeof r[r[s]]!="number"),a={};for(const s of o)a[s]=r[s];return e.objectValues(a)},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 a in r)Object.prototype.hasOwnProperty.call(r,a)&&o.push(a);return o},e.find=(r,o)=>{for(const a of r)if(o(a))return a},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(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=i,e.jsonStringifyReplacer=(r,o)=>typeof o=="bigint"?o.toString():o})(Ji||(Ji={}));var Qh;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Qh||(Qh={}));Ji.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);Ji.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 ns 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 a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)i._errors.push(n(a));else{let s=i,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(n(a))):s[l]=s[l]||{_errors:[]},s=s[l],u++}}};return r(this),i}static assert(t){if(!(t instanceof ns))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ji.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()}}ns.create=e=>new ns(e);var Xh;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Xh||(Xh={}));var J;(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"})(J||(J={}));var cO=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new js({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`};cO();function CI(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 dO(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 AI(e,...t){const n=new Headers(dO(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var pO=Symbol.for("vercel.ai.validator");function fO(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var hO=Symbol.for("vercel.ai.schema");function mO(e,{validate:t}={}){return{[hO]:!0,_type:void 0,[pO]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let Qp;Qp=globalThis.crypto;async function gO(e){return(await Qp).getRandomValues(new Uint8Array(e))}async function vO(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const i=await gO(e);for(let r=0;r<e;r++){const o=i[r]%t.length;n+=t[o]}return n}async function yO(e){return await vO(e)}async function bO(e){const t=await(await Qp).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function _O(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await yO(e),n=await bO(t);return{code_verifier:t,code_challenge:n}}var wO="AI_MCPClientError",PI=`vercel.ai.error.${wO}`,xO=Symbol.for(PI),em,tm,xe=class extends(tm=ue,em=xO,tm){constructor({name:e="MCPClientError",message:t,cause:n,data:i,code:r}){super({name:e,message:t,cause:n}),this[em]=!0,this.data=i,this.code=r}static isInstance(e){return ue.hasMarker(e,PI)}},pi="2025-06-18",SO=[pi,"2025-03-26","2024-11-05"],IO=Vn({name:k(),version:k()}),Pl=Vn({_meta:de(O({}).loose())}),Pn=Pl,RI=O({method:k(),params:de(Pl)}),OI=O({applyDefaults:de(Ee())}).loose(),kO=Vn({experimental:de(O({}).loose()),logging:de(O({}).loose()),prompts:de(Vn({listChanged:de(Ee())})),resources:de(Vn({subscribe:de(Ee()),listChanged:de(Ee())})),tools:de(Vn({listChanged:de(Ee())})),elicitation:de(OI)});O({elicitation:de(OI)}).loose();var EO=Pn.extend({protocolVersion:k(),capabilities:kO,serverInfo:IO,instructions:de(k())}),Xp=Pn.extend({nextCursor:de(k())}),TO=O({name:k(),description:de(k()),inputSchema:O({type:L("object"),properties:de(O({}).loose())}).loose()}).loose(),$O=Xp.extend({tools:W(TO)}),NI=O({type:L("text"),text:k()}).loose(),jI=O({type:L("image"),data:yl(),mimeType:k()}).loose(),CO=O({uri:k(),name:k(),title:de(k()),description:de(k()),mimeType:de(k()),size:de(ee())}).loose(),AO=Xp.extend({resources:W(CO)}),MI=O({uri:k(),name:de(k()),title:de(k()),mimeType:de(k())}).loose(),zI=MI.extend({text:k()}),DI=MI.extend({blob:yl()}),UI=O({type:L("resource"),resource:ae([zI,DI])}).loose(),PO=Pn.extend({content:W(ae([NI,jI,UI])),isError:Ee().default(!1).optional()}).or(Pn.extend({toolResult:ze()})),RO=O({uriTemplate:k(),name:k(),title:de(k()),description:de(k()),mimeType:de(k())}).loose(),OO=Pn.extend({resourceTemplates:W(RO)}),NO=Pn.extend({contents:W(ae([zI,DI]))}),jO=O({name:k(),description:de(k()),required:de(Ee())}).loose(),MO=O({name:k(),title:de(k()),description:de(k()),arguments:de(W(jO))}).loose(),zO=Xp.extend({prompts:W(MO)}),DO=O({role:ae([L("user"),L("assistant")]),content:ae([NI,jI,UI])}).loose(),UO=Pn.extend({description:de(k()),messages:W(DO)}),LO=Pl.extend({message:k(),requestedSchema:ze()}),nm=RI.extend({method:L("elicitation/create"),params:LO}),FO=Pn.extend({action:ae([L("accept"),L("decline"),L("cancel")]),content:de(kt(k(),ze()))}),Rl="2.0",BO=O({jsonrpc:L(Rl),id:ae([k(),ee().int()])}).merge(RI).strict(),ZO=O({jsonrpc:L(Rl),id:ae([k(),ee().int()]),result:Pn}).strict(),qO=O({jsonrpc:L(Rl),id:ae([k(),ee().int()]),error:O({code:ee().int(),message:k(),data:de(ze())})}).strict(),VO=O({jsonrpc:L(Rl)}).merge(O({method:k(),params:de(Pl)})).strict(),Pi=ae([BO,VO,ZO,qO]),LI=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",FI=O({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:ee().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),ht=k().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:TI.custom,message:"URL must be parseable",fatal:!0}),fd}).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"}),HO=O({resource:k().url(),authorization_servers:W(ht).optional(),jwks_uri:k().url().optional(),scopes_supported:W(k()).optional(),bearer_methods_supported:W(k()).optional(),resource_signing_alg_values_supported:W(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:Ee().optional(),authorization_details_types_supported:W(k()).optional(),dpop_signing_alg_values_supported:W(k()).optional(),dpop_bound_access_tokens_required:Ee().optional()}).passthrough(),BI=O({issuer:k(),authorization_endpoint:ht,token_endpoint:ht,registration_endpoint:ht.optional(),scopes_supported:W(k()).optional(),response_types_supported:W(k()),grant_types_supported:W(k()).optional(),code_challenge_methods_supported:W(k()),token_endpoint_auth_methods_supported:W(k()).optional(),token_endpoint_auth_signing_alg_values_supported:W(k()).optional()}).passthrough(),JO=O({issuer:k(),authorization_endpoint:ht,token_endpoint:ht,userinfo_endpoint:ht.optional(),jwks_uri:ht,registration_endpoint:ht.optional(),scopes_supported:W(k()).optional(),response_types_supported:W(k()),grant_types_supported:W(k()).optional(),subject_types_supported:W(k()),id_token_signing_alg_values_supported:W(k()),claims_supported:W(k()).optional(),token_endpoint_auth_methods_supported:W(k()).optional()}).passthrough(),WO=JO.merge(BI.pick({code_challenge_methods_supported:!0})),GO=O({client_id:k(),client_secret:k().optional(),client_id_issued_at:ee().optional(),client_secret_expires_at:ee().optional()}).strip(),KO=O({redirect_uris:W(ht),token_endpoint_auth_method:k().optional(),grant_types:W(k()).optional(),response_types:W(k()).optional(),client_name:k().optional(),client_uri:ht.optional(),logo_uri:ht.optional(),scope:k().optional(),contacts:W(k()).optional(),tos_uri:ht.optional(),policy_uri:k().optional(),jwks_uri:ht.optional(),jwks:Je().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),YO=O({error:k(),error_description:k().optional(),error_uri:k().optional()}),QO=KO.merge(GO),XO="AI_MCPClientOAuthError",ZI=`vercel.ai.error.${XO}`,eN=Symbol.for(ZI),rm,im,Bo=class extends(im=ue,rm=eN,im){constructor({name:e="MCPClientOAuthError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[rm]=!0}static isInstance(e){return ue.hasMarker(e,ZI)}},oi=class extends Bo{};oi.errorCode="server_error";var rs=class extends Bo{};rs.errorCode="invalid_client";var is=class extends Bo{};is.errorCode="invalid_grant";var os=class extends Bo{};os.errorCode="unauthorized_client";var tN={[oi.errorCode]:oi,[rs.errorCode]:rs,[is.errorCode]:is,[os.errorCode]:os};function nN(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function rN({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 as=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function ss(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="([^"]*)"/,a=n.match(o);if(a)try{return new URL(a[1])}catch{return}}function iN(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ef(e,t,n=fetch){try{return await n(e,{headers:t})}catch(i){if(i instanceof TypeError)return t?ef(e,void 0,n):void 0;throw i}}async function om(e,t,n=fetch){return await ef(e,{"MCP-Protocol-Version":t},n)}function oN(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function aN(e,t,n,i){var r,o;const a=new URL(e),s=(r=i?.protocolVersion)!=null?r:pi;let u;if(i?.metadataUrl)u=new URL(i.metadataUrl);else{const c=iN(t,a.pathname);u=new URL(c,(o=i?.metadataServerUrl)!=null?o:a),u.search=a.search}let l=await om(u,s,n);if(!i?.metadataUrl&&oN(l,a.pathname)){const c=new URL(`/.well-known/${t}`,a);l=await om(c,s,n)}return l}async function sN(e,t,n=fetch){const i=await aN(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 HO.parse(await i.json())}function lN(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 uN(e,{fetchFn:t=fetch,protocolVersion:n=pi}={}){var i;const r={"MCP-Protocol-Version":n},o=lN(e);for(const{url:a,type:s}of o){const u=await ef(a,r,t);if(u){if(!u.ok){if(u.status>=400&&u.status<500)continue;throw new Error(`HTTP ${u.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return BI.parse(await u.json());{const l=WO.parse(await u.json());if(!((i=l.code_challenge_methods_supported)!=null&&i.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return l}}}}async function cN(e,{metadata:t,clientInformation:n,redirectUrl:i,scope:r,state:o,resource:a}){const s="code",u="S256";let l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(u))throw new Error(`Incompatible auth server: does not support code challenge method ${u}`)}else l=new URL("/authorize",e);const c=await _O(),d=c.code_verifier,f=c.code_challenge;return l.searchParams.set("response_type",s),l.searchParams.set("client_id",n.client_id),l.searchParams.set("code_challenge",f),l.searchParams.set("code_challenge_method",u),l.searchParams.set("redirect_uri",String(i)),o&&l.searchParams.set("state",o),r&&l.searchParams.set("scope",r),r?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:d}}function qI(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 VI(e,t,n,i){const{client_id:r,client_secret:o}=t;switch(e){case"client_secret_basic":dN(r,o,n);return;case"client_secret_post":pN(r,o,i);return;case"none":fN(r,i);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function dN(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 pN(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function fN(e,t){t.set("client_id",e)}async function tf(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const i=YO.parse(JSON.parse(n)),{error:r,error_description:o,error_uri:a}=i,s=tN[r]||oi;return new s({message:o||"",cause:a})}catch(i){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${i}. Raw body: ${n}`;return new oi({message:r})}}async function hN(e,{metadata:t,clientInformation:n,authorizationCode:i,codeVerifier:r,redirectUri:o,resource:a,addClientAuthentication:s,fetchFn:u}){var l;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(s)s(f,p,e,t);else{const m=(l=t?.token_endpoint_auth_methods_supported)!=null?l:[],y=qI(n,m);VI(y,n,f,p)}a&&p.set("resource",a.href);const g=await(u??fetch)(d,{method:"POST",headers:f,body:p});if(!g.ok)throw await tf(g);return FI.parse(await g.json())}async function mN(e,{metadata:t,clientInformation:n,refreshToken:i,resource:r,addClientAuthentication:o,fetchFn:a}){var s;const u="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`)}else l=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:u,refresh_token:i});if(o)o(c,d,e,t);else{const p=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],g=qI(n,p);VI(g,n,c,d)}r&&d.set("resource",r.href);const f=await(a??fetch)(l,{method:"POST",headers:c,body:d});if(!f.ok)throw await tf(f);return FI.parse({refresh_token:i,...await f.json()})}async function gN(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 tf(o);return QO.parse(await o.json())}async function ls(e,t){var n,i;try{return await du(e,t)}catch(r){if(r instanceof rs||r instanceof os)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await du(e,t);if(r instanceof is)return await((i=e.invalidateCredentials)==null?void 0:i.call(e,"tokens")),await du(e,t);throw r}}async function vN(e,t,n){const i=nN(e);if(t.validateResourceURL)return await t.validateResourceURL(i,n?.resource);if(n){if(!rN({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 du(e,{serverUrl:t,authorizationCode:n,scope:i,resourceMetadataUrl:r,fetchFn:o}){let a,s;try{a=await sN(t,{resourceMetadataUrl:r},o),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=t);const u=await vN(t,e,a),l=await uN(s,{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 m=await gN(s,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(m),c=m}if(n!==void 0){const m=await e.codeVerifier(),y=await hN(s,{metadata:l,clientInformation:c,authorizationCode:n,codeVerifier:m,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(y),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const m=await mN(s,{metadata:l,clientInformation:c,refreshToken:d.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(m),"AUTHORIZED"}catch(m){if(!(!(m instanceof Bo)||m instanceof oi))throw m}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:g}=await cN(s,{metadata:l,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(p),"REDIRECT"}var yN=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":pi};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return AI(t,`ai-sdk/${LI}`,CI())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(i=!1)=>{var r,o,a,s,u;try{const l=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:l,signal:(r=this.abortController)==null?void 0:r.signal});if(c.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=ss(c);try{if(await ls(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const m=new as;return(o=this.onerror)==null||o.call(this,m),t(m)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return n(!0)}if(!c.ok||!c.body){let g=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const m=new xe({message:g});return(s=this.onerror)==null||s.call(this,m),t(m)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).getReader(),p=async()=>{var g,m,y;try{for(;;){const{done:v,value:x}=await f.read();if(v){if(this.connected)throw this.connected=!1,new xe({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:S,data:b}=x;if(S==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new xe({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 A=Pi.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,A)}catch(A){const E=new xe({message:"MCP SSE Transport Error: Failed to parse message",cause:A});(m=this.onerror)==null||m.call(this,E)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(y=this.onerror)==null||y.call(this,v),t(v)}};this.sseConnection={close:()=>f.cancel()},p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(u=this.onerror)==null||u.call(this,l),t(l)}};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 xe({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,n=async(i=!1)=>{var r,o,a,s,u;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=ss(d);try{if(await ls(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new as;(o=this.onerror)==null||o.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return n(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new xe({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(s=this.onerror)==null||s.call(this,p);return}}catch(l){(u=this.onerror)==null||u.call(this,l);return}};await n()}},bN=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":pi};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 AI(t,`ai-sdk/${LI}`,CI())}async start(){if(this.abortController)throw new xe({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,a,s,u,l;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=ss(f);try{if(await ls(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new as}catch(y){throw(r=this.onerror)==null||r.call(this,y),y}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const y=await f.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${y}`;f.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const x=new xe({message:v});throw(o=this.onerror)==null||o.call(this,x),x}const g=f.headers.get("content-type")||"";if(g.includes("application/json")){const y=await f.json(),v=Array.isArray(y)?y.map(x=>Pi.parse(x)):[Pi.parse(y)];for(const x of v)(a=this.onmessage)==null||a.call(this,x);return}if(g.includes("text/event-stream")){if(!f.body){const S=new xe({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(s=this.onerror)==null||s.call(this,S),S}const v=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).getReader();(async()=>{var S,b,A;try{for(;;){const{done:E,value:C}=await v.read();if(E)return;const{event:P,data:j}=C;if(P==="message")try{const F=Pi.parse(JSON.parse(j));(S=this.onmessage)==null||S.call(this,F)}catch(F){const D=new xe({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(b=this.onerror)==null||b.call(this,D)}}}catch(E){if(E instanceof Error&&E.name==="AbortError")return;(A=this.onerror)==null||A.call(this,E)}})();return}const m=new xe({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});throw(u=this.onerror)==null||u.call(this,m),m}catch(c){throw(l=this.onerror)==null||l.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 xe({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,a,s;try{const u=await this.commonHeaders({Accept:"text/event-stream"});t&&(u["last-event-id"]=t);const l=await fetch(this.url.href,{method:"GET",headers:u,signal:(n=this.abortController)==null?void 0:n.signal}),c=l.headers.get("mcp-session-id");if(c&&(this.sessionId=c),l.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ss(l);try{if(await ls(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const m=new as;(i=this.onerror)==null||i.call(this,m);return}}catch(g){(r=this.onerror)==null||r.call(this,g);return}return this.openInboundSse(!0,t)}if(l.status===405)return;if(!l.ok||!l.body){const g=new xe({message:`MCP HTTP Transport Error: GET SSE failed: ${l.status} ${l.statusText}`});(o=this.onerror)==null||o.call(this,g);return}const f=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).getReader(),p=async()=>{var g,m,y,v;try{for(;;){const{done:x,value:S}=await f.read();if(x)return;const{event:b,data:A,id:E}=S;if(E&&(this.lastInboundEventId=E),b==="message")try{const C=Pi.parse(JSON.parse(A));(g=this.onmessage)==null||g.call(this,C)}catch(C){const P=new xe({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(m=this.onerror)==null||m.call(this,P)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(y=this.onerror)==null||y.call(this,x),(v=this.abortController)!=null&&v.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(a=this.onerror)==null||a.call(this,u),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function _N(e){switch(e.type){case"sse":return new yN(e);case"http":return new bN(e);default:throw new xe({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function wN(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var xN="1.0.0";async function SN(e){const t=new IN(e);return await t.init(),t}var IN=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:n=xN,onUncaughtError:i,capabilities:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=r??{},wN(e)?this.transport=e:this.transport=_N(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 xe({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:pi,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:EO});if(e===void 0)throw new xe({message:"Server sent invalid initialize result"});if(!SO.includes(e.protocolVersion))throw new xe({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 xe({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new xe({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new xe({message:"Server does not support prompts"});break;default:throw new xe({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((i,r)=>{if(this.isClosed)return r(new xe({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const o=n?.signal;o?.throwIfAborted();const a=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:a},u=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,l=>{if(o?.aborted)return r(new xe({message:"Request was aborted",cause:o.reason}));if(l instanceof Error)return r(l);try{const c=t.parse(l.result);i(c)}catch(c){const d=new xe({message:"Failed to parse server response",cause:c});r(d)}}),this.transport.send(s).catch(l=>{u(),r(l)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:$O,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:PO,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:AO,options:t})}catch(n){throw n}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:NO,options:t})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:OO,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:zO,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:UO,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:a}of i.tools){if(e!=="automatic"&&!(r in e))continue;const s=this,u=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),s.callTool({name:r,args:c,options:d})},l=e==="automatic"?fO({description:o,inputSchema:mO({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:u}):{description:o,inputSchema:e[r].inputSchema,execute:u};n[r]=l}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!==nm)throw new xe({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=nm.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=FO.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 xe({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 xe({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new xe({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Zo=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(){}},kN={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},EN=class{#e=kN;#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)}},cr=new EN;function TN(e){setTimeout(e,0)}var vr=typeof window>"u"||"Deno"in globalThis;function pt(){}function $N(e,t){return typeof e=="function"?e(t):e}function gc(e){return typeof e=="number"&&e>=0&&e!==1/0}function HI(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Jn(e,t){return typeof e=="function"?e(t):e}function Mt(e,t){return typeof e=="function"?e(t):e}function am(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:o,queryKey:a,stale:s}=e;if(a){if(i){if(t.queryHash!==nf(a,t.options))return!1}else if(!Gi(t.queryKey,a))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof s=="boolean"&&t.isStale()!==s||r&&r!==t.state.fetchStatus||o&&!o(t))}function sm(e,t){const{exact:n,status:i,predicate:r,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(Wi(t.options.mutationKey)!==Wi(o))return!1}else if(!Gi(t.options.mutationKey,o))return!1}return!(i&&t.state.status!==i||r&&!r(t))}function nf(e,t){return(t?.queryKeyHashFn||Wi)(e)}function Wi(e){return JSON.stringify(e,(t,n)=>bc(n)?Object.keys(n).sort().reduce((i,r)=>(i[r]=n[r],i),{}):n)}function Gi(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Gi(e[n],t[n])):!1}var CN=Object.prototype.hasOwnProperty;function vc(e,t){if(e===t)return e;const n=lm(e)&&lm(t);if(!n&&!(bc(e)&&bc(t)))return t;const r=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),a=o.length,s=n?new Array(a):{};let u=0;for(let l=0;l<a;l++){const c=n?l:o[l],d=e[c],f=t[c];if(d===f){s[c]=d,(n?l<r:CN.call(e,c))&&u++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){s[c]=f;continue}const p=vc(d,f);s[c]=p,p===d&&u++}return r===a&&u===r?e:s}function yc(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 lm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function bc(e){if(!um(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!um(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function um(e){return Object.prototype.toString.call(e)==="[object Object]"}function AN(e){return new Promise(t=>{cr.setTimeout(t,e)})}function _c(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 vc(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 vc(e,t)}return t}function PN(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function RN(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var us=Symbol();function JI(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===us&&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===us?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ON(e,t){return typeof e=="function"?e(...t):!!e}var NN=class extends Zo{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!vr&&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"}},rf=new NN;function wc(){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 jN=TN;function MN(){let e=[],t=0,n=s=>{s()},i=s=>{s()},r=jN;const o=s=>{t?e.push(s):r(()=>{n(s)})},a=()=>{const s=e;e=[],s.length&&r(()=>{i(()=>{s.forEach(u=>{n(u)})})})};return{batch:s=>{let u;t++;try{u=s()}finally{t--,t||a()}return u},batchCalls:s=>(...u)=>{o(()=>{s(...u)})},schedule:o,setNotifyFunction:s=>{n=s},setBatchNotifyFunction:s=>{i=s},setScheduler:s=>{r=s}}}var Ye=MN(),zN=class extends Zo{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!vr&&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}},cs=new zN;function DN(e){return Math.min(1e3*2**e,3e4)}function WI(e){return(e??"online")==="online"?cs.isOnline():!0}var xc=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function GI(e){let t=!1,n=0,i;const r=wc(),o=()=>r.status!=="pending",a=m=>{if(!o()){const y=new xc(m);f(y),e.onCancel?.(y)}},s=()=>{t=!0},u=()=>{t=!1},l=()=>rf.isFocused()&&(e.networkMode==="always"||cs.isOnline())&&e.canRun(),c=()=>WI(e.networkMode)&&e.canRun(),d=m=>{o()||(i?.(),r.resolve(m))},f=m=>{o()||(i?.(),r.reject(m))},p=()=>new Promise(m=>{i=y=>{(o()||l())&&m(y)},e.onPause?.()}).then(()=>{i=void 0,o()||e.onContinue?.()}),g=()=>{if(o())return;let m;const y=n===0?e.initialPromise:void 0;try{m=y??e.fn()}catch(v){m=Promise.reject(v)}Promise.resolve(m).then(d).catch(v=>{if(o())return;const x=e.retry??(vr?0:3),S=e.retryDelay??DN,b=typeof S=="function"?S(n,v):S,A=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,v);if(t||!A){f(v);return}n++,e.onFail?.(n,v),AN(b).then(()=>l()?void 0:p()).then(()=>{t?f(v):g()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(i?.(),r),cancelRetry:s,continueRetry:u,canStart:c,start:()=>(c()?g():p().then(g),r)}}var KI=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),gc(this.gcTime)&&(this.#e=cr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(vr?1/0:300*1e3))}clearGcTimeout(){this.#e&&(cr.clearTimeout(this.#e),this.#e=void 0)}},UN=class extends KI{#e;#t;#n;#i;#r;#s;#a;constructor(e){super(),this.#a=!1,this.#s=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=dm(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.#s,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=dm(this.options);t.data!==void 0&&(this.setState(cm(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=_c(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(pt).catch(pt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Mt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===us||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Jn(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:!HI(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.#a?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 s=this.observers.find(u=>u.options.queryFn);s&&this.setOptions(s.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=s=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#a=!0,n.signal)})},r=()=>{const s=JI(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return i(c),c})();return this.#a=!1,this.options.persister?this.options.persister(s,l,this):s(l)},a=(()=>{const s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return i(s),s})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#o({type:"fetch",meta:a.fetchOptions?.meta}),this.#r=GI({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:s=>{s instanceof xc&&s.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(s,u)=>{this.#o({type:"failed",failureCount:s,error:u})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{const s=await this.#r.start();if(s===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(s),this.#n.config.onSuccess?.(s,this),this.#n.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof xc){if(s.silent)return this.#r.promise;if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#o({type:"error",error:s}),this.#n.config.onError?.(s,this),this.#n.config.onSettled?.(this.state.data,s,this),s}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,...YI(n.data,this.options),fetchMeta:e.meta??null};case"success":const i={...n,...cm(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),Ye.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function YI(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:WI(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function cm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function dm(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 LN=class extends Zo{constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.#a=wc(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#i=void 0;#r;#s;#a;#o;#m;#p;#f;#u;#c;#l;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),pm(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Sc(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Sc(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 Mt(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&&!yc(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const i=this.hasListeners();i&&fm(this.#t,n,this.options,t)&&this.#d(),this.updateResult(),i&&(this.#t!==n||Mt(this.options.enabled,this.#t)!==Mt(t.enabled,this.#t)||Jn(this.options.staleTime,this.#t)!==Jn(t.staleTime,this.#t))&&this.#g();const r=this.#v();i&&(this.#t!==n||Mt(this.options.enabled,this.#t)!==Mt(t.enabled,this.#t)||r!==this.#l)&&this.#y(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return BN(this,n)&&(this.#i=n,this.#s=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.#a.status==="pending"&&this.#a.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(pt)),t}#g(){this.#_();const e=Jn(this.options.staleTime,this.#t);if(vr||this.#i.isStale||!gc(e))return;const n=HI(this.#i.dataUpdatedAt,e)+1;this.#u=cr.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.#l=e,!(vr||Mt(this.options.enabled,this.#t)===!1||!gc(this.#l)||this.#l===0)&&(this.#c=cr.setInterval(()=>{(this.options.refetchIntervalInBackground||rf.isFocused())&&this.#d()},this.#l))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#u&&(cr.clearTimeout(this.#u),this.#u=void 0)}#w(){this.#c&&(cr.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const n=this.#t,i=this.options,r=this.#i,o=this.#r,a=this.#s,u=e!==n?e.state:this.#n,{state:l}=e;let c={...l},d=!1,f;if(t._optimisticResults){const P=this.hasListeners(),j=!P&&pm(e,t),F=P&&fm(e,n,t,i);(j||F)&&(c={...c,...YI(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:m}=c;f=c.data;let y=!1;if(t.placeholderData!==void 0&&f===void 0&&m==="pending"){let P;r?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(P=r.data,y=!0):P=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,P!==void 0&&(m="success",f=_c(r?.data,P,t),d=!0)}if(t.select&&f!==void 0&&!y)if(r&&f===o?.data&&t.select===this.#m)f=this.#p;else try{this.#m=t.select,f=t.select(f),f=_c(r?.data,f,t),this.#p=f,this.#o=null}catch(P){this.#o=P}this.#o&&(p=this.#o,f=this.#p,g=Date.now(),m="error");const v=c.fetchStatus==="fetching",x=m==="pending",S=m==="error",b=x&&v,A=f!==void 0,C={status:m,fetchStatus:c.fetchStatus,isPending:x,isSuccess:m==="success",isError:S,isInitialLoading:b,isLoading:b,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>u.dataUpdateCount||c.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!x,isLoadingError:S&&!A,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:S&&A,isStale:of(e,t),refetch:this.refetch,promise:this.#a,isEnabled:Mt(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const P=D=>{C.status==="error"?D.reject(C.error):C.data!==void 0&&D.resolve(C.data)},j=()=>{const D=this.#a=C.promise=wc();P(D)},F=this.#a;switch(F.status){case"pending":e.queryHash===n.queryHash&&P(F);break;case"fulfilled":(C.status==="error"||C.data!==F.value)&&j();break;case"rejected":(C.status!=="error"||C.error!==F.reason)&&j();break}}return C}updateResult(){const e=this.#i,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#s=this.options,this.#r.data!==void 0&&(this.#f=this.#t),yc(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(a=>{const s=a;return this.#i[s]!==e[s]&&o.has(s)})};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){Ye.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#i)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function FN(e,t){return Mt(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function pm(e,t){return FN(e,t)||e.state.data!==void 0&&Sc(e,t,t.refetchOnMount)}function Sc(e,t,n){if(Mt(t.enabled,e)!==!1&&Jn(t.staleTime,e)!=="static"){const i=typeof n=="function"?n(e):n;return i==="always"||i!==!1&&of(e,t)}return!1}function fm(e,t,n,i){return(e!==t||Mt(i.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&of(e,n)}function of(e,t){return Mt(t.enabled,e)!==!1&&e.isStaleByTime(Jn(t.staleTime,e))}function BN(e,t){return!yc(e.getCurrentResult(),t)}function hm(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let s={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const d=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=JI(t.options,t.fetchOptions),p=async(g,m,y)=>{if(c)return Promise.reject();if(m==null&&g.pages.length)return Promise.resolve(g);const x=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:m,direction:y?"backward":"forward",meta:t.options.meta};return d(E),E})(),S=await f(x),{maxPages:b}=t.options,A=y?RN:PN;return{pages:A(g.pages,S,b),pageParams:A(g.pageParams,m,b)}};if(r&&o.length){const g=r==="backward",m=g?ZN:mm,y={pages:o,pageParams:a},v=m(i,y);s=await p(y,v,g)}else{const g=e??o.length;do{const m=u===0?a[0]??i.initialPageParam:mm(i,s);if(u>0&&m==null)break;s=await p(s,m),u++}while(u<g)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function mm(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 ZN(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var qN=class extends KI{#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||VN(),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=GI({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{this.#r({type:"failed",failureCount:o,error:a})},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 a=await this.options.onMutate?.(e,n);a!==this.state.context&&this.#r({type:"pending",context:a,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),Ye.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function VN(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var HN=class extends Zo{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 qN({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=ha(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=ha(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=ha(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=ha(e);return typeof t=="string"?this.#t.get(t)?.find(i=>i!==e&&i.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ye.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=>sm(t,n))}findAll(e={}){return this.getAll().filter(t=>sm(e,t))}notify(e){Ye.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ye.batch(()=>Promise.all(e.map(t=>t.continue().catch(pt))))}};function ha(e){return e.options.scope?.id}var JN=class extends Zo{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const i=t.queryKey,r=t.queryHash??nf(i,t);let o=this.get(r);return o||(o=new UN({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(){Ye.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=>am(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>am(e,n)):t}notify(e){Ye.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ye.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ye.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},WN=class{#e;#t;#n;#i;#r;#s;#a;#o;constructor(e={}){this.#e=e.queryCache||new JN,this.#t=e.mutationCache||new HN,this.#n=e.defaultOptions||{},this.#i=new Map,this.#r=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#a=rf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=cs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#a?.(),this.#a=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(Jn(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,a=$N(t,o);if(a!==void 0)return this.#e.build(this,i).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Ye.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;Ye.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Ye.batch(()=>(n.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},i=Ye.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(i).then(pt).catch(pt)}invalidateQueries(e,t={}){return Ye.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=Ye.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(pt)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(i).then(pt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Jn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(pt).catch(pt)}fetchInfiniteQuery(e){return e.behavior=hm(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(pt).catch(pt)}ensureInfiniteQueryData(e){return e.behavior=hm(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return cs.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(Wi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(i=>{Gi(e,i.queryKey)&&Object.assign(n,i.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(Wi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(i=>{Gi(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=nf(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===us&&(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()}},QI=w.createContext(void 0),XI=e=>{const t=w.useContext(QI);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},GN=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),h.jsx(QI.Provider,{value:e,children:t})),ek=w.createContext(!1),KN=()=>w.useContext(ek);ek.Provider;function YN(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var QN=w.createContext(YN()),XN=()=>w.useContext(QN),ej=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},tj=e=>{w.useEffect(()=>{e.clearReset()},[e])},nj=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&e.data===void 0||ON(n,[e.error,i])),rj=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))}},ij=(e,t)=>e.isLoading&&e.isFetching&&!t,oj=(e,t)=>e?.suspense&&t.isPending,gm=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function aj(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=KN(),r=XN(),o=XI(),a=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(a),process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.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`)),a._optimisticResults=i?"isRestoring":"optimistic",rj(a),ej(a,r),tj(r);const s=!o.getQueryCache().get(a.queryHash),[u]=w.useState(()=>new t(o,a)),l=u.getOptimisticResult(a),c=!i&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(d=>{const f=c?u.subscribe(Ye.batchCalls(d)):pt;return u.updateResult(),f},[u,c]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),w.useEffect(()=>{u.setOptions(a)},[a,u]),oj(a,l))throw gm(a,u,r);if(nj({result:l,errorResetBoundary:r,throwOnError:a.throwOnError,query:o.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw l.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!vr&&ij(l,i)&&(s?gm(a,u,r):o.getQueryCache().get(a.queryHash)?.promise)?.catch(pt).finally(()=>{u.updateResult()}),a.notifyOnChangeProps?l:u.trackResult(l)}function tk(e,t){return aj(e,LN)}function sj({auth:e,mcp:t,environment:n}){const i=Object.entries(e.headers??{}).map((o,a)=>`${o}:${a}`);return tk({queryKey:["mcpTools",t,...i],queryFn:async()=>(_.assert(!e.isLoading,"No auth found"),_.assert(t,"No MCP URL found"),await(await SN({name:"gram-elements-mcp-client",transport:{type:"http",url:t,headers:{...lj(n??{}),...e.headers}}})).tools()),enabled:!e.isLoading&&!!t,staleTime:1/0,gcTime:1/0})}const vm="MCP-";function lj(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[n,i])=>{const r=n.replace(/_/g,"-"),o=r.startsWith(vm)?r:`${vm}${r}`;return t[o]=i,t},{})}const nk=()=>{const e=$.useContext(_.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e};function uj(e){return(e.api?.url||""||"https://app.getgram.ai").replace(/\/+$/,"")}const af=["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"];class sf{_contextProvider=new _.CompositeContextProvider;registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}getModelContextProvider(){return this._contextProvider}}class Ol{_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 cj=e=>e.status.type==="complete";class rk extends Ol{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=>cj(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 a=this._attachments.findIndex(s=>s.id===o.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),o,...this._attachments.slice(a+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 ik extends rk{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 ok=(e,t=21)=>(n=t)=>{let i="",r=n|0;for(;r--;)i+=e[Math.random()*e.length|0];return i};const qo=ok("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),dj="__optimistic__",pj=()=>`${dj}${qo()}`,fi=Symbol("autoStatus"),fj=Object.freeze(Object.assign({type:"running"},{[fi]:!0})),hj=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[fi]:!0})),mj=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[fi]:!0})),gj=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[fi]:!0})),ak=e=>e[fi]===!0,Vo=(e,t,n,i,r)=>e&&r?Object.assign({type:"incomplete",reason:"error",error:r},{[fi]:!0}):e&&t?fj:n?gj:i?mj:hj;function Ho(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ar={exports:{}},ym;function vj(){if(ym)return ar.exports;ym=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(s,u,l){l==null&&u!==null&&typeof u=="object"&&(l=u,u=void 0),e&&Buffer.isBuffer(s)&&(s=s.toString()),s&&s.charCodeAt(0)===65279&&(s=s.slice(1));const c=JSON.parse(s,u);if(c===null||typeof c!="object")return c;const d=l&&l.protoAction||"error",f=l&&l.constructorAction||"error";if(d==="ignore"&&f==="ignore")return c;if(d!=="ignore"&&f!=="ignore"){if(t.test(s)===!1&&n.test(s)===!1)return c}else if(d!=="ignore"&&f==="ignore"){if(t.test(s)===!1)return c}else if(n.test(s)===!1)return c;return r(c,{protoAction:d,constructorAction:f,safe:l&&l.safe})}function r(s,{protoAction:u="error",constructorAction:l="error",safe:c}={}){let d=[s];for(;d.length;){const f=d;d=[];for(const p of f){if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(p,"__proto__")){if(c===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.__proto__}if(l!=="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(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.constructor}for(const g in p){const m=p[g];m&&typeof m=="object"&&d.push(m)}}}return s}function o(s,u,l){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return i(s,u,l)}finally{Error.stackTraceLimit=c}}function a(s,u){const{stackTraceLimit:l}=Error;Error.stackTraceLimit=0;try{return i(s,u,{safe:!0})}catch{return}finally{Error.stackTraceLimit=l}}return ar.exports=o,ar.exports.default=o,ar.exports.parse=o,ar.exports.safeParse=a,ar.exports.scan=r,ar.exports}var yj=vj();const Ic=Ho(yj);function bj(e){const t=["ROOT"];let n=-1,i=null;const r=[];let o;function a(){o!==void 0&&(r.push(JSON.parse(`"${o}"`)),o=void 0)}function s(d,f,p){switch(d){case'"':{n=f,t.pop(),t.push(p),t.push("INSIDE_STRING"),a();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"),a();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"),a();break}case"{":{n=f,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START"),a();break}case"[":{n=f,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START"),a();break}}}function u(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=f,t.pop(),o=r.pop();break}}}function l(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":s(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":{s(f,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{u(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",s(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":{s(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"&&l(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&u(f,d);break}case"}":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&u(f,d);break}case"]":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d);break}default:{t.pop(),o=r.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(i,d+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?u(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(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 ja=Symbol("aui.parse-partial-json-object.meta"),_j=e=>e?.[ja],ds=e=>{if(e.length===0)return{[ja]:{state:"partial",partialPath:[]}};try{const t=Ic.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[ja]={state:"complete",partialPath:[]},t}catch{try{const[t,n]=bj(e),i=Ic.parse(t);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[ja]={state:"partial",partialPath:n},i}catch{return}}},sk=(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,...a]=t.partialPath;if(i!==o)return"complete";const s=e[i];return sk(s,{state:"partial",partialPath:a},r)},ai=(e,t)=>{const n=_j(e);if(!n)throw new Error("unable to determine object state");return sk(e,n,t.map(String))};async function*wj(){const e=this.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{e.releaseLock()}}function pu(e){return e[Symbol.asyncIterator]??=wj,e}const kc={toResponse(e,t){return new Response(kc.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return kc.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},lf=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}},xj=()=>{const e=[];let t=!1,n,i;const r=a=>{a.promise||(a.promise=a.reader.read().then(({done:s,value:u})=>{a.promise=void 0,s?(e.splice(e.indexOf(a),1),t&&e.length===0&&n.close()):n.enqueue(u),i?.resolve(),i=void 0}).catch(s=>{console.error(s),e.forEach(u=>{u.reader.cancel()}),e.length=0,n.error(s),i?.reject(s),i=void 0}))};return{readable:new ReadableStream({start(a){n=a},pull(){return i=lf(),e.forEach(a=>{r(a)}),i.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(a){if(t)throw new Error("Cannot add streams after the run callback has settled.");const s={reader:a.getReader()};e.push(s),r(s)},enqueue(a){this.addStream(new ReadableStream({start(s){s.enqueue(a),s.close()}}))}}};class bm{_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 lk=e=>new ReadableStream({start(t){return e.start?.(new bm(t))},pull(t){return e.pull?.(new bm(t))},cancel(t){return e.cancel?.(t)}}),_m=()=>{let e;return[lk({start(n){e=n}}),e]};class wm{_controller;_isClosed=!1;_mergeTask;constructor(t){this._controller=t;const n=lk({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 Sj=e=>new ReadableStream({start(t){return e.start?.(new wm(t))},pull(t){return e.pull?.(new wm(t))},cancel(t){return e.cancel?.(t)}}),Ij=()=>{let e;return[Sj({start(n){e=n}}),e]};class uk{value=-1;up(){return++this.value}}class kj extends TransformStream{constructor(t){super({transform(n,i){i.enqueue({...n,path:[t,...n.path]})}})}}class hK 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 Ej extends TransformStream{constructor(t){const n=new uk,i=new Map;super({transform(r,o){r.type==="part-start"&&r.path.length===0&&i.set(n.up(),t.up());const[a,...s]=r.path;if(a===void 0){o.enqueue(r);return}const u=i.get(a);if(u===void 0)throw new Error("Path not found");o.enqueue({...r,path:[u,...s]})}})}}class ck extends TransformStream{constructor(t){super();const n=t(super.readable);Object.defineProperty(this,"readable",{value:n,writable:!1})}}class dk 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 pk=ok("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class uf{_state;_parentId;constructor(t){this._state=t||{merger:xj(),contentCounter:new uk}}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 kj(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new Ej(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]=_m();return this._addPart({type:"text"},t),n}addReasoningPart(){const[t,n]=_m();return this._addPart({type:"reasoning"},t),n}addToolCallPart(t){const n=typeof t=="string"?{toolName:t}:t,i=n.toolName,r=n.toolCallId??pk(),[o,a]=Ij();return this._addPart({type:"tool-call",toolName:i,toolCallId:r,...this._parentId&&{parentId:this._parentId}},o),n.argsText!==void 0&&(a.argsText.append(n.argsText),a.argsText.close()),n.args!==void 0&&(a.argsText.append(JSON.stringify(n.args)),a.argsText.close()),n.response!==void 0&&a.setResponse(n.response),a}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 uf(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}function Tj(e){const t=new uf;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 fk(){const{resolve:e,promise:t}=lf();let n;return[Tj(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}class $j extends TransformStream{constructor(t,n,i){const[r,o]=fk();let a;super({start(s){return a=r.pipeTo(new WritableStream({write(u){s.enqueue(u)},abort(u){s.error(u)},close(){s.terminate()}})).catch(u=>{s.error(u)}),t.start?.(o)},transform(s){return t.transform?.(s,o)},async flush(){await t.flush?.(o),o.close(),await a}},n,i)}}const kr=(e,t,n)=>{const{role:i,id:r,createdAt:o,attachments:a,status:s,metadata:u}=e,l={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"&&a?.length)throw new Error("attachments are only supported for user messages");if(i!=="assistant"&&s)throw new Error("status is only supported for assistant messages");if(i!=="assistant"&&u?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(i){case"assistant":return{...l,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:g,messages:m,...y}=f,v={...y,toolCallId:f.toolCallId??`tool-${qo()}`,...g!==void 0&&{parentId:g},...m!==void 0&&{messages:m}};return f.args?{...v,args:f.args,argsText:f.argsText??JSON.stringify(f.args)}:{...v,args:ds(f.argsText??"")??{},argsText:f.argsText??""}}default:{const g=p;throw new Error(`Unsupported assistant message part type: ${g}`)}}}).filter(f=>!!f),status:s??n,metadata:{unstable_state:u?.unstable_state??null,unstable_annotations:u?.unstable_annotations??[],unstable_data:u?.unstable_data??[],custom:u?.custom??{},steps:u?.steps??[],...u?.submittedFeedback&&{submittedFeedback:u.submittedFeedback}}};case"user":return{...l,role:i,content:c.map(f=>{const p=f.type;switch(p){case"text":case"image":case"audio":case"file":return f;default:{const g=p;throw new Error(`Unsupported user message part type: ${g}`)}}}),attachments:a??[],metadata:{custom:u?.custom??{}}};case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...l,role:i,content:c,metadata:{custom:u?.custom??{}}};default:{const f=i;throw new Error(`Unknown message role: ${f}`)}}},cf={fromArray:e=>{const t=e.map(n=>kr(n,qo(),Vo(!1,!1,!1,!1,void 0)));return{messages:t.map((n,i)=>({parentId:i>0?t[i-1].id:null,message:n}))}}},Ma=e=>e.next?Ma(e.next):"current"in e?e:null;class Cj{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 df=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(a=>a!==n.current.id),r.next===n)){const a=r.children.at(-1),s=a?this.messages.get(a):null;if(s===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=s}if(i!=="cut"){for(let s=t;s;s=s.prev)if(s.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],(Ma(n)===this.head||o.next===null)&&(o.next=n),n.prev=t;const a=t?t.level+1:0;this.updateLevels(n,a)}}}_messages=new Cj(()=>{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=pj();while(this.messages.has(i));return this.addOrUpdateMessage(t,kr(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 a=this.messages.get(o);if(!a)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,a,"relink")}this.performOp(null,i,"cut"),this.messages.delete(t),this.head===i&&(this.head=Ma(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=Ma(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 a=this.messages.get(o);a&&(i(a),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 Nl{_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 nn=Symbol("skip-update");class pf extends Nl{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!==nn&&(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 ma{_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(),a=o.isMain,s=o.id;i===a&&r===s||(i=a,r=s,!(t==="switched-to"&&!a)&&(t==="switched-away"&&a||n()))})}subscribe(t){return this._core.subscribe(t)}detach(){const t=this._core.getState();this._threadListBinding.detach(t.id)}__internal_getRuntime(){return this}}function Aj(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 Qt extends Nl{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t;const n=t.getState();if(n===nn)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===nn||Aj(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}}const St=Symbol("innerMessage"),fu=Symbol("innerMessages"),Pj=e=>e[St],Rj=[],hr=e=>{const t="messages"in e?e.messages:e,n=t[fu]||t[St];return n?Array.isArray(n)?n:(t[fu]=[n],t[fu]):Rj},Ki=e=>e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
30
|
+
|
|
31
|
+
`);class hk{_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 mk extends hk{_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 Oj extends mk{get source(){return"thread-composer"}}class Nj extends mk{get source(){return"edit-composer"}}class jj extends hk{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}}class gk extends Nl{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 a=this.config.binding.getState();a!==n&&(n=a,i?.(),i=this.config.binding.getState()?.unstable_on(this.config.event,t))},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const vk=Object.freeze([]),yk=Object.freeze({}),Mj=e=>Object.freeze({type:"thread",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??vk,text:e?.text??"",role:e?.role??"user",runConfig:e?.runConfig??yk,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""}),zj=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??vk,runConfig:e?.runConfig??yk,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""});class bk{_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 gk({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}class Dj extends bk{get path(){return this._core.path}get type(){return"thread"}_getState;constructor(t){const n=new pf({path:t.path,getState:()=>Mj(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 Oj(new Qt({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"}:nn},subscribe:n=>this._core.subscribe(n)}),this._core)}}class Uj extends bk{_beginEdit;get path(){return this._core.path}get type(){return"edit"}_getState;constructor(t,n){const i=new pf({path:t.path,getState:()=>zj(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 Nj(new Qt({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"}:nn},subscribe:n=>this._core.subscribe(n)}),this._core)}}class ji{_state;constructor(t=null){this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,i)=>ji.apply(n,i),this._state)}static apply(t,n){const i=n.type;switch(i){case"set":return ji.updatePath(t,n.path,()=>n.value);case"append-text":return ji.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 s=Number(r);if(Number.isNaN(s))throw new Error(`Expected array index at [${n.join(", ")}]`);if(s>t.length||s<0)throw new Error("Insert array index out of bounds");const u=[...t];return u[s]=this.updatePath(u[s],o,i),u}const a={...t};return a[r]=this.updatePath(a[r],o,i),a}}const Lj=({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:{}}}),jl=(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}}},Fj=(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}`)},Bj=(e,t)=>jl(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"}}),Zj=(e,t)=>jl(e,t,n=>({...n,status:{type:"complete",reason:"unknown"}})),qj=(e,t)=>jl(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=ds(i)??n.args;return{...n,argsText:i,args:r}}else throw new Error("text-delta received but part is neither text nor tool-call")}),Vj=(e,t)=>jl(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")}),xm=(e,t)=>{if(e.status?.type==="incomplete"&&e.status?.reason==="error")return e;const n=Hj(t);return{...e,status:n}},Hj=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},Jj=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),Wj=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),Gj=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]}}),Kj=(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:pk(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},Yj=(e,t)=>({...e,status:{type:"incomplete",reason:"error",error:t.error}}),Qj=(e,t)=>{const n=new ji(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},Xj=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}};class eM extends TransformStream{constructor({initialMessage:t,throttle:n,onError:i}={}){let r=t??Lj(),o;const a=n?Xj(()=>{o?.enqueue(r)}):()=>{o?.enqueue(r)};super({start(s){o=s},transform(s){const u=s.type;switch(u){case"part-start":r=Fj(r,s);break;case"tool-call-args-text-finish":r=Bj(r,s);break;case"part-finish":r=Zj(r,s);break;case"text-delta":r=qj(r,s);break;case"result":r=Vj(r,s);break;case"message-finish":r=xm(r,s);break;case"annotations":r=Jj(r,s);break;case"data":r=Wj(r,s);break;case"step-start":r=Gj(r,s);break;case"step-finish":r=Kj(r,s);break;case"error":r=Yj(r,s),i?.(s.error);break;case"update-state":r=Qj(r,s);break;default:{const l=u;throw new Error(`Unsupported chunk type: ${l}`)}}a()},flush(s){if(r.status?.type==="running"){const u=r.parts?.some(l=>l.type==="tool-call"&&(l.state==="call"||l.state==="partial-call")&&l.result===void 0)??!1;r=xm(r,{finishReason:u?"tool-calls":"unknown"}),s.enqueue(r)}}})}}class tM extends ck{constructor(){super(t=>{const n=new $j({transform(i,r){r.appendText(i)}});return t.pipeThrough(new TextDecoderStream).pipeThrough(n)})}}class Mi{readable;constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new Mi(t.pipeThrough(new eM))}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 Mi(t),new Mi(n)]}}const Sm=Symbol.for("aui.tool-response");class en{get[Sm](){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&&Sm in t}static toResponse(t){return t instanceof en?t:new en({result:t===void 0?"<no result>":t})}}function nM(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 Jo(e,t){let n=e;for(const i of t){if(n==null)return;n=n[i]}return n}class rM{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(ai(t,this.fieldPath)==="complete"){const n=Jo(t,this.fieldPath);n!==void 0&&(this.resolve(n),this.dispose())}}catch(n){this.reject(n),this.dispose()}}dispose(){this.disposed=!0}}class Im{controller;disposed=!1;fieldPath;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=Jo(t,this.fieldPath);n!==void 0&&this.controller.enqueue(n),ai(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class km{controller;disposed=!1;fieldPath;lastValue=void 0;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=Jo(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)}ai(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class Em{controller;disposed=!1;fieldPath;processedIndexes=new Set;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=Jo(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];ai(t,r)==="complete"&&(this.controller.enqueue(n[i]),this.processedIndexes.add(i))}ai(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class iM{argTextDeltas;handles=new Set;args=ds("");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=ds(t);if(o!==void 0){this.args=o;for(const a of this.handles)a.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 rM(n,i,t);if(this.args&&ai(this.args,t)==="complete"){const o=Jo(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 Im(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Im){r.dispose(),this.handles.delete(r);break}}});return pu(i)}streamText(...t){const n=t,i=new ReadableStream({start:r=>{const o=new km(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof km){r.dispose(),this.handles.delete(r);break}}});return pu(i)}forEach(...t){const n=t,i=new ReadableStream({start:r=>{const o=new Em(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Em){r.dispose(),this.handles.delete(r);break}}});return pu(i)}}class oM{promise;constructor(t){this.promise=t}get(){return this.promise}}class aM{args;response;writable;resolve;argsText="";constructor(){const t=new TransformStream;this.writable=t.writable,this.args=new iM(t.readable);const{promise:n,resolve:i}=lf();this.resolve=i,this.response=new oM(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 sM extends ck{constructor(t){const n=new Map,i=new Map;super(r=>{const o=new TransformStream({transform(a,s){switch((a.type!=="part-finish"||a.meta.type!=="tool-call")&&s.enqueue(a),a.type){case"part-start":if(a.part.type==="tool-call"){const l=new aM;i.set(a.part.toolCallId,l),t.streamCall({reader:l,toolCallId:a.part.toolCallId,toolName:a.part.toolName})}break;case"text-delta":{if(a.meta.type==="tool-call"){const l=a.meta.toolCallId,c=i.get(l);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(a.textDelta)}break}case"result":{if(a.meta.type!=="tool-call")break;const{toolCallId:l}=a.meta,c=i.get(l);if(!c)throw new Error("No controller found for tool call");c.setResponse(new en({result:a.result,artifact:a.artifact,isError:a.isError}));break}case"tool-call-args-text-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:l,toolName:c}=a.meta,d=i.get(l);if(!d)throw new Error("No controller found for tool call");let f=!1;const p=nM(()=>{let g;try{g=Ic.parse(d.argsText)}catch(y){throw new Error(`Function parameter parsing failed. ${JSON.stringify(y.message)}`)}const m=t.execute({toolCallId:l,toolName:c,args:g});return m!==void 0&&(f=!0,t.onExecutionStart?.(l,c)),m},g=>{if(f&&t.onExecutionEnd?.(l,c),g===void 0)return;const m=new en({artifact:g.artifact,result:g.result,isError:g.isError});d.setResponse(m),s.enqueue({type:"result",path:a.path,...m})},g=>{f&&t.onExecutionEnd?.(l,c);const m=new en({result:String(g),isError:!0});d.setResponse(m),s.enqueue({type:"result",path:a.path,...m})});p&&n.set(l,p);break}case"part-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:l}=a.meta,c=n.get(l);c?c.then(()=>{n.delete(l),i.delete(l),s.enqueue(a)}):s.enqueue(a)}}},async flush(){await Promise.all(n.values())}});return r.pipeThrough(new dk).pipeThrough(o)})}}const lM=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function uM(e,t,n,i){const r=e?.[n.toolName];return!r||!r.execute?void 0:(async a=>{if(t.aborted)return new en({result:"Tool execution was cancelled.",isError:!0});let s=a;if(lM(r.parameters)){let c=r.parameters["~standard"].validate(n.args);c instanceof Promise&&(c=await c),c.issues&&(s=r.experimental_onSchemaValidationError??(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const u=new Promise(c=>{const d=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new en({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?d():t.addEventListener("abort",d,{once:!0})}),l=(async()=>{const c=await s(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:d=>i(n.toolCallId,d)});return en.toResponse(c)})();return Promise.race([l,u])})(r.execute)}function cM(e,t,n,i,r){e?.[i.toolName]?.streamCall?.(n,{toolCallId:i.toolCallId,abortSignal:t,human:o=>r(i.toolCallId,o)})}function dM(e,t,n,i){const r=typeof e=="function"?e:()=>e,o=typeof t=="function"?t:()=>t;return new sM({execute:a=>uM(r(),o(),a,n),streamCall:({reader:a,...s})=>cM(r(),o(),a,s,n),onExecutionStart:i?.onExecutionStart,onExecutionEnd:i?.onExecutionEnd})}class Tm{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,a=en.toResponse(t);this.threadApi.getState().addToolResult({messageId:i.id,toolName:r,toolCallId:o,result:a.result,artifact:a.artifact,isError:a.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 ps extends Nl{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 a=this.binding.getState();a!==n&&(n=a,i?.(),i=this.binding.getState()?.subscribe(t),t())},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const ga=Object.freeze({type:"complete"}),pM=(e,t,n)=>{if(e.role!=="assistant")return ga;if(n.type==="tool-call")return n.result?ga:e.status;const i=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?ga:i?e.status:ga},$m=(e,t)=>{const n=e.content[t];if(!n)return nn;const i=pM(e,t,n);return Object.freeze({...n,[St]:n[St],status:i})};class fM{_core;_threadBinding;get path(){return this._core.path}constructor(t,n){this._core=t,this._threadBinding=n,this.composer=new Uj(new ps({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,a=this._core.getState();if(a.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.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 a=n;if(t==="previous"?a=o[i.branchNumber-2]:t==="next"&&(a=o[i.branchNumber]),!a)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(a)}unstable_getCopyText(){return Ki(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 Tm(new Qt({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${t}]`,messagePartSelector:{type:"index",index:t}},getState:()=>$m(this.getState(),t),subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getMessagePartByToolCallId(t){return new Tm(new Qt({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?nn:$m(n,i)},subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new jj(new Qt({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"}:nn},subscribe:n=>this._core.subscribe(n)}))}}const hM=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),mM=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),gM=(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},vM=(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 _k{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(t,n){const i=new Qt({path:t.path,getState:()=>vM(t.getState(),n.getState()),subscribe:r=>{const o=t.subscribe(r),a=n.subscribe(r);return()=>{o(),a()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>i.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new Dj(new ps({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(gM(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(mM(n))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(hM(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 fM(new Qt({path:t,getState:()=>{const{message:i,parentId:r,index:o}=n()??{},{messages:a,speech:s}=this._threadBinding.getState();if(!i||r===void 0||o===void 0)return nn;const l=this._threadBinding.getState().getBranches(i.id),c=i.metadata.submittedFeedback;return{...i,[St]:i[St],index:o,isLast:a.at(-1)?.id===i.id,parentId:r,branchNumber:l.indexOf(i.id)+1,branchCount:l.length,speech:s?.messageId===i.id?s: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 gk({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}const yM=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),va=(e,t)=>{if(t===void 0)return nn;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}:nn};class bM{_core;_runtimeFactory;_getState;constructor(t,n=_k){this._core=t,this._runtimeFactory=n;const i=new pf({path:{},getState:()=>yM(t),subscribe:r=>t.subscribe(r)});this._getState=i.getState.bind(i),this._mainThreadListItemRuntime=new ma(new Qt({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>va(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new n(new ps({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 ps({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 ma(new Qt({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>va(this._core,this._core.threadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getArchivedItemByIndex(t){return new ma(new Qt({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>va(this._core,this._core.archivedThreadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getItemById(t){return new ma(new Qt({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>va(this._core,t),subscribe:n=>this._core.subscribe(n)}),this._core)}}const _M=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file";class wM{cloud;accept="*";constructor(t){this.cloud=t}uploadedUrls=new Map;async*add({file:t}){const n=crypto.randomUUID(),i=_M(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:a}=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,a),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 Ec=$.createContext(null),wk=({adapters:e,children:t})=>{const n=$.useContext(Ec);return h.jsx(Ec.Provider,{value:{...n,...e},children:t})},xk=()=>$.useContext(Ec),sr=Object.freeze([]),dr="DEFAULT_THREAD_ID",xM=Object.freeze([dr]),Sk=Object.freeze({id:dr,remoteId:void 0,externalId:void 0,status:"regular"}),SM=Promise.resolve(),Cm=Object.freeze({[dr]:Sk});class IM{adapter;threadFactory;_mainThreadId=dr;_threads=xM;_archivedThreads=sr;_threadData=Cm;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 SM}_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===dr)return Sk}__internal_setAdapter(t,n=!1){const i=this.adapter;this.adapter=t;const r=t.threadId??dr,o=t.threads??sr,a=t.archivedThreads??sr,s=i.threadId??dr,u=i.threads??sr,l=i.archivedThreads??sr;!n&&s===r&&u===o&&l===a||(this._threadData={...Cm,...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"}])??[])},u!==o&&(this._threads=this.adapter.threads?.map(c=>c.id)??sr),l!==a&&(this._archivedThreads=this.adapter.archivedThreads?.map(c=>c.id)??sr),s!==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 Tc{cache=new WeakMap;convertMessages(t,n){return t.map((i,r)=>{const o=this.cache.get(i),a=n(o,i,r);return this.cache.set(i,a),a})}}class kM extends rk{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=Ki(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){Ki(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 EM{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new df;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 ik(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 kM(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 a={...r,metadata:{...r.metadata,submittedFeedback:{type:n}}};this.repository.addOrUpdateMessage(o,a)}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(Ki(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(cf.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 TM=Object.freeze([]),$M=(e,t)=>e&&t[t.length-1]?.role!=="assistant";class CM extends EM{_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 Tc;_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??TM,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 Tc;else if(i.isRunning===t.isRunning&&i.messages===t.messages){this._notifySubscribers();return}}r=t.convertMessage?this._converter.convertMessages(t.messages,(o,a,s)=>{if(!t.convertMessage)return a;const u=s===t.messages.length-1,l=Vo(u,n,!1,!1,void 0);if(o&&(o.role!=="assistant"||!ak(o.status)||o.status===l))return o;const c=t.convertMessage(a,s),d=kr(c,s.toString(),l);return d[St]=a,d}):t.messages;for(let o=0;o<r.length;o++){const a=r[o],s=r[o-1];this.repository.addOrUpdateMessage(s?.id??null,a)}}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),$M(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(Ki(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 df;n.import(cf.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(Pj).filter(i=>i!=null)):this._store.setMessages?.(t)}}const Am=e=>e.adapters?.threadList??{};class AM extends sf{threads;constructor(t){super(),this.threads=new IM(Am(t),()=>new CM(this._contextProvider,t))}setAdapter(t){this.threads.__internal_setAdapter(Am(t)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(t)}}const PM=e=>{const[t]=$.useState(()=>new AM(e));$.useEffect(()=>{t.setAdapter(e)});const{modelContext:n}=xk()??{};return $.useEffect(()=>{if(n)return t.registerModelContextProvider(n)},[n,t]),$.useMemo(()=>new hf(t),[t])},RM=e=>{try{return JSON.parse(e),!0}catch{return!1}};function Ik({state:e,getTools:t,onResult:n,setToolStatuses:i}){const r=$.useRef({}),o=$.useRef(new Map),a=$.useRef(new AbortController),s=$.useRef(0),u=$.useRef([]),[l]=$.useState(()=>{const[p,g]=fk(),m=dM(t,()=>a.current?.signal??new AbortController().signal,(y,v)=>new Promise((x,S)=>{const b=o.current.get(y);b&&b.reject(new Error("Human input request was superseded by a new request")),o.current.set(y,{resolve:x,reject:S}),i(A=>({...A,[y]:{type:"interrupt",payload:{type:"human",payload:v}}}))}),{onExecutionStart:y=>{s.current++,i(v=>({...v,[y]:{type:"executing"}}))},onExecutionEnd:y=>{s.current--,i(v=>{const x={...v};return delete x[y],x}),s.current===0&&(u.current.forEach(v=>v()),u.current=[])}});return p.pipeThrough(m).pipeThrough(new dk).pipeTo(new WritableStream({write(y){if(y.type==="result"){if(r.current[y.meta.toolCallId]?.hasResult)return;n({type:"add-tool-result",toolCallId:y.meta.toolCallId,toolName:y.meta.toolName,result:y.result,isError:y.isError,...y.artifact&&{artifact:y.artifact}})}}})),g}),c=$.useRef(new Set),d=$.useRef(!0);$.useEffect(()=>{const p=g=>{g.forEach(m=>{m.content.forEach(y=>{if(y.type==="tool-call"){if(d.current)c.current.add(y.toolCallId);else{if(c.current.has(y.toolCallId))return;let v=r.current[y.toolCallId];if(v||(v={argsText:"",hasResult:!1,argsComplete:!1,controller:l.addToolCallPart({toolName:y.toolName,toolCallId:y.toolCallId})},r.current[y.toolCallId]=v),y.argsText!==v.argsText)if(v.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:v.argsText,next:y.argsText});else{if(!y.argsText.startsWith(v.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${y.argsText} does not start with ${v.argsText}`);const x=y.argsText.slice(v.argsText.length);v.controller.argsText.append(x);const S=RM(y.argsText);S&&v.controller.argsText.close(),r.current[y.toolCallId]={argsText:y.argsText,hasResult:v.hasResult,argsComplete:S,controller:v.controller}}y.result!==void 0&&!v.hasResult&&(v.controller.setResponse(new en({result:y.result,artifact:y.artifact,isError:y.isError})),v.controller.close(),r.current[y.toolCallId]={hasResult:!0,argsComplete:!0,argsText:v.argsText,controller:v.controller})}y.messages&&p(y.messages)}})})};p(e.messages),d.current&&(d.current=!1)},[e,l,n]);const f=()=>(o.current.forEach(({reject:p})=>{p(new Error("Tool execution aborted"))}),o.current.clear(),a.current.abort(),a.current=new AbortController,s.current===0?Promise.resolve():new Promise(p=>{u.current.push(p)}));return{reset:()=>{f(),d.current=!0},abort:f,resume:(p,g)=>{const m=o.current.get(p);if(m)o.current.delete(p),i(y=>({...y,[p]:{type:"executing"}})),m.resolve(g);else throw new Error(`Tool call ${p} is not waiting for human input`)}}}class OM{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"))}}const NM=e=>{const t=_.useAssistantApi();$.useEffect(()=>{if(e.render)return t.tools().setToolUI(e.toolName,e.render)},[t,e.toolName,e.render]),$.useEffect(()=>{const{toolName:n,render:i,...r}=e,o={tools:{[n]:r}};return t.modelContext().register({getModelContext:()=>o})},[t,e])},jM=e=>{const t=()=>(NM(e),null);return t.unstable_tool=e,t};function Pm(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ff(...e){return t=>{let n=!1;const i=e.map(r=>{const o=Pm(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():Pm(e[r],null)}}}}function Ge(...e){return w.useCallback(ff(...e),e)}const hu=(e,t)=>{const n=_.useAssistantApi(),i=$.useRef(t);$.useEffect(()=>{i.current=t});const{scope:r,event:o}=_.normalizeEventSelector(e);$.useEffect(()=>n.on({scope:r,event:o},a=>i.current(a)),[n,r,o])};function MM(e,t){function n(i){const r=$.useContext(e);if(!i?.optional&&!r)throw new Error(`This component must be used within ${t}.`);return r}return n}function kk(e,t){function n(r){const o=e(r);return o?o[t]:null}function i(r){let o=!1,a;typeof r=="function"?a=r:r&&typeof r=="object"&&(o=!!r.optional,a=r.selector);const s=n({optional:o});return s?a?s(a):s():null}return{[t]:i,[`${t}Store`]:n}}const Ek=$.createContext(null),zM=MM(Ek,"ThreadPrimitive.Viewport"),{useThreadViewport:Yi,useThreadViewportStore:Ml}=kk(zM,"useThreadViewport"),Tk=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,[St]:[...r[St]??[],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,[St]:[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},$k=(e,t)=>{const n=[];let i=!1,r=!1,o=[],a=[];const s=()=>{a.length&&n.push({inputs:o,outputs:a}),o=[],a=[],i=!1,r=!1};for(const u of e)for(const l of u.outputs)(r&&l.role!=="tool"||!i||l.role==="user"||l.role==="system")&&s(),i=l.role==="assistant"||l.role==="tool",o.at(-1)!==u.input&&o.push(u.input),a.push(l),l.role==="assistant"&&(l.convertConfig?.joinStrategy==="none"||t==="none")&&(r=!0);return s(),n},DM=(e,t,n,i)=>{const r=[];for(const a of e){const s=t(a,i),u=Array.isArray(s)?s:[s],l={input:a,outputs:u};r.push(l)}const o=$k(r);return o.map((a,s)=>{const u=s===o.length-1,l=Tk(a.outputs),c=typeof l.content=="object"&&l.content.some(g=>g.type==="tool-call"&&g.result===void 0),d=typeof l.content=="object"&&l.content.some(g=>g.type==="tool-call"&&g.result===void 0),f=Vo(u,n,c,d,u?i.error:void 0),p=kr(l,s.toString(),f);return p[St]=a.inputs,p})},UM=({callback:e,messages:t,isRunning:n,joinStrategy:i,metadata:r})=>{const o=$.useMemo(()=>({metadata:r??{},callback:e,callbackCache:new WeakMap,chunkCache:new WeakMap,converterCache:new Tc}),[e,r]);return $.useMemo(()=>{const a=[];for(const l of t){let c=o.callbackCache.get(l);if(!c){const d=o.callback(l,o.metadata),f=Array.isArray(d)?d:[d];c={input:l,outputs:f},o.callbackCache.set(l,c)}a.push(c)}const s=$k(a,i).map(l=>{const c=l.outputs[0];if(!c)return l;const d=o.chunkCache.get(c);return d&&Rm(d.outputs,l.outputs)?d:(o.chunkCache.set(c,l),l)}),u=o.converterCache.convertMessages(s,(l,c,d)=>{const f=d===s.length-1,p=Tk(c.outputs),g=typeof p.content=="object"&&p.content.some(x=>x.type==="tool-call"&&x.result===void 0),m=typeof p.content=="object"&&p.content.some(x=>x.type==="tool-call"&&x.result===void 0),y=Vo(f,n,g,m,f?o.metadata.error:void 0);if(l&&(l.role!=="assistant"||!ak(l.status)||l.status===y)){const x=hr(l);if(Rm(x,c.inputs))return l}const v=kr(p,d.toString(),y);return v[St]=c.inputs,v});return u[St]=t,u},[o,t,n,i])},Rm=(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},Er=e=>{const[,t]=_.tapState(e.getState);return _.tapEffect(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},LM=_.resource(({runtime:e})=>{const t=Er(e),n=_.tapEvents();return _.tapEffect(()=>{const i=[],r=["switched-to","switched-away"];for(const o of r){const a=e.unstable_on(o,()=>{n.emit(`thread-list-item.${o}`,{threadId:e.getState().id})});i.push(a)}return()=>{for(const o of i)o()}},[e,n]),_.tapApi({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})}),Qi=e=>{const t=_.tapMemo(()=>Object.fromEntries(e),[e]),n=_.tapResources(t,o=>o,[]),i=_.tapMemo(()=>Object.keys(n),[n]);return{state:_.tapMemo(()=>{const o=new Array(i.length);for(let a=0;a<i.length;a++)o[a]=n[i[a]].state;return o},[i,n]),api:o=>{const a="index"in o?n[i[o.index]]?.api:n[o.key]?.api;if(!a)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(o)}`);return a}}},Ck=_.resource(({runtime:e})=>{const t=Er(e);return _.tapApi({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),FM=_.resource(({runtime:e,index:t})=>{const n=_.tapMemo(()=>e.getAttachmentByIndex(t),[e,t]);return _.tapInlineResource(Ck({runtime:n}))}),Ak=_.resource(({threadIdRef:e,messageIdRef:t,runtime:n})=>{const i=Er(n),r=_.tapEvents();_.tapEffect(()=>{const s=[],u=["send","attachment-add"];for(const l of u){const c=n.unstable_on(l,()=>{r.emit(`composer.${l}`,{threadId:e.current,...t&&{messageId:t.current}})});s.push(c)}return()=>{for(const l of s)l()}},[n,r,e,t]);const o=Qi(i.attachments.map((s,u)=>[s.id,FM({runtime:n,index:u})])),a=_.tapMemo(()=>({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 _.tapApi({getState:()=>a,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:s=>"id"in s?o.api({key:s.id}):o.api(s),__internal_getRuntime:()=>n})}),BM=_.resource(({runtime:e})=>{const t=Er(e),n={getState:()=>t,addToolResult:i=>e.addToolResult(i),resumeToolCall:i=>e.resumeToolCall(i),__internal_getRuntime:()=>e};return _.tapApi(n,{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),ZM=_.resource(({runtime:e,index:t})=>{const n=_.tapMemo(()=>e.getAttachmentByIndex(t),[e,t]);return _.tapInlineResource(Ck({runtime:n}))}),qM=_.resource(({runtime:e,index:t})=>{const n=_.tapMemo(()=>e.getMessagePartByIndex(t),[e,t]);return _.tapInlineResource(BM({runtime:n}))}),VM=_.resource(({runtime:e,threadIdRef:t})=>{const n=Er(e),[i,r]=_.tapState(!1),[o,a]=_.tapState(!1),s=_.tapMemo(()=>({get current(){return e.getState().id}}),[e]),u=_.tapInlineResource(Ak({runtime:e.composer,threadIdRef:t,messageIdRef:s})),l=Qi(n.content.map((f,p)=>["toolCallId"in f&&f.toolCallId!=null?`toolCallId-${f.toolCallId}`:`index-${p}`,qM({runtime:e,index:p})])),c=Qi(n.attachments?.map((f,p)=>[f.id,ZM({runtime:e,index:p})])??[]),d=_.tapMemo(()=>({...n,parts:l.state,composer:u.state,isCopied:i,isHovering:o}),[n,l.state,u.state,i,o]);return _.tapApi({getState:()=>d,composer:u.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?l.api({index:f.index}):l.api({key:`toolCallId-${f.toolCallId}`}),attachment:f=>"id"in f?c.api({key:f.id}):c.api(f),setIsCopied:r,setIsHovering:a,__internal_getRuntime:()=>e},{key:n.id})}),HM=_.resource(({runtime:e,id:t,threadIdRef:n})=>{const i=_.tapMemo(()=>e.getMessageById(t),[e,t]);return _.tapInlineResource(VM({runtime:i,threadIdRef:n}))}),JM=_.resource(({runtime:e})=>{const t=Er(e),n=_.tapEvents();_.tapEffect(()=>{const s=[],u=["run-start","run-end","initialize","model-context-update"];for(const l of u){const c=e.unstable_on(l,()=>{const d=e.getState()?.threadId||"unknown";n.emit(`thread.${l}`,{threadId:d})});s.push(c)}return()=>{for(const l of s)l()}},[e]);const i=_.tapMemo(()=>({get current(){return e.getState().threadId}}),[e]),r=_.tapInlineResource(Ak({runtime:e.composer,threadIdRef:i})),o=Qi(t.messages.map(s=>[s.id,HM({runtime:e,id:s.id,threadIdRef:i})])),a=_.tapMemo(()=>({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 _.tapApi({getState:()=>a,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:s=>"id"in s?o.api({key:s.id}):o.api(s),__internal_getRuntime:()=>e})}),WM=_.resource(({runtime:e,id:t})=>{const n=_.tapMemo(()=>e.getItemById(t),[e,t]);return _.tapInlineResource(LM({runtime:n}))}),GM=_.resource(({runtime:e,__internal_assistantRuntime:t})=>{const n=Er(e),i=_.tapInlineResource(JM({runtime:e.main})),r=Qi(Object.keys(n.threadItems).map(a=>[a,WM({runtime:e,id:a})])),o=_.tapMemo(()=>({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 _.tapApi({getState:()=>o,thread:()=>i.api,item:a=>{if(a==="main")return r.api({key:o.mainThreadId});if("id"in a)return r.api({key:a.id});const{index:s,archived:u=!1}=a,l=u?o.archivedThreadIds[s]:o.threadIds[s];return r.api({key:l})},switchToThread:a=>{e.switchToThread(a)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),KM=_.resource(e=>{const t=_.tapModelContext();return _.tapEffect(()=>e.registerModelContextProvider(t),[e,t]),_.tapInlineResource(GM({runtime:e.threads,__internal_assistantRuntime:e}))}),mu=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()}}}}},YM=(e={})=>{const t=new Set,n=mu(a=>{o.setState({height:{...o.getState().height,viewport:a}})}),i=mu(a=>{o.setState({height:{...o.getState().height,inset:a}})}),r=mu(a=>{o.setState({height:{...o.getState().height,userMessage:a}})}),o=Wr.create(()=>({isAtBottom:!0,scrollToBottom:({behavior:a="auto"}={})=>{for(const s of t)s({behavior:a})},onScrollToBottom:a=>(t.add(a),()=>{t.delete(a)}),turnAnchor:e.turnAnchor??"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:i.register,registerUserMessageHeight:r.register}));return o},Xi=e=>e,QM=e=>{const t=Ml({optional:!0}),[n]=$.useState(()=>YM(e));return $.useEffect(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),$.useEffect(()=>{if(t)return n.subscribe(i=>{t.getState().isAtBottom!==i.isAtBottom&&Xi(t).setState({isAtBottom:i.isAtBottom})})},[n,t]),$.useEffect(()=>{const i={turnAnchor:e.turnAnchor??"bottom"};n.getState().turnAnchor!==i.turnAnchor&&Xi(n).setState(i)},[n,e.turnAnchor]),n},Pk=({children:e,options:t={}})=>{const n=QM(t),[i]=$.useState(()=>({useThreadViewport:n}));return h.jsx(Ek.Provider,{value:i,children:e})},XM=e=>e._core?.RenderComponent,ez=({children:e,runtime:t})=>{const n=_.useAssistantApi({threads:KM(t)}),i=XM(t);return h.jsxs(_.AssistantProvider,{api:n,children:[i&&h.jsx(i,{}),h.jsx(Pk,{children:e})]})},tz=$.memo(ez),nz=({id:e,children:t})=>{const n=_.useAssistantApi(),i=_.useExtendedAssistantApi({threadListItem:_.DerivedScope({source:"threads",query:{type:"id",id:e},get:()=>n.threads().item({id:e})}),on(r,o){const a=()=>n.threads().item({id:e}),{event:s,scope:u}=_.normalizeEventSelector(r);return _.checkEventScope("thread-list-item",u)?n.on({scope:"*",event:s},l=>{l.threadId===a().getState().id&&o(l)}):n.on(r,o)}});return h.jsx(_.AssistantProvider,{api:i,children:t})},rz=({index:e,children:t})=>{const n=_.useAssistantApi(),i=_.useExtendedAssistantApi({message:_.DerivedScope({source:"thread",query:{type:"index",index:e},get:()=>n.thread().message({index:e})}),composer:_.DerivedScope({source:"message",query:{},get:()=>n.thread().message({index:e}).composer}),on(r,o){const a=()=>n.thread().message({index:e}),{event:s,scope:u}=_.normalizeEventSelector(r);return!_.checkEventScope("composer",u)&&!_.checkEventScope("message",u)?n.on(r,o):n.on({scope:"thread",event:s},l=>{l.messageId===a().getState().id&&o(l)})}});return h.jsx(_.AssistantProvider,{api:i,children:t})},iz=({index:e,children:t})=>{const n=_.useAssistantApi(),i=_.useExtendedAssistantApi({part:_.DerivedScope({source:"message",query:{type:"index",index:e},get:()=>n.message().part({index:e})})});return h.jsx(_.AssistantProvider,{api:i,children:t})},oz=({index:e,children:t})=>{const n=_.useAssistantApi(),i=_.useExtendedAssistantApi({attachment:_.DerivedScope({source:"message",query:{type:"index",index:e},get:()=>n.message().attachment({index:e})})});return h.jsx(_.AssistantProvider,{api:i,children:t})},az=({index:e,children:t})=>{const n=_.useAssistantApi(),i=_.useExtendedAssistantApi({attachment:_.DerivedScope({source:"composer",query:{type:"index",index:e},get:()=>n.composer().attachment({index:e})})});return h.jsx(_.AssistantProvider,{api:i,children:t})},sz=_.resource(({text:e,isRunning:t})=>{const n=_.tapMemo(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return _.tapApi({getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),lz=({text:e,isRunning:t=!1,children:n})=>{const i=_.useResource(_.asStore(sz({text:e,isRunning:t}))),r=_.useExtendedAssistantApi({part:_.DerivedScope({source:"root",query:{},get:()=>i.getState().api}),subscribe:i.subscribe});return h.jsx(_.AssistantProvider,{api:r,children:n})},uz=e=>{const t={useThreadMessages:({messages:n,isRunning:i,joinStrategy:r,metadata:o})=>UM({callback:e,messages:n,isRunning:i,joinStrategy:r,metadata:o}),toThreadMessages:(n,i=!1,r={})=>DM(n,e,i,r),toOriginalMessages:n=>{const i=hr(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=_.useAssistantApi(),i=_.useAssistantState(a=>{if(n.part.source)return hr(a.part)}),r=_.useAssistantState(({message:a})=>hr(a)),o=i??r;if(o.length===0)throw new Error("No original messages found");return o}};return t},Om=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),a=JSON.parse(r).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}};class Rk{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=Om(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=Om(r)}}class cz{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 ya="aui:refresh_token";class dz{strategy="anon";baseUrl;jwtStrategy;constructor(t){this.baseUrl=t,this.jwtStrategy=new Rk(async()=>{const n=Date.now(),i=localStorage.getItem(ya),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(ya,JSON.stringify(p)),f}}else localStorage.removeItem(ya);const o=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!o.ok)return null;const a=await o.json(),{access_token:s,refresh_token:u}=a;return!s||!u?null:(localStorage.setItem(ya,JSON.stringify(u)),s)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(t){this.jwtStrategy.readAuthHeaders(t)}}class pz extends Error{constructor(t){super(t),this.name="APIError"}}class fz{_auth;_baseUrl;constructor(t){if("authToken"in t)this._baseUrl=t.baseUrl,this._auth=new Rk(t.authToken);else if("apiKey"in t)this._baseUrl="https://backend.assistant-api.com",this._auth=new cz(t.apiKey,t.userId,t.workspaceId);else if("anonymous"in t)this._baseUrl=t.baseUrl,this._auth=new dz(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[u,l]of Object.entries(n.query))l!==!1&&(l===!0?o.set(u,"true"):o.set(u,l.toString()));const a=new URL(`${this._baseUrl}/v1${t}`);a.search=o.toString();const s=await fetch(a,{method:n.method??"GET",headers:r,body:n.body?JSON.stringify(n.body):null});if(this._auth.readAuthHeaders(s.headers),!s.ok){const u=await s.text();try{const l=JSON.parse(u);throw new pz(l.message)}catch{throw new Error(`Request failed with status ${s.status}, ${u}`)}}return s}async makeRequest(t,n={}){return(await this.makeRawRequest(t,n)).json()}}class hz{cloud;constructor(t){this.cloud=t}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}}class mz{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 kc.fromResponse(n,new tM)}}class gz{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 vz{cloud;messages;constructor(t){this.cloud=t,this.messages=new gz(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 yz{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 bz{threads;auth;runs;files;constructor(t){const n=new fz(t);this.threads=new vz(n),this.auth={tokens:new hz(n)},this.runs=new mz(n),this.files=new yz(n)}}function $c(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=>$c(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,i])=>typeof n=="string"&&$c(i,t+1)):!1}const _z=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 $c(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}),wz=e=>{const t=e.content,n=kr({id:e.id,createdAt:e.created_at,...t},e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},gu=new WeakMap;class xz{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 Sz{cloudRef;store;constructor(t,n){this.cloudRef=t,this.store=n}get _getIdForLocalId(){return gu.has(this.store.threadListItem())||gu.set(this.store.threadListItem(),{}),gu.get(this.store.threadListItem())}withFormat(t){return new xz(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:_z(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(wz).reverse()}}async _appendWithFormat(t,n,i,r){const{remoteId:o}=await this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(o,{parent_id:t?await this._getIdForLocalId[t]??t:null,format:i,content:r}).then(({message_id:s})=>(this._getIdForLocalId[n]=s,s));return this._getIdForLocalId[n]=a,a.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 Iz=e=>{const t=_.useAssistantApi(),[n]=$.useState(()=>new Sz(e,t));return n},Nm=typeof process<"u"&&process?.env?.NEXT_PUBLIC_ASSISTANT_BASE_URL,vu=Nm?new bz({baseUrl:Nm,anonymous:!0}):void 0,kz=e=>{const t=$.useRef(e);$.useEffect(()=>{t.current=e},[e]);const n=$.useCallback(function({children:o}){const a=Iz({get current(){return t.current.cloud??vu}}),s=t.current.cloud??vu,u=$.useMemo(()=>new wM(s),[s]),l=$.useMemo(()=>({history:a,attachments:u}),[a,u]);return h.jsx(wk,{adapters:l,children:o})},[]),i=e.cloud??vu;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()),a=o?o.externalId:void 0,{thread_id:s}=await i.threads.create({last_message_at:new Date,external_id:a});return{externalId:a,remoteId:s}},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 OM};class hf{_core;threads;get threadList(){return this.threads}_thread;constructor(t){this._core=t,this.threads=new bM(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(cf.fromArray(t??[]))}}const Ez=e=>{const{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o,...a}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o},otherOptions:a}};function Et(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>(...n)=>t.current?.(...n),[])}const Ok=$.createContext(null),Tz=e=>({useSmoothStatus:Wr.create(()=>e)}),$z=({children:e})=>{const t=Nk({optional:!0}),n=_.useAssistantApi(),[i]=$.useState(()=>Tz(n.part().getState().status));return t?e:h.jsx(Ok.Provider,{value:i,children:e})},Cz=e=>{const t=$.forwardRef((n,i)=>h.jsx($z,{children:h.jsx(e,{...n,ref:i})}));return t.displayName=e.displayName,t};function Nk(e){const t=$.useContext(Ok);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:Az,useSmoothStatusStore:Pz}=kk(Nk,"useSmoothStatus");class Rz{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 a=0;for(;i>=o&&a<r;)a++,i-=o;a!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=t-i,this.setText(this.currentText))}}const yu=Object.freeze({type:"running"}),jk=(e,t=!1)=>{const{text:n}=e,i=_.useAssistantState(({message:c})=>c.id),r=$.useRef(i),[o,a]=$.useState(n),s=Pz({optional:!0}),u=Et(c=>{if(a(c),s){const d=o!==c||e.status.type==="running"?yu:e.status;Xi(s).setState(d,!0)}});$.useEffect(()=>{if(s){const c=t&&(o!==n||e.status.type==="running")?yu:e.status;Xi(s).setState(c,!0)}},[s,t,n,o,e.status]);const[l]=$.useState(new Rz(n,u));return $.useEffect(()=>{if(!t){l.stop();return}if(r.current!==i||!n.startsWith(l.targetText)){r.current=i,u(n),l.currentText=n,l.targetText=n,l.stop();return}l.targetText=n,l.start()},[u,l,i,t,n]),$.useEffect(()=>()=>{l.stop()},[l]),$.useMemo(()=>t?{type:"text",text:o,status:n===o?e.status:yu}:e,[t,o,e,n])},Mk=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:hf,BaseAssistantRuntimeCore:sf,CompositeContextProvider:_.CompositeContextProvider,DefaultThreadComposerRuntimeCore:ik,MessageRepository:df,ThreadRuntimeImpl:_k,fromThreadMessageLike:kr,generateId:qo,getAutoStatus:Vo,splitLocalRuntimeOptions:Ez,useSmooth:jk,useSmoothStatus:Az,useToolInvocations:Ik,withSmoothContextProvider:Cz},Symbol.toStringTag,{value:"Module"}));class Oz extends Ol{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=Wr.create(()=>({}));constructor(t){super(),this.useRuntimeHook=Wr.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 a=this.instances.get(t);if(!a)o(),i(new Error("Thread was deleted before runtime was started"));else if(a.runtime)o(),n(a.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=$.useCallback(()=>{const u=this.instances.get(t);if(!u)throw new Error("Thread not found. This is a bug in assistant-ui.");u.runtime=r.getState(),this._notifySubscribers()},[t,r]),a=$.useRef(!1);a.current||o(),$.useEffect(()=>(a.current=!0,o(),r.outerSubscribe(o)),[r,o]);const s=_.useAssistantApi();return $.useEffect(()=>i.threads.main.unstable_on("initialize",()=>{if(s.threadListItem().getState().status==="new"){s.threadListItem().initialize();const l=i.thread.unstable_on("run-end",()=>{l(),s.threadListItem().generateTitle()})}}),[i,s]),null};_OuterActiveThreadProvider=$.memo(({threadId:t,provider:n})=>h.jsx(nz,{id:t,children:h.jsx(n,{children:h.jsx(this._InnerActiveThreadProvider,{threadId:t})})}));__internal_RenderThreadRuntimes=({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(n=>h.jsx(this._OuterActiveThreadProvider,{threadId:n,provider:t},n)))}const Ze=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."),Nz={getMessageById(){},getBranches(){return[]},switchToBranch(){throw Ze},append(){throw Ze},startRun(){throw Ze},resumeRun(){throw Ze},cancelRun(){throw Ze},addToolResult(){throw Ze},resumeToolCall(){throw Ze},speak(){throw Ze},stopSpeaking(){throw Ze},submitFeedback(){throw Ze},getModelContext(){return{}},unstable_loadExternalState(){throw Ze},composer:{attachments:[],attachmentAccept:"*",async addAttachment(){throw Ze},async removeAttachment(){throw Ze},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw Ze},role:"user",setRole(){throw Ze},runConfig:{},setRunConfig(){throw Ze},async reset(){},async clearAttachments(){},send(){throw Ze},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw Ze},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 Ze},export(){return{messages:[]}},reset(){throw Ze},unstable_on(){return()=>{}}},jm=(e,t,n)=>n.reduce((i,r)=>r?.(i,t)??i,e);class jz extends Ol{_pendingTransforms=[];_baseValue;_cachedValue;constructor(t){super(),this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,n)=>jm(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=jm(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 za=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},ba=(e,t,n)=>{const i=za(e,t);if(!i)return e;const{id:r,remoteId:o,status:a}=i;if(a===n)return e;const s={...e};switch(a){case"new":s.newThreadId=void 0;break;case"regular":s.threadIds=s.threadIds.filter(u=>u!==r);break;case"archived":s.archivedThreadIds=s.archivedThreadIds.filter(u=>u!==r);break;default:{const u=a;throw new Error(`Unsupported state: ${u}`)}}switch(n){case"regular":s.threadIds=[r,...s.threadIds];break;case"archived":s.archivedThreadIds=[r,...s.archivedThreadIds];break;case"deleted":s.threadData=Object.fromEntries(Object.entries(s.threadData).filter(([u])=>u!==r)),s.threadIdMap=Object.fromEntries(Object.entries(s.threadIdMap).filter(([u])=>u!==r&&u!==o));break;default:{const u=n;throw new Error(`Unsupported state: ${u}`)}}return n!=="deleted"&&(s.threadData={...s.threadData,[r]:{...i,status:n}}),s};class Mz extends Ol{contextProvider;_options;_hookManager;_loadThreadsPromise;_mainThreadId;_state=new jz({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={},a={};for(const s of n.threads){switch(s.status){case"regular":i.push(s.remoteId);break;case"archived":r.push(s.remoteId);break;default:{const l=s.status;throw new Error(`Unsupported state: ${l}`)}}const u=s.remoteId;o[s.remoteId]=u,a[u]={id:s.remoteId,remoteId:s.remoteId,externalId:s.externalId,status:s.status,title:s.title,initializeTask:Promise.resolve({remoteId:s.remoteId,externalId:s.externalId})}}return{...t,threadIds:i,archivedThreadIds:r,threadIdMap:{...t.threadIdMap,...o},threadData:{...t.threadData,...a}}}}).then(()=>{})),this._loadThreadsPromise}constructor(t,n){super(),this.contextProvider=n,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Oz(t.runtimeHook),this.useProvider=Wr.create(()=>({Provider:t.adapter.unstable_Provider??$.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??$.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||Nz}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 za(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,a=r.remoteId,s={...o.threadData,[a]:{id:a,initializeTask:Promise.resolve({remoteId:r.remoteId,externalId:r.externalId}),remoteId:r.remoteId,externalId:r.externalId,status:r.status,title:r.title}},u={...o.threadIdMap,[r.remoteId]:a},l=r.status==="regular"?[...o.threadIds,r.remoteId]:o.threadIds,c=r.status==="archived"?[...o.archivedThreadIds,r.remoteId]:o.archivedThreadIds;this._state.update({...o,threadIds:l,archivedThreadIds:c,threadIdMap:u,threadData:s}),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_${qo()}`;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=>ba(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=za(n,t);if(!o)return n;const a=t;return{...n,threadIdMap:{...n.threadIdMap,[i]:a},threadData:{...n.threadData,[a]:{...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,a=await this._options.adapter.generateTitle(i,o),s=Mi.fromAssistantStream(a);for await(const u of s){const l=u.parts.filter(d=>d.type==="text")[0]?.text,c=this._state.baseValue;this._state.update({...c,threadData:{...c.threadData,[n.id]:{...n,title:l}}})}};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=za(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=>ba(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=>ba(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=>ba(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=Wr.create(()=>[]);__internal_RenderComponent=()=>{const t=$.useId();$.useEffect(()=>(this.useBoundIds.setState(o=>[...o,t],!0),()=>{this.useBoundIds.setState(o=>o.filter(a=>a!==t),!0)}),[t]);const n=this.useBoundIds(),{Provider:i}=this.useProvider(),r={modelContext:this.contextProvider};return(n.length===0||n[0]===t)&&h.jsx(wk,{adapters:r,children:h.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:i})})}}class zz extends sf{threads;constructor(t){super(),this.threads=new Mz(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}}const Dz=e=>{const[t]=$.useState(()=>new zz(e));return $.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),$.useMemo(()=>new hf(t),[t])},Uz=e=>{if(_.useAssistantApiImpl().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 Dz(e)};var Lz=Symbol.for("react.lazy"),fs=w[" use ".trim().toString()];function Fz(e){return typeof e=="object"&&e!==null&&"then"in e}function zk(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Lz&&"_payload"in e&&Fz(e._payload)}function Dk(e){const t=Bz(e),n=w.forwardRef((i,r)=>{let{children:o,...a}=i;zk(o)&&typeof fs=="function"&&(o=fs(o._payload));const s=w.Children.toArray(o),u=s.find(Vz);if(u){const l=u.props.children,c=s.map(d=>d===u?w.Children.count(l)>1?w.Children.only(null):w.isValidElement(l)?l.props.children:null:d);return h.jsx(t,{...a,ref:r,children:w.isValidElement(l)?w.cloneElement(l,void 0,c):null})}return h.jsx(t,{...a,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}var mf=Dk("Slot");function Bz(e){const t=w.forwardRef((n,i)=>{let{children:r,...o}=n;if(zk(r)&&typeof fs=="function"&&(r=fs(r._payload)),w.isValidElement(r)){const a=Jz(r),s=Hz(o,r.props);return r.type!==w.Fragment&&(s.ref=i?ff(i,a):a),w.cloneElement(r,s)}return w.Children.count(r)>1?w.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Uk=Symbol("radix.slottable");function Zz(e){const t=({children:n})=>h.jsx(h.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Uk,t}var qz=Zz("Slottable");function Vz(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Uk}function Hz(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]=(...s)=>{const u=o(...s);return r(...s),u}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function Jz(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 Wz=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ct=Wz.reduce((e,t)=>{const n=Dk(`Primitive.${t}`),i=w.forwardRef((r,o)=>{const{asChild:a,...s}=r,u=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(u,{...s,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{}),Tn;(function(e){e.Hidden="hidden",e.Floating="floating",e.Normal="normal"})(Tn||(Tn={}));const Gz=({hideWhenRunning:e,autohide:t,autohideFloat:n})=>_.useAssistantState(({thread:i,message:r})=>e&&i.isRunning?Tn.Hidden:t==="always"||t==="not-last"&&!r.isLast?r.isHovering?n==="always"||n==="single-branch"&&r.branchCount<=1?Tn.Floating:Tn.Normal:Tn.Hidden:Tn.Normal),gf=$.forwardRef(({hideWhenRunning:e,autohide:t,autohideFloat:n,...i},r)=>{const o=Gz({hideWhenRunning:e,autohide:t,autohideFloat:n});return o===Tn.Hidden?null:h.jsx(ct.div,{...o===Tn.Floating?{"data-floating":"true"}:null,...i,ref:r})});gf.displayName="ActionBarPrimitive.Root";function Re(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}const Kz=({copiedDuration:e=3e3}={})=>{const t=_.useAssistantApi(),n=_.useAssistantState(({message:a})=>(a.role!=="assistant"||a.status?.type!=="running")&&a.parts.some(s=>s.type==="text"&&s.text.length>0)),i=_.useAssistantState(({composer:a})=>a.isEditing),r=_.useAssistantState(({composer:a})=>a.text),o=$.useCallback(()=>{const a=i?r:t.message().getCopyText();a&&navigator.clipboard.writeText(a).then(()=>{t.message().setIsCopied(!0),setTimeout(()=>t.message().setIsCopied(!1),e)})},[t,i,r,e]);return n?o:null},Lk=$.forwardRef(({copiedDuration:e,onClick:t,disabled:n,...i},r)=>{const o=_.useAssistantState(({message:s})=>s.isCopied),a=Kz({copiedDuration:e});return h.jsx(ct.button,{type:"button",...o?{"data-copied":"true"}:{},...i,ref:r,disabled:n||!a,onClick:Re(t,()=>{a?.()})})});Lk.displayName="ActionBarPrimitive.Copy";const _n=(e,t,n=[])=>{const i=$.forwardRef((r,o)=>{const a={},s={};Object.keys(r).forEach(l=>{n.includes(l)?a[l]=r[l]:s[l]=r[l]});const u=t(a)??void 0;return h.jsx(ct.button,{type:"button",...s,ref:o,disabled:s.disabled||!u,onClick:Re(s.onClick,u)})});return i.displayName=e,i},Yz=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(i=>i.thread.isRunning||i.thread.isDisabled||i.message.role!=="assistant"),n=$.useCallback(()=>{e.message().reload()},[e]);return t?null:n},Qz=_n("ActionBarPrimitive.Reload",Yz),Xz=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(({composer:i})=>i.isEditing),n=$.useCallback(()=>{e.composer().beginEdit()},[e]);return t?null:n},eD=_n("ActionBarPrimitive.Edit",Xz);function Fk(e,t=globalThis?.document){const n=Et(e);w.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 tD(e,t){const n=w.createContext(t),i=o=>{const{children:a,...s}=o,u=w.useMemo(()=>s,Object.values(s));return h.jsx(n.Provider,{value:u,children:a})};i.displayName=e+"Provider";function r(o){const a=w.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[i,r]}function Wo(e,t=[]){let n=[];function i(o,a){const s=w.createContext(a),u=n.length;n=[...n,a];const l=d=>{const{scope:f,children:p,...g}=d,m=f?.[e]?.[u]||s,y=w.useMemo(()=>g,Object.values(g));return h.jsx(m.Provider,{value:y,children:p})};l.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[u]||s,g=w.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[l,c]}const r=()=>{const o=n.map(a=>w.createContext(a));return function(s){const u=s?.[e]||o;return w.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return r.scopeName=e,[i,nD(r,...t)]}function nD(...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 a=i.reduce((s,{useScope:u,scopeName:l})=>{const d=u(o)[`__scope${l}`];return{...s,...d}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function vf(e){const t=rD(e),n=w.forwardRef((i,r)=>{const{children:o,...a}=i,s=w.Children.toArray(o),u=s.find(oD);if(u){const l=u.props.children,c=s.map(d=>d===u?w.Children.count(l)>1?w.Children.only(null):w.isValidElement(l)?l.props.children:null:d);return h.jsx(t,{...a,ref:r,children:w.isValidElement(l)?w.cloneElement(l,void 0,c):null})}return h.jsx(t,{...a,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}function rD(e){const t=w.forwardRef((n,i)=>{const{children:r,...o}=n;if(w.isValidElement(r)){const a=sD(r),s=aD(o,r.props);return r.type!==w.Fragment&&(s.ref=i?ff(i,a):a),w.cloneElement(r,s)}return w.Children.count(r)>1?w.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Bk=Symbol("radix.slottable");function iD(e){const t=({children:n})=>h.jsx(h.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Bk,t}function oD(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Bk}function aD(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]=(...s)=>{const u=o(...s);return r(...s),u}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function sD(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 lD=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],We=lD.reduce((e,t)=>{const n=vf(`Primitive.${t}`),i=w.forwardRef((r,o)=>{const{asChild:a,...s}=r,u=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(u,{...s,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{});function uD(e,t){e&&yy.flushSync(()=>e.dispatchEvent(t))}var cD="DismissableLayer",Cc="dismissableLayer.update",dD="dismissableLayer.pointerDownOutside",pD="dismissableLayer.focusOutside",Mm,Zk=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),zl=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:o,onInteractOutside:a,onDismiss:s,...u}=e,l=w.useContext(Zk),[c,d]=w.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=w.useState({}),g=Ge(t,C=>d(C)),m=Array.from(l.layers),[y]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=m.indexOf(y),x=c?m.indexOf(c):-1,S=l.layersWithOutsidePointerEventsDisabled.size>0,b=x>=v,A=mD(C=>{const P=C.target,j=[...l.branches].some(F=>F.contains(P));!b||j||(r?.(C),a?.(C),C.defaultPrevented||s?.())},f),E=gD(C=>{const P=C.target;[...l.branches].some(F=>F.contains(P))||(o?.(C),a?.(C),C.defaultPrevented||s?.())},f);return Fk(C=>{x===l.layers.size-1&&(i?.(C),!C.defaultPrevented&&s&&(C.preventDefault(),s()))},f),w.useEffect(()=>{if(c)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Mm=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),zm(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=Mm)}},[c,f,n,l]),w.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),zm())},[c,l]),w.useEffect(()=>{const C=()=>p({});return document.addEventListener(Cc,C),()=>document.removeEventListener(Cc,C)},[]),h.jsx(We.div,{...u,ref:g,style:{pointerEvents:S?b?"auto":"none":void 0,...e.style},onFocusCapture:Re(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Re(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Re(e.onPointerDownCapture,A.onPointerDownCapture)})});zl.displayName=cD;var fD="DismissableLayerBranch",hD=w.forwardRef((e,t)=>{const n=w.useContext(Zk),i=w.useRef(null),r=Ge(t,i);return w.useEffect(()=>{const o=i.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),h.jsx(We.div,{...e,ref:r})});hD.displayName=fD;function mD(e,t=globalThis?.document){const n=Et(e),i=w.useRef(!1),r=w.useRef(()=>{});return w.useEffect(()=>{const o=s=>{if(s.target&&!i.current){let u=function(){qk(dD,n,l,{discrete:!0})};const l={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=u,t.addEventListener("click",r.current,{once:!0})):u()}else t.removeEventListener("click",r.current);i.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>i.current=!0}}function gD(e,t=globalThis?.document){const n=Et(e),i=w.useRef(!1);return w.useEffect(()=>{const r=o=>{o.target&&!i.current&&qk(pD,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 zm(){const e=new CustomEvent(Cc);document.dispatchEvent(e)}function qk(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?uD(r,o):r.dispatchEvent(o)}var bu=0;function Vk(){w.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Dm()),document.body.insertAdjacentElement("beforeend",e[1]??Dm()),bu++,()=>{bu===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bu--}},[])}function Dm(){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 _u="focusScope.autoFocusOnMount",wu="focusScope.autoFocusOnUnmount",Um={bubbles:!1,cancelable:!0},vD="FocusScope",yf=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:o,...a}=e,[s,u]=w.useState(null),l=Et(r),c=Et(o),d=w.useRef(null),f=Ge(t,m=>u(m)),p=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(i){let m=function(S){if(p.paused||!s)return;const b=S.target;s.contains(b)?d.current=b:Bn(d.current,{select:!0})},y=function(S){if(p.paused||!s)return;const b=S.relatedTarget;b!==null&&(s.contains(b)||Bn(d.current,{select:!0}))},v=function(S){if(document.activeElement===document.body)for(const A of S)A.removedNodes.length>0&&Bn(s)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const x=new MutationObserver(v);return s&&x.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),x.disconnect()}}},[i,s,p.paused]),w.useEffect(()=>{if(s){Fm.add(p);const m=document.activeElement;if(!s.contains(m)){const v=new CustomEvent(_u,Um);s.addEventListener(_u,l),s.dispatchEvent(v),v.defaultPrevented||(yD(SD(Hk(s)),{select:!0}),document.activeElement===m&&Bn(s))}return()=>{s.removeEventListener(_u,l),setTimeout(()=>{const v=new CustomEvent(wu,Um);s.addEventListener(wu,c),s.dispatchEvent(v),v.defaultPrevented||Bn(m??document.body,{select:!0}),s.removeEventListener(wu,c),Fm.remove(p)},0)}}},[s,l,c,p]);const g=w.useCallback(m=>{if(!n&&!i||p.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,v=document.activeElement;if(y&&v){const x=m.currentTarget,[S,b]=bD(x);S&&b?!m.shiftKey&&v===b?(m.preventDefault(),n&&Bn(S,{select:!0})):m.shiftKey&&v===S&&(m.preventDefault(),n&&Bn(b,{select:!0})):v===x&&m.preventDefault()}},[n,i,p.paused]);return h.jsx(We.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});yf.displayName=vD;function yD(e,{select:t=!1}={}){const n=document.activeElement;for(const i of e)if(Bn(i,{select:t}),document.activeElement!==n)return}function bD(e){const t=Hk(e),n=Lm(t,e),i=Lm(t.reverse(),e);return[n,i]}function Hk(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 Lm(e,t){for(const n of e)if(!_D(n,{upTo:t}))return n}function _D(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 wD(e){return e instanceof HTMLInputElement&&"select"in e}function Bn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&wD(e)&&t&&e.select()}}var Fm=xD();function xD(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Bm(e,t),e.unshift(t)},remove(t){e=Bm(e,t),e[0]?.resume()}}}function Bm(e,t){const n=[...e],i=n.indexOf(t);return i!==-1&&n.splice(i,1),n}function SD(e){return e.filter(t=>t.tagName!=="A")}var Lt=globalThis?.document?w.useLayoutEffect:()=>{},ID=w[" useId ".trim().toString()]||(()=>{}),kD=0;function Fr(e){const[t,n]=w.useState(ID());return Lt(()=>{n(i=>i??String(kD++))},[e]),t?`radix-${t}`:""}const ED=["top","right","bottom","left"],Qn=Math.min,wt=Math.max,hs=Math.round,_a=Math.floor,gn=e=>({x:e,y:e}),TD={left:"right",right:"left",bottom:"top",top:"bottom"},$D={start:"end",end:"start"};function Ac(e,t,n){return wt(e,Qn(t,n))}function Rn(e,t){return typeof e=="function"?e(t):e}function On(e){return e.split("-")[0]}function hi(e){return e.split("-")[1]}function bf(e){return e==="x"?"y":"x"}function _f(e){return e==="y"?"height":"width"}const CD=new Set(["top","bottom"]);function mn(e){return CD.has(On(e))?"y":"x"}function wf(e){return bf(mn(e))}function AD(e,t,n){n===void 0&&(n=!1);const i=hi(e),r=wf(e),o=_f(r);let a=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=ms(a)),[a,ms(a)]}function PD(e){const t=ms(e);return[Pc(e),t,Pc(t)]}function Pc(e){return e.replace(/start|end/g,t=>$D[t])}const Zm=["left","right"],qm=["right","left"],RD=["top","bottom"],OD=["bottom","top"];function ND(e,t,n){switch(e){case"top":case"bottom":return n?t?qm:Zm:t?Zm:qm;case"left":case"right":return t?RD:OD;default:return[]}}function jD(e,t,n,i){const r=hi(e);let o=ND(On(e),n==="start",i);return r&&(o=o.map(a=>a+"-"+r),t&&(o=o.concat(o.map(Pc)))),o}function ms(e){return e.replace(/left|right|bottom|top/g,t=>TD[t])}function MD(e){return{top:0,right:0,bottom:0,left:0,...e}}function Jk(e){return typeof e!="number"?MD(e):{top:e,right:e,bottom:e,left:e}}function gs(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 Vm(e,t,n){let{reference:i,floating:r}=e;const o=mn(t),a=wf(t),s=_f(a),u=On(t),l=o==="y",c=i.x+i.width/2-r.width/2,d=i.y+i.height/2-r.height/2,f=i[s]/2-r[s]/2;let p;switch(u){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(hi(t)){case"start":p[a]-=f*(n&&l?-1:1);break;case"end":p[a]+=f*(n&&l?-1:1);break}return p}const zD=async(e,t,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:o=[],platform:a}=n,s=o.filter(Boolean),u=await(a.isRTL==null?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:r}),{x:c,y:d}=Vm(l,i,u),f=i,p={},g=0;for(let m=0;m<s.length;m++){const{name:y,fn:v}=s[m],{x,y:S,data:b,reset:A}=await v({x:c,y:d,initialPlacement:i,placement:f,strategy:r,middlewareData:p,rects:l,platform:a,elements:{reference:e,floating:t}});c=x??c,d=S??d,p={...p,[y]:{...p[y],...b}},A&&g<=50&&(g++,typeof A=="object"&&(A.placement&&(f=A.placement),A.rects&&(l=A.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):A.rects),{x:c,y:d}=Vm(l,f,u)),m=-1)}return{x:c,y:d,placement:f,strategy:r,middlewareData:p}};async function eo(e,t){var n;t===void 0&&(t={});const{x:i,y:r,platform:o,rects:a,elements:s,strategy:u}=e,{boundary:l="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Rn(t,e),g=Jk(p),y=s[f?d==="floating"?"reference":"floating":d],v=gs(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(y)))==null||n?y:y.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(s.floating)),boundary:l,rootBoundary:c,strategy:u})),x=d==="floating"?{x:i,y:r,width:a.floating.width,height:a.floating.height}:a.reference,S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(s.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},A=gs(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:x,offsetParent:S,strategy:u}):x);return{top:(v.top-A.top+g.top)/b.y,bottom:(A.bottom-v.bottom+g.bottom)/b.y,left:(v.left-A.left+g.left)/b.x,right:(A.right-v.right+g.right)/b.x}}const DD=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:i,placement:r,rects:o,platform:a,elements:s,middlewareData:u}=t,{element:l,padding:c=0}=Rn(e,t)||{};if(l==null)return{};const d=Jk(c),f={x:n,y:i},p=wf(r),g=_f(p),m=await a.getDimensions(l),y=p==="y",v=y?"top":"left",x=y?"bottom":"right",S=y?"clientHeight":"clientWidth",b=o.reference[g]+o.reference[p]-f[p]-o.floating[g],A=f[p]-o.reference[p],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(l));let C=E?E[S]:0;(!C||!await(a.isElement==null?void 0:a.isElement(E)))&&(C=s.floating[S]||o.floating[g]);const P=b/2-A/2,j=C/2-m[g]/2-1,F=Qn(d[v],j),D=Qn(d[x],j),V=F,G=C-m[g]-D,z=C/2-m[g]/2+P,U=Ac(V,z,G),Q=!u.arrow&&hi(r)!=null&&z!==U&&o.reference[g]/2-(z<V?F:D)-m[g]/2<0,ie=Q?z<V?z-V:z-G:0;return{[p]:f[p]+ie,data:{[p]:U,centerOffset:z-U-ie,...Q&&{alignmentOffset:ie}},reset:Q}}}),UD=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:r,middlewareData:o,rects:a,initialPlacement:s,platform:u,elements:l}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=Rn(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const v=On(r),x=mn(s),S=On(s)===s,b=await(u.isRTL==null?void 0:u.isRTL(l.floating)),A=f||(S||!m?[ms(s)]:PD(s)),E=g!=="none";!f&&E&&A.push(...jD(s,m,g,b));const C=[s,...A],P=await eo(t,y),j=[];let F=((i=o.flip)==null?void 0:i.overflows)||[];if(c&&j.push(P[v]),d){const z=AD(r,a,b);j.push(P[z[0]],P[z[1]])}if(F=[...F,{placement:r,overflows:j}],!j.every(z=>z<=0)){var D,V;const z=(((D=o.flip)==null?void 0:D.index)||0)+1,U=C[z];if(U&&(!(d==="alignment"?x!==mn(U):!1)||F.every(X=>mn(X.placement)===x?X.overflows[0]>0:!0)))return{data:{index:z,overflows:F},reset:{placement:U}};let Q=(V=F.filter(ie=>ie.overflows[0]<=0).sort((ie,X)=>ie.overflows[1]-X.overflows[1])[0])==null?void 0:V.placement;if(!Q)switch(p){case"bestFit":{var G;const ie=(G=F.filter(X=>{if(E){const me=mn(X.placement);return me===x||me==="y"}return!0}).map(X=>[X.placement,X.overflows.filter(me=>me>0).reduce((me,I)=>me+I,0)]).sort((X,me)=>X[1]-me[1])[0])==null?void 0:G[0];ie&&(Q=ie);break}case"initialPlacement":Q=s;break}if(r!==Q)return{reset:{placement:Q}}}return{}}}};function Hm(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Jm(e){return ED.some(t=>e[t]>=0)}const LD=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:i="referenceHidden",...r}=Rn(e,t);switch(i){case"referenceHidden":{const o=await eo(t,{...r,elementContext:"reference"}),a=Hm(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:Jm(a)}}}case"escaped":{const o=await eo(t,{...r,altBoundary:!0}),a=Hm(o,n.floating);return{data:{escapedOffsets:a,escaped:Jm(a)}}}default:return{}}}}},Wk=new Set(["left","top"]);async function FD(e,t){const{placement:n,platform:i,elements:r}=e,o=await(i.isRTL==null?void 0:i.isRTL(r.floating)),a=On(n),s=hi(n),u=mn(n)==="y",l=Wk.has(a)?-1:1,c=o&&u?-1:1,d=Rn(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof g=="number"&&(p=s==="end"?g*-1:g),u?{x:p*c,y:f*l}:{x:f*l,y:p*c}}const BD=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:r,y:o,placement:a,middlewareData:s}=t,u=await FD(t,e);return a===((n=s.offset)==null?void 0:n.placement)&&(i=s.arrow)!=null&&i.alignmentOffset?{}:{x:r+u.x,y:o+u.y,data:{...u,placement:a}}}}},ZD=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:a=!1,limiter:s={fn:y=>{let{x:v,y:x}=y;return{x:v,y:x}}},...u}=Rn(e,t),l={x:n,y:i},c=await eo(t,u),d=mn(On(r)),f=bf(d);let p=l[f],g=l[d];if(o){const y=f==="y"?"top":"left",v=f==="y"?"bottom":"right",x=p+c[y],S=p-c[v];p=Ac(x,p,S)}if(a){const y=d==="y"?"top":"left",v=d==="y"?"bottom":"right",x=g+c[y],S=g-c[v];g=Ac(x,g,S)}const m=s.fn({...t,[f]:p,[d]:g});return{...m,data:{x:m.x-n,y:m.y-i,enabled:{[f]:o,[d]:a}}}}}},qD=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:i,placement:r,rects:o,middlewareData:a}=t,{offset:s=0,mainAxis:u=!0,crossAxis:l=!0}=Rn(e,t),c={x:n,y:i},d=mn(r),f=bf(d);let p=c[f],g=c[d];const m=Rn(s,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(u){const S=f==="y"?"height":"width",b=o.reference[f]-o.floating[S]+y.mainAxis,A=o.reference[f]+o.reference[S]-y.mainAxis;p<b?p=b:p>A&&(p=A)}if(l){var v,x;const S=f==="y"?"width":"height",b=Wk.has(On(r)),A=o.reference[d]-o.floating[S]+(b&&((v=a.offset)==null?void 0:v[d])||0)+(b?0:y.crossAxis),E=o.reference[d]+o.reference[S]+(b?0:((x=a.offset)==null?void 0:x[d])||0)-(b?y.crossAxis:0);g<A?g=A:g>E&&(g=E)}return{[f]:p,[d]:g}}}},VD=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,i;const{placement:r,rects:o,platform:a,elements:s}=t,{apply:u=()=>{},...l}=Rn(e,t),c=await eo(t,l),d=On(r),f=hi(r),p=mn(r)==="y",{width:g,height:m}=o.floating;let y,v;d==="top"||d==="bottom"?(y=d,v=f===(await(a.isRTL==null?void 0:a.isRTL(s.floating))?"start":"end")?"left":"right"):(v=d,y=f==="end"?"top":"bottom");const x=m-c.top-c.bottom,S=g-c.left-c.right,b=Qn(m-c[y],x),A=Qn(g-c[v],S),E=!t.middlewareData.shift;let C=b,P=A;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(P=S),(i=t.middlewareData.shift)!=null&&i.enabled.y&&(C=x),E&&!f){const F=wt(c.left,0),D=wt(c.right,0),V=wt(c.top,0),G=wt(c.bottom,0);p?P=g-2*(F!==0||D!==0?F+D:wt(c.left,c.right)):C=m-2*(V!==0||G!==0?V+G:wt(c.top,c.bottom))}await u({...t,availableWidth:P,availableHeight:C});const j=await a.getDimensions(s.floating);return g!==j.width||m!==j.height?{reset:{rects:!0}}:{}}}};function Dl(){return typeof window<"u"}function mi(e){return Gk(e)?(e.nodeName||"").toLowerCase():"#document"}function It(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function wn(e){var t;return(t=(Gk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Gk(e){return Dl()?e instanceof Node||e instanceof It(e).Node:!1}function rn(e){return Dl()?e instanceof Element||e instanceof It(e).Element:!1}function yn(e){return Dl()?e instanceof HTMLElement||e instanceof It(e).HTMLElement:!1}function Wm(e){return!Dl()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof It(e).ShadowRoot}const HD=new Set(["inline","contents"]);function Go(e){const{overflow:t,overflowX:n,overflowY:i,display:r}=on(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&!HD.has(r)}const JD=new Set(["table","td","th"]);function WD(e){return JD.has(mi(e))}const GD=[":popover-open",":modal"];function Ul(e){return GD.some(t=>{try{return e.matches(t)}catch{return!1}})}const KD=["transform","translate","scale","rotate","perspective"],YD=["transform","translate","scale","rotate","perspective","filter"],QD=["paint","layout","strict","content"];function xf(e){const t=Sf(),n=rn(e)?on(e):e;return KD.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)||YD.some(i=>(n.willChange||"").includes(i))||QD.some(i=>(n.contain||"").includes(i))}function XD(e){let t=Xn(e);for(;yn(t)&&!si(t);){if(xf(t))return t;if(Ul(t))return null;t=Xn(t)}return null}function Sf(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const e4=new Set(["html","body","#document"]);function si(e){return e4.has(mi(e))}function on(e){return It(e).getComputedStyle(e)}function Ll(e){return rn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xn(e){if(mi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Wm(e)&&e.host||wn(e);return Wm(t)?t.host:t}function Kk(e){const t=Xn(e);return si(t)?e.ownerDocument?e.ownerDocument.body:e.body:yn(t)&&Go(t)?t:Kk(t)}function to(e,t,n){var i;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=Kk(e),o=r===((i=e.ownerDocument)==null?void 0:i.body),a=It(r);if(o){const s=Rc(a);return t.concat(a,a.visualViewport||[],Go(r)?r:[],s&&n?to(s):[])}return t.concat(r,to(r,[],n))}function Rc(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Yk(e){const t=on(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const r=yn(e),o=r?e.offsetWidth:n,a=r?e.offsetHeight:i,s=hs(n)!==o||hs(i)!==a;return s&&(n=o,i=a),{width:n,height:i,$:s}}function If(e){return rn(e)?e:e.contextElement}function Br(e){const t=If(e);if(!yn(t))return gn(1);const n=t.getBoundingClientRect(),{width:i,height:r,$:o}=Yk(t);let a=(o?hs(n.width):n.width)/i,s=(o?hs(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!s||!Number.isFinite(s))&&(s=1),{x:a,y:s}}const t4=gn(0);function Qk(e){const t=It(e);return!Sf()||!t.visualViewport?t4:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function n4(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==It(e)?!1:t}function yr(e,t,n,i){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),o=If(e);let a=gn(1);t&&(i?rn(i)&&(a=Br(i)):a=Br(e));const s=n4(o,n,i)?Qk(o):gn(0);let u=(r.left+s.x)/a.x,l=(r.top+s.y)/a.y,c=r.width/a.x,d=r.height/a.y;if(o){const f=It(o),p=i&&rn(i)?It(i):i;let g=f,m=Rc(g);for(;m&&i&&p!==g;){const y=Br(m),v=m.getBoundingClientRect(),x=on(m),S=v.left+(m.clientLeft+parseFloat(x.paddingLeft))*y.x,b=v.top+(m.clientTop+parseFloat(x.paddingTop))*y.y;u*=y.x,l*=y.y,c*=y.x,d*=y.y,u+=S,l+=b,g=It(m),m=Rc(g)}}return gs({width:c,height:d,x:u,y:l})}function kf(e,t){const n=Ll(e).scrollLeft;return t?t.left+n:yr(wn(e)).left+n}function Xk(e,t,n){n===void 0&&(n=!1);const i=e.getBoundingClientRect(),r=i.left+t.scrollLeft-(n?0:kf(e,i)),o=i.top+t.scrollTop;return{x:r,y:o}}function r4(e){let{elements:t,rect:n,offsetParent:i,strategy:r}=e;const o=r==="fixed",a=wn(i),s=t?Ul(t.floating):!1;if(i===a||s&&o)return n;let u={scrollLeft:0,scrollTop:0},l=gn(1);const c=gn(0),d=yn(i);if((d||!d&&!o)&&((mi(i)!=="body"||Go(a))&&(u=Ll(i)),yn(i))){const p=yr(i);l=Br(i),c.x=p.x+i.clientLeft,c.y=p.y+i.clientTop}const f=a&&!d&&!o?Xk(a,u,!0):gn(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-u.scrollLeft*l.x+c.x+f.x,y:n.y*l.y-u.scrollTop*l.y+c.y+f.y}}function i4(e){return Array.from(e.getClientRects())}function o4(e){const t=wn(e),n=Ll(e),i=e.ownerDocument.body,r=wt(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),o=wt(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let a=-n.scrollLeft+kf(e);const s=-n.scrollTop;return on(i).direction==="rtl"&&(a+=wt(t.clientWidth,i.clientWidth)-r),{width:r,height:o,x:a,y:s}}function a4(e,t){const n=It(e),i=wn(e),r=n.visualViewport;let o=i.clientWidth,a=i.clientHeight,s=0,u=0;if(r){o=r.width,a=r.height;const l=Sf();(!l||l&&t==="fixed")&&(s=r.offsetLeft,u=r.offsetTop)}return{width:o,height:a,x:s,y:u}}const s4=new Set(["absolute","fixed"]);function l4(e,t){const n=yr(e,!0,t==="fixed"),i=n.top+e.clientTop,r=n.left+e.clientLeft,o=yn(e)?Br(e):gn(1),a=e.clientWidth*o.x,s=e.clientHeight*o.y,u=r*o.x,l=i*o.y;return{width:a,height:s,x:u,y:l}}function Gm(e,t,n){let i;if(t==="viewport")i=a4(e,n);else if(t==="document")i=o4(wn(e));else if(rn(t))i=l4(t,n);else{const r=Qk(e);i={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return gs(i)}function eE(e,t){const n=Xn(e);return n===t||!rn(n)||si(n)?!1:on(n).position==="fixed"||eE(n,t)}function u4(e,t){const n=t.get(e);if(n)return n;let i=to(e,[],!1).filter(s=>rn(s)&&mi(s)!=="body"),r=null;const o=on(e).position==="fixed";let a=o?Xn(e):e;for(;rn(a)&&!si(a);){const s=on(a),u=xf(a);!u&&s.position==="fixed"&&(r=null),(o?!u&&!r:!u&&s.position==="static"&&!!r&&s4.has(r.position)||Go(a)&&!u&&eE(e,a))?i=i.filter(c=>c!==a):r=s,a=Xn(a)}return t.set(e,i),i}function c4(e){let{element:t,boundary:n,rootBoundary:i,strategy:r}=e;const a=[...n==="clippingAncestors"?Ul(t)?[]:u4(t,this._c):[].concat(n),i],s=a[0],u=a.reduce((l,c)=>{const d=Gm(t,c,r);return l.top=wt(d.top,l.top),l.right=Qn(d.right,l.right),l.bottom=Qn(d.bottom,l.bottom),l.left=wt(d.left,l.left),l},Gm(t,s,r));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function d4(e){const{width:t,height:n}=Yk(e);return{width:t,height:n}}function p4(e,t,n){const i=yn(t),r=wn(t),o=n==="fixed",a=yr(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const u=gn(0);function l(){u.x=kf(r)}if(i||!i&&!o)if((mi(t)!=="body"||Go(r))&&(s=Ll(t)),i){const p=yr(t,!0,o,t);u.x=p.x+t.clientLeft,u.y=p.y+t.clientTop}else r&&l();o&&!i&&r&&l();const c=r&&!i&&!o?Xk(r,s):gn(0),d=a.left+s.scrollLeft-u.x-c.x,f=a.top+s.scrollTop-u.y-c.y;return{x:d,y:f,width:a.width,height:a.height}}function xu(e){return on(e).position==="static"}function Km(e,t){if(!yn(e)||on(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return wn(e)===n&&(n=n.ownerDocument.body),n}function tE(e,t){const n=It(e);if(Ul(e))return n;if(!yn(e)){let r=Xn(e);for(;r&&!si(r);){if(rn(r)&&!xu(r))return r;r=Xn(r)}return n}let i=Km(e,t);for(;i&&WD(i)&&xu(i);)i=Km(i,t);return i&&si(i)&&xu(i)&&!xf(i)?n:i||XD(e)||n}const f4=async function(e){const t=this.getOffsetParent||tE,n=this.getDimensions,i=await n(e.floating);return{reference:p4(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function h4(e){return on(e).direction==="rtl"}const m4={convertOffsetParentRelativeRectToViewportRelativeRect:r4,getDocumentElement:wn,getClippingRect:c4,getOffsetParent:tE,getElementRects:f4,getClientRects:i4,getDimensions:d4,getScale:Br,isElement:rn,isRTL:h4};function nE(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function g4(e,t){let n=null,i;const r=wn(e);function o(){var s;clearTimeout(i),(s=n)==null||s.disconnect(),n=null}function a(s,u){s===void 0&&(s=!1),u===void 0&&(u=1),o();const l=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=l;if(s||t(),!f||!p)return;const g=_a(d),m=_a(r.clientWidth-(c+f)),y=_a(r.clientHeight-(d+p)),v=_a(c),S={rootMargin:-g+"px "+-m+"px "+-y+"px "+-v+"px",threshold:wt(0,Qn(1,u))||1};let b=!0;function A(E){const C=E[0].intersectionRatio;if(C!==u){if(!b)return a();C?a(!1,C):i=setTimeout(()=>{a(!1,1e-7)},1e3)}C===1&&!nE(l,e.getBoundingClientRect())&&a(),b=!1}try{n=new IntersectionObserver(A,{...S,root:r.ownerDocument})}catch{n=new IntersectionObserver(A,S)}n.observe(e)}return a(!0),o}function v4(e,t,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:u=!1}=i,l=If(e),c=r||o?[...l?to(l):[],...to(t)]:[];c.forEach(v=>{r&&v.addEventListener("scroll",n,{passive:!0}),o&&v.addEventListener("resize",n)});const d=l&&s?g4(l,n):null;let f=-1,p=null;a&&(p=new ResizeObserver(v=>{let[x]=v;x&&x.target===l&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),l&&!u&&p.observe(l),p.observe(t));let g,m=u?yr(e):null;u&&y();function y(){const v=yr(e);m&&!nE(m,v)&&n(),m=v,g=requestAnimationFrame(y)}return n(),()=>{var v;c.forEach(x=>{r&&x.removeEventListener("scroll",n),o&&x.removeEventListener("resize",n)}),d?.(),(v=p)==null||v.disconnect(),p=null,u&&cancelAnimationFrame(g)}}const y4=BD,b4=ZD,_4=UD,w4=VD,x4=LD,Ym=DD,S4=qD,I4=(e,t,n)=>{const i=new Map,r={platform:m4,...n},o={...r.platform,_c:i};return zD(e,t,{...r,platform:o})};var k4=typeof document<"u",E4=function(){},Da=k4?$.useLayoutEffect:E4;function vs(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(!vs(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)&&!vs(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function rE(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Qm(e,t){const n=rE(e);return Math.round(t*n)/n}function Su(e){const t=w.useRef(e);return Da(()=>{t.current=e}),t}function T4(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:o,floating:a}={},transform:s=!0,whileElementsMounted:u,open:l}=e,[c,d]=w.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=w.useState(i);vs(f,i)||p(i);const[g,m]=w.useState(null),[y,v]=w.useState(null),x=w.useCallback(X=>{X!==E.current&&(E.current=X,m(X))},[]),S=w.useCallback(X=>{X!==C.current&&(C.current=X,v(X))},[]),b=o||g,A=a||y,E=w.useRef(null),C=w.useRef(null),P=w.useRef(c),j=u!=null,F=Su(u),D=Su(r),V=Su(l),G=w.useCallback(()=>{if(!E.current||!C.current)return;const X={placement:t,strategy:n,middleware:f};D.current&&(X.platform=D.current),I4(E.current,C.current,X).then(me=>{const I={...me,isPositioned:V.current!==!1};z.current&&!vs(P.current,I)&&(P.current=I,yy.flushSync(()=>{d(I)}))})},[f,t,n,D,V]);Da(()=>{l===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,d(X=>({...X,isPositioned:!1})))},[l]);const z=w.useRef(!1);Da(()=>(z.current=!0,()=>{z.current=!1}),[]),Da(()=>{if(b&&(E.current=b),A&&(C.current=A),b&&A){if(F.current)return F.current(b,A,G);G()}},[b,A,G,F,j]);const U=w.useMemo(()=>({reference:E,floating:C,setReference:x,setFloating:S}),[x,S]),Q=w.useMemo(()=>({reference:b,floating:A}),[b,A]),ie=w.useMemo(()=>{const X={position:n,left:0,top:0};if(!Q.floating)return X;const me=Qm(Q.floating,c.x),I=Qm(Q.floating,c.y);return s?{...X,transform:"translate("+me+"px, "+I+"px)",...rE(Q.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:me,top:I}},[n,s,Q.floating,c.x,c.y]);return w.useMemo(()=>({...c,update:G,refs:U,elements:Q,floatingStyles:ie}),[c,G,U,Q,ie])}const $4=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?Ym({element:i.current,padding:r}).fn(n):{}:i?Ym({element:i,padding:r}).fn(n):{}}}},C4=(e,t)=>({...y4(e),options:[e,t]}),A4=(e,t)=>({...b4(e),options:[e,t]}),P4=(e,t)=>({...S4(e),options:[e,t]}),R4=(e,t)=>({..._4(e),options:[e,t]}),O4=(e,t)=>({...w4(e),options:[e,t]}),N4=(e,t)=>({...x4(e),options:[e,t]}),j4=(e,t)=>({...$4(e),options:[e,t]});var M4="Arrow",iE=w.forwardRef((e,t)=>{const{children:n,width:i=10,height:r=5,...o}=e;return h.jsx(We.svg,{...o,ref:t,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:h.jsx("polygon",{points:"0,0 30,0 15,10"})})});iE.displayName=M4;var z4=iE;function D4(e){const[t,n]=w.useState(void 0);return Lt(()=>{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 a,s;if("borderBoxSize"in o){const u=o.borderBoxSize,l=Array.isArray(u)?u[0]:u;a=l.inlineSize,s=l.blockSize}else a=e.offsetWidth,s=e.offsetHeight;n({width:a,height:s})});return i.observe(e,{box:"border-box"}),()=>i.unobserve(e)}else n(void 0)},[e]),t}var Ef="Popper",[oE,Fl]=Wo(Ef),[U4,aE]=oE(Ef),sE=e=>{const{__scopePopper:t,children:n}=e,[i,r]=w.useState(null);return h.jsx(U4,{scope:t,anchor:i,onAnchorChange:r,children:n})};sE.displayName=Ef;var lE="PopperAnchor",uE=w.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:i,...r}=e,o=aE(lE,n),a=w.useRef(null),s=Ge(t,a),u=w.useRef(null);return w.useEffect(()=>{const l=u.current;u.current=i?.current||a.current,l!==u.current&&o.onAnchorChange(u.current)}),i?null:h.jsx(We.div,{...r,ref:s})});uE.displayName=lE;var Tf="PopperContent",[L4,F4]=oE(Tf),cE=w.forwardRef((e,t)=>{const{__scopePopper:n,side:i="bottom",sideOffset:r=0,align:o="center",alignOffset:a=0,arrowPadding:s=0,avoidCollisions:u=!0,collisionBoundary:l=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:g,...m}=e,y=aE(Tf,n),[v,x]=w.useState(null),S=Ge(t,we=>x(we)),[b,A]=w.useState(null),E=D4(b),C=E?.width??0,P=E?.height??0,j=i+(o!=="center"?"-"+o:""),F=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},D=Array.isArray(l)?l:[l],V=D.length>0,G={padding:F,boundary:D.filter(Z4),altBoundary:V},{refs:z,floatingStyles:U,placement:Q,isPositioned:ie,middlewareData:X}=T4({strategy:"fixed",placement:j,whileElementsMounted:(...we)=>v4(...we,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[C4({mainAxis:r+P,alignmentAxis:a}),u&&A4({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?P4():void 0,...G}),u&&R4({...G}),O4({...G,apply:({elements:we,rects:vt,availableWidth:sn,availableHeight:Rt})=>{const{width:Qe,height:Cr}=vt.reference,He=we.floating.style;He.setProperty("--radix-popper-available-width",`${sn}px`),He.setProperty("--radix-popper-available-height",`${Rt}px`),He.setProperty("--radix-popper-anchor-width",`${Qe}px`),He.setProperty("--radix-popper-anchor-height",`${Cr}px`)}}),b&&j4({element:b,padding:s}),q4({arrowWidth:C,arrowHeight:P}),f&&N4({strategy:"referenceHidden",...G})]}),[me,I]=fE(Q),Te=Et(g);Lt(()=>{ie&&Te?.()},[ie,Te]);const ve=X.arrow?.x,T=X.arrow?.y,H=X.arrow?.centerOffset!==0,[te,le]=w.useState();return Lt(()=>{v&&le(window.getComputedStyle(v).zIndex)},[v]),h.jsx("div",{ref:z.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:ie?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:te,"--radix-popper-transform-origin":[X.transformOrigin?.x,X.transformOrigin?.y].join(" "),...X.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:h.jsx(L4,{scope:n,placedSide:me,onArrowChange:A,arrowX:ve,arrowY:T,shouldHideArrow:H,children:h.jsx(We.div,{"data-side":me,"data-align":I,...m,ref:S,style:{...m.style,animation:ie?void 0:"none"}})})})});cE.displayName=Tf;var dE="PopperArrow",B4={top:"bottom",right:"left",bottom:"top",left:"right"},pE=w.forwardRef(function(t,n){const{__scopePopper:i,...r}=t,o=F4(dE,i),a=B4[o.placedSide];return h.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]: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:h.jsx(z4,{...r,ref:n,style:{...r.style,display:"block"}})})});pE.displayName=dE;function Z4(e){return e!==null}var q4=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:i,middlewareData:r}=t,a=r.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,u=a?0:e.arrowHeight,[l,c]=fE(n),d={start:"0%",center:"50%",end:"100%"}[c],f=(r.arrow?.x??0)+s/2,p=(r.arrow?.y??0)+u/2;let g="",m="";return l==="bottom"?(g=a?d:`${f}px`,m=`${-u}px`):l==="top"?(g=a?d:`${f}px`,m=`${i.floating.height+u}px`):l==="right"?(g=`${-u}px`,m=a?d:`${p}px`):l==="left"&&(g=`${i.floating.width+u}px`,m=a?d:`${p}px`),{data:{x:g,y:m}}}});function fE(e){const[t,n="center"]=e.split("-");return[t,n]}var hE=sE,$f=uE,mE=cE,gE=pE,V4="Portal",Bl=w.forwardRef((e,t)=>{const{container:n,...i}=e,[r,o]=w.useState(!1);Lt(()=>o(!0),[]);const a=n||r&&globalThis?.document?.body;return a?vy.createPortal(h.jsx(We.div,{...i,ref:t}),a):null});Bl.displayName=V4;function H4(e,t){return w.useReducer((n,i)=>t[n][i]??n,e)}var Mn=e=>{const{present:t,children:n}=e,i=J4(t),r=typeof n=="function"?n({present:i.isPresent}):w.Children.only(n),o=Ge(i.ref,W4(r));return typeof n=="function"||i.isPresent?w.cloneElement(r,{ref:o}):null};Mn.displayName="Presence";function J4(e){const[t,n]=w.useState(),i=w.useRef(null),r=w.useRef(e),o=w.useRef("none"),a=e?"mounted":"unmounted",[s,u]=H4(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const l=wa(i.current);o.current=s==="mounted"?l:"none"},[s]),Lt(()=>{const l=i.current,c=r.current;if(c!==e){const f=o.current,p=wa(l);e?u("MOUNT"):p==="none"||l?.display==="none"?u("UNMOUNT"):u(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,u]),Lt(()=>{if(t){let l;const c=t.ownerDocument.defaultView??window,d=p=>{const m=wa(i.current).includes(CSS.escape(p.animationName));if(p.target===t&&m&&(u("ANIMATION_END"),!r.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",l=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},f=p=>{p.target===t&&(o.current=wa(i.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{c.clearTimeout(l),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:w.useCallback(l=>{i.current=l?getComputedStyle(l):null,n(l)},[])}}function wa(e){return e?.animationName||"none"}function W4(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 G4=w[" useInsertionEffect ".trim().toString()]||Lt;function Zl({prop:e,defaultProp:t,onChange:n=()=>{},caller:i}){const[r,o,a]=K4({defaultProp:t,onChange:n}),s=e!==void 0,u=s?e:r;{const c=w.useRef(e!==void 0);w.useEffect(()=>{const d=c.current;d!==s&&console.warn(`${i} is changing from ${d?"controlled":"uncontrolled"} to ${s?"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=s},[s,i])}const l=w.useCallback(c=>{if(s){const d=Y4(c)?c(e):c;d!==e&&a.current?.(d)}else o(c)},[s,e,o,a]);return[u,l]}function K4({defaultProp:e,onChange:t}){const[n,i]=w.useState(e),r=w.useRef(n),o=w.useRef(t);return G4(()=>{o.current=t},[t]),w.useEffect(()=>{r.current!==n&&(o.current?.(n),r.current=n)},[n,r]),[n,i,o]}function Y4(e){return typeof e=="function"}var Q4=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Rr=new WeakMap,xa=new WeakMap,Sa={},Iu=0,vE=function(e){return e&&(e.host||vE(e.parentNode))},X4=function(e,t){return t.map(function(n){if(e.contains(n))return n;var i=vE(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})},eU=function(e,t,n,i){var r=X4(t,Array.isArray(e)?e:[e]);Sa[n]||(Sa[n]=new WeakMap);var o=Sa[n],a=[],s=new Set,u=new Set(r),l=function(d){!d||s.has(d)||(s.add(d),l(d.parentNode))};r.forEach(l);var c=function(d){!d||u.has(d)||Array.prototype.forEach.call(d.children,function(f){if(s.has(f))c(f);else try{var p=f.getAttribute(i),g=p!==null&&p!=="false",m=(Rr.get(f)||0)+1,y=(o.get(f)||0)+1;Rr.set(f,m),o.set(f,y),a.push(f),m===1&&g&&xa.set(f,!0),y===1&&f.setAttribute(n,"true"),g||f.setAttribute(i,"true")}catch(v){console.error("aria-hidden: cannot operate on ",f,v)}})};return c(t),s.clear(),Iu++,function(){a.forEach(function(d){var f=Rr.get(d)-1,p=o.get(d)-1;Rr.set(d,f),o.set(d,p),f||(xa.has(d)||d.removeAttribute(i),xa.delete(d)),p||d.removeAttribute(n)}),Iu--,Iu||(Rr=new WeakMap,Rr=new WeakMap,xa=new WeakMap,Sa={})}},yE=function(e,t,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),r=Q4(e);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),eU(i,r,n,"aria-hidden")):function(){return null}},pn=function(){return pn=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},pn.apply(this,arguments)};function bE(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 tU(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 Ua="right-scroll-bar-position",La="width-before-scroll-bar",nU="with-scroll-bars-hidden",rU="--removed-body-scroll-bar-size";function ku(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function iU(e,t){var n=$.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 oU=typeof window<"u"?w.useLayoutEffect:w.useEffect,Xm=new WeakMap;function aU(e,t){var n=iU(null,function(i){return e.forEach(function(r){return ku(r,i)})});return oU(function(){var i=Xm.get(n);if(i){var r=new Set(i),o=new Set(e),a=n.current;r.forEach(function(s){o.has(s)||ku(s,null)}),o.forEach(function(s){r.has(s)||ku(s,a)})}Xm.set(n,e)},[e]),n}function sU(e){return e}function lU(e,t){t===void 0&&(t=sU);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 a=t(o,i);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(o){for(i=!0;n.length;){var a=n;n=[],a.forEach(o)}n={push:function(s){return o(s)},filter:function(){return n}}},assignMedium:function(o){i=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(o),a=n}var u=function(){var c=a;a=[],c.forEach(o)},l=function(){return Promise.resolve().then(u)};l(),n={push:function(c){a.push(c),l()},filter:function(c){return a=a.filter(c),n}}}};return r}function uU(e){e===void 0&&(e={});var t=lU(null);return t.options=pn({async:!0,ssr:!1},e),t}var _E=function(e){var t=e.sideCar,n=bE(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 w.createElement(i,pn({},n))};_E.isSideCarExport=!0;function cU(e,t){return e.useMedium(t),_E}var wE=uU(),Eu=function(){},ql=w.forwardRef(function(e,t){var n=w.useRef(null),i=w.useState({onScrollCapture:Eu,onWheelCapture:Eu,onTouchMoveCapture:Eu}),r=i[0],o=i[1],a=e.forwardProps,s=e.children,u=e.className,l=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,v=e.as,x=v===void 0?"div":v,S=e.gapMode,b=bE(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),A=f,E=aU([n,t]),C=pn(pn({},b),r);return w.createElement(w.Fragment,null,c&&w.createElement(A,{sideCar:wE,removeScrollBar:l,shards:d,noRelative:p,noIsolation:g,inert:m,setCallbacks:o,allowPinchZoom:!!y,lockRef:n,gapMode:S}),a?w.cloneElement(w.Children.only(s),pn(pn({},C),{ref:E})):w.createElement(x,pn({},C,{className:u,ref:E}),s))});ql.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ql.classNames={fullWidth:La,zeroRight:Ua};var dU=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function pU(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=dU();return t&&e.setAttribute("nonce",t),e}function fU(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function hU(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var mU=function(){var e=0,t=null;return{add:function(n){e==0&&(t=pU())&&(fU(t,n),hU(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},gU=function(){var e=mU();return function(t,n){w.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},xE=function(){var e=gU(),t=function(n){var i=n.styles,r=n.dynamic;return e(i,r),null};return t},vU={left:0,top:0,right:0,gap:0},Tu=function(e){return parseInt(e||"",10)||0},yU=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[Tu(n),Tu(i),Tu(r)]},bU=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return vU;var t=yU(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])}},_U=xE(),Zr="data-scroll-locked",wU=function(e,t,n,i){var r=e.left,o=e.top,a=e.right,s=e.gap;return n===void 0&&(n="margin"),`
|
|
32
|
+
.`.concat(nU,` {
|
|
33
|
+
overflow: hidden `).concat(i,`;
|
|
34
|
+
padding-right: `).concat(s,"px ").concat(i,`;
|
|
35
|
+
}
|
|
36
|
+
body[`).concat(Zr,`] {
|
|
37
|
+
overflow: hidden `).concat(i,`;
|
|
38
|
+
overscroll-behavior: contain;
|
|
39
|
+
`).concat([t&&"position: relative ".concat(i,";"),n==="margin"&&`
|
|
40
|
+
padding-left: `.concat(r,`px;
|
|
41
|
+
padding-top: `).concat(o,`px;
|
|
42
|
+
padding-right: `).concat(a,`px;
|
|
43
|
+
margin-left:0;
|
|
44
|
+
margin-top:0;
|
|
45
|
+
margin-right: `).concat(s,"px ").concat(i,`;
|
|
46
|
+
`),n==="padding"&&"padding-right: ".concat(s,"px ").concat(i,";")].filter(Boolean).join(""),`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
.`).concat(Ua,` {
|
|
50
|
+
right: `).concat(s,"px ").concat(i,`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
.`).concat(La,` {
|
|
54
|
+
margin-right: `).concat(s,"px ").concat(i,`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
.`).concat(Ua," .").concat(Ua,` {
|
|
58
|
+
right: 0 `).concat(i,`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
.`).concat(La," .").concat(La,` {
|
|
62
|
+
margin-right: 0 `).concat(i,`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
body[`).concat(Zr,`] {
|
|
66
|
+
`).concat(rU,": ").concat(s,`px;
|
|
67
|
+
}
|
|
68
|
+
`)},eg=function(){var e=parseInt(document.body.getAttribute(Zr)||"0",10);return isFinite(e)?e:0},xU=function(){w.useEffect(function(){return document.body.setAttribute(Zr,(eg()+1).toString()),function(){var e=eg()-1;e<=0?document.body.removeAttribute(Zr):document.body.setAttribute(Zr,e.toString())}},[])},SU=function(e){var t=e.noRelative,n=e.noImportant,i=e.gapMode,r=i===void 0?"margin":i;xU();var o=w.useMemo(function(){return bU(r)},[r]);return w.createElement(_U,{styles:wU(o,!t,r,n?"":"!important")})},Oc=!1;if(typeof window<"u")try{var Ia=Object.defineProperty({},"passive",{get:function(){return Oc=!0,!0}});window.addEventListener("test",Ia,Ia),window.removeEventListener("test",Ia,Ia)}catch{Oc=!1}var Or=Oc?{passive:!1}:!1,IU=function(e){return e.tagName==="TEXTAREA"},SE=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!IU(e)&&n[t]==="visible")},kU=function(e){return SE(e,"overflowY")},EU=function(e){return SE(e,"overflowX")},tg=function(e,t){var n=t.ownerDocument,i=t;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=IE(e,i);if(r){var o=kE(e,i),a=o[1],s=o[2];if(a>s)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},TU=function(e){var t=e.scrollTop,n=e.scrollHeight,i=e.clientHeight;return[t,n,i]},$U=function(e){var t=e.scrollLeft,n=e.scrollWidth,i=e.clientWidth;return[t,n,i]},IE=function(e,t){return e==="v"?kU(t):EU(t)},kE=function(e,t){return e==="v"?TU(t):$U(t)},CU=function(e,t){return e==="h"&&t==="rtl"?-1:1},AU=function(e,t,n,i,r){var o=CU(e,window.getComputedStyle(t).direction),a=o*i,s=n.target,u=t.contains(s),l=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=kE(e,s),g=p[0],m=p[1],y=p[2],v=m-y-o*g;(g||v)&&IE(e,s)&&(d+=v,f+=g);var x=s.parentNode;s=x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE?x.host:x}while(!u&&s!==document.body||u&&(t.contains(s)||t===s));return(c&&Math.abs(d)<1||!c&&Math.abs(f)<1)&&(l=!0),l},ka=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ng=function(e){return[e.deltaX,e.deltaY]},rg=function(e){return e&&"current"in e?e.current:e},PU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},RU=function(e){return`
|
|
69
|
+
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
70
|
+
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
71
|
+
`)},OU=0,Nr=[];function NU(e){var t=w.useRef([]),n=w.useRef([0,0]),i=w.useRef(),r=w.useState(OU++)[0],o=w.useState(xE)[0],a=w.useRef(e);w.useEffect(function(){a.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var m=tU([e.lockRef.current],(e.shards||[]).map(rg),!0).filter(Boolean);return m.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),m.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var s=w.useCallback(function(m,y){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var v=ka(m),x=n.current,S="deltaX"in m?m.deltaX:x[0]-v[0],b="deltaY"in m?m.deltaY:x[1]-v[1],A,E=m.target,C=Math.abs(S)>Math.abs(b)?"h":"v";if("touches"in m&&C==="h"&&E.type==="range")return!1;var P=tg(C,E);if(!P)return!0;if(P?A=C:(A=C==="v"?"h":"v",P=tg(C,E)),!P)return!1;if(!i.current&&"changedTouches"in m&&(S||b)&&(i.current=A),!A)return!0;var j=i.current||A;return AU(j,y,m,j==="h"?S:b)},[]),u=w.useCallback(function(m){var y=m;if(!(!Nr.length||Nr[Nr.length-1]!==o)){var v="deltaY"in y?ng(y):ka(y),x=t.current.filter(function(A){return A.name===y.type&&(A.target===y.target||y.target===A.shadowParent)&&PU(A.delta,v)})[0];if(x&&x.should){y.cancelable&&y.preventDefault();return}if(!x){var S=(a.current.shards||[]).map(rg).filter(Boolean).filter(function(A){return A.contains(y.target)}),b=S.length>0?s(y,S[0]):!a.current.noIsolation;b&&y.cancelable&&y.preventDefault()}}},[]),l=w.useCallback(function(m,y,v,x){var S={name:m,delta:y,target:v,should:x,shadowParent:jU(v)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(b){return b!==S})},1)},[]),c=w.useCallback(function(m){n.current=ka(m),i.current=void 0},[]),d=w.useCallback(function(m){l(m.type,ng(m),m.target,s(m,e.lockRef.current))},[]),f=w.useCallback(function(m){l(m.type,ka(m),m.target,s(m,e.lockRef.current))},[]);w.useEffect(function(){return Nr.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,Or),document.addEventListener("touchmove",u,Or),document.addEventListener("touchstart",c,Or),function(){Nr=Nr.filter(function(m){return m!==o}),document.removeEventListener("wheel",u,Or),document.removeEventListener("touchmove",u,Or),document.removeEventListener("touchstart",c,Or)}},[]);var p=e.removeScrollBar,g=e.inert;return w.createElement(w.Fragment,null,g?w.createElement(o,{styles:RU(r)}):null,p?w.createElement(SU,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function jU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const MU=cU(wE,NU);var Cf=w.forwardRef(function(e,t){return w.createElement(ql,pn({},e,{ref:t,sideCar:MU}))});Cf.classNames=ql.classNames;var Vl="Popover",[EE]=Wo(Vl,[Fl]),Ko=Fl(),[zU,rr]=EE(Vl),TE=e=>{const{__scopePopover:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:a=!1}=e,s=Ko(t),u=w.useRef(null),[l,c]=w.useState(!1),[d,f]=Zl({prop:i,defaultProp:r??!1,onChange:o,caller:Vl});return h.jsx(hE,{...s,children:h.jsx(zU,{scope:t,contentId:Fr(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:w.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:w.useCallback(()=>c(!0),[]),onCustomAnchorRemove:w.useCallback(()=>c(!1),[]),modal:a,children:n})})};TE.displayName=Vl;var $E="PopoverAnchor",DU=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=rr($E,n),o=Ko(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=r;return w.useEffect(()=>(a(),()=>s()),[a,s]),h.jsx($f,{...o,...i,ref:t})});DU.displayName=$E;var CE="PopoverTrigger",AE=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=rr(CE,n),o=Ko(n),a=Ge(t,r.triggerRef),s=h.jsx(We.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":jE(r.open),...i,ref:a,onClick:Re(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?s:h.jsx($f,{asChild:!0,...o,children:s})});AE.displayName=CE;var Af="PopoverPortal",[UU,LU]=EE(Af,{forceMount:void 0}),PE=e=>{const{__scopePopover:t,forceMount:n,children:i,container:r}=e,o=rr(Af,t);return h.jsx(UU,{scope:t,forceMount:n,children:h.jsx(Mn,{present:n||o.open,children:h.jsx(Bl,{asChild:!0,container:r,children:i})})})};PE.displayName=Af;var li="PopoverContent",RE=w.forwardRef((e,t)=>{const n=LU(li,e.__scopePopover),{forceMount:i=n.forceMount,...r}=e,o=rr(li,e.__scopePopover);return h.jsx(Mn,{present:i||o.open,children:o.modal?h.jsx(BU,{...r,ref:t}):h.jsx(ZU,{...r,ref:t})})});RE.displayName=li;var FU=vf("PopoverContent.RemoveScroll"),BU=w.forwardRef((e,t)=>{const n=rr(li,e.__scopePopover),i=w.useRef(null),r=Ge(t,i),o=w.useRef(!1);return w.useEffect(()=>{const a=i.current;if(a)return yE(a)},[]),h.jsx(Cf,{as:FU,allowPinchZoom:!0,children:h.jsx(OE,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Re(e.onCloseAutoFocus,a=>{a.preventDefault(),o.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Re(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,u=s.button===0&&s.ctrlKey===!0,l=s.button===2||u;o.current=l},{checkForDefaultPrevented:!1}),onFocusOutside:Re(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),ZU=w.forwardRef((e,t)=>{const n=rr(li,e.__scopePopover),i=w.useRef(!1),r=w.useRef(!1);return h.jsx(OE,{...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 a=o.target;n.triggerRef.current?.contains(a)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),OE=w.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:s,onPointerDownOutside:u,onFocusOutside:l,onInteractOutside:c,...d}=e,f=rr(li,n),p=Ko(n);return Vk(),h.jsx(yf,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:h.jsx(zl,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:c,onEscapeKeyDown:s,onPointerDownOutside:u,onFocusOutside:l,onDismiss:()=>f.onOpenChange(!1),children:h.jsx(mE,{"data-state":jE(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)"}})})})}),NE="PopoverClose",qU=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=rr(NE,n);return h.jsx(We.button,{type:"button",...i,ref:t,onClick:Re(e.onClick,()=>r.onOpenChange(!1))})});qU.displayName=NE;var VU="PopoverArrow",HU=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=Ko(n);return h.jsx(gE,{...r,...i,ref:t})});HU.displayName=VU;function jE(e){return e?"open":"closed"}var JU=TE,WU=AE,GU=PE,KU=RE;const ME=$.forwardRef((e,t)=>h.jsx(ct.div,{...e,ref:t}));ME.displayName="AttachmentPrimitive.Root";const zE=()=>{const e=_.useAssistantState(({attachment:t})=>t.name);return h.jsx(h.Fragment,{children:e})};zE.displayName="AttachmentPrimitive.Name";const YU=()=>{const e=_.useAssistantApi();return $.useCallback(()=>{e.attachment().remove()},[e])},QU=_n("AttachmentPrimitive.Remove",YU),XU=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(({thread:i,message:r})=>!!(r.branchNumber>=r.branchCount||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=$.useCallback(()=>{e.message().switchToBranch({position:"next"})},[e]);return t?null:n},eL=_n("BranchPickerPrimitive.Next",XU),tL=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(({thread:i,message:r})=>!!(r.branchNumber<=1||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=$.useCallback(()=>{e.message().switchToBranch({position:"previous"})},[e]);return t?null:n},nL=_n("BranchPickerPrimitive.Previous",tL),rL=()=>_.useAssistantState(({message:t})=>t.branchCount),DE=()=>{const e=rL();return h.jsx(h.Fragment,{children:e})};DE.displayName="BranchPickerPrimitive.Count";const iL=()=>_.useAssistantState(({message:t})=>t.branchNumber),UE=()=>{const e=iL();return h.jsx(h.Fragment,{children:e})};UE.displayName="BranchPickerPrimitive.Number";const Yo=e=>{const t=$.useRef(void 0);return $.useCallback(i=>{t.current&&t.current(),i&&(t.current=e(i))},[e])},LE=(e,t)=>{const n=$.useCallback(i=>{if(!e)return;const r=e(),o=()=>{const s=t?t(i):i.offsetHeight;r.setHeight(s)},a=new ResizeObserver(o);return a.observe(i),o(),()=>{a.disconnect(),r.unregister()}},[e,t]);return Yo(n)},ig=$.createContext(!1),og=(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},FE=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const i=_.useAssistantState(({message:u})=>u.isLast&&u.index>=2),r=Ml({optional:!0}),o=$.useContext(ig),a=$.useCallback(u=>{if(!r||o)return;const l=()=>{const c=r.getState();if(c.turnAnchor==="top"&&i){const{viewport:d,inset:f,userMessage:p}=c.height,g=og(t,u),m=og(n,u),y=p<=g?p:m,v=Math.max(0,d-f-y);u.style.minHeight=`${v}px`,u.style.flexShrink="0",u.style.transition="min-height 0s"}else u.style.minHeight="",u.style.flexShrink="",u.style.transition=""};return l(),r.subscribe(l)},[r,i,o,t,n]),s=Yo(a);return h.jsx(ig.Provider,{value:!0,children:h.jsx(mf,{ref:s,children:e})})};FE.displayName="ThreadPrimitive.ViewportSlack";const oL=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(()=>e.message()),n=$.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 Yo(n)},aL=()=>{const e=Yi(r=>r.turnAnchor),t=Yi(r=>r.registerUserMessageHeight),n=_.useAssistantState(({thread:r,message:o})=>e==="top"&&o.role==="user"&&o.index===r.messages.length-2&&r.messages.at(-1)?.role==="assistant"),i=$.useCallback(r=>r.offsetHeight,[]);return LE(n?t:null,i)},Pf=$.forwardRef((e,t)=>{const n=oL(),i=aL(),r=Ge(t,n,i);return h.jsx(FE,{children:h.jsx(ct.div,{...e,ref:r})})});Pf.displayName="MessagePrimitive.Root";const BE=()=>_.useAssistantState(({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}),ZE=$.forwardRef(({smooth:e=!0,component:t="span",...n},i)=>{const{text:r,status:o}=jk(BE(),e);return h.jsx(t,{"data-status":o.type,...n,ref:i,children:r})});ZE.displayName="MessagePartPrimitive.Text";const sL=()=>_.useAssistantState(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),qE=$.forwardRef((e,t)=>{const{image:n}=sL();return h.jsx(ct.img,{src:n,...e,ref:t})});qE.displayName="MessagePartPrimitive.Image";const VE=({children:e})=>_.useAssistantState(({part:n})=>n.status.type==="running")?e:null;VE.displayName="MessagePartPrimitive.InProgress";const ag=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})}}},lL=e=>{const t=[],n=ag("toolGroup"),i=ag("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},uL=()=>{const e=_.useAssistantState(gy.useShallow(t=>t.message.parts.map(n=>n.type)));return $.useMemo(()=>e.length===0?[]:lL(e),[e])},cL=({Fallback:e,...t})=>{const n=_.useAssistantState(({tools:i})=>{const r=i.tools[t.toolName]??e;return Array.isArray(r)?r[0]??e:r});return n?h.jsx(n,{...t}):null},kn={Text:()=>h.jsxs("p",{style:{whiteSpace:"pre-line"},children:[h.jsx(ZE,{}),h.jsx(VE,{children:h.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>h.jsx(qE,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},dL=({components:{Text:e=kn.Text,Reasoning:t=kn.Reasoning,Image:n=kn.Image,Source:i=kn.Source,File:r=kn.File,Unstable_Audio:o=kn.Unstable_Audio,tools:a={}}={}})=>{const s=_.useAssistantApi(),u=_.useAssistantState(({part:c})=>c),l=u.type;if(l==="tool-call"){const c=s.part().addToolResult,d=s.part().resumeToolCall;if("Override"in a)return h.jsx(a.Override,{...u,addResult:c,resume:d});const f=a.by_name?.[u.toolName]??a.Fallback;return h.jsx(cL,{...u,Fallback:f,addResult:c,resume:d})}if(u.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(l){case"text":return h.jsx(e,{...u});case"reasoning":return h.jsx(t,{...u});case"source":return h.jsx(i,{...u});case"image":return h.jsx(n,{...u});case"file":return h.jsx(r,{...u});case"audio":return h.jsx(o,{...u});case"data":return null;default:const c=l;throw new Error(`Unknown message part type: ${c}`)}},Fa=$.memo(({index:e,components:t})=>h.jsx(iz,{index:e,children:h.jsx(dL,{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);Fa.displayName="MessagePrimitive.PartByIndex";const pL=({status:e,component:t})=>h.jsx(lz,{text:"",isRunning:e.type==="running",children:h.jsx(t,{type:"text",text:"",status:e})}),fL=Object.freeze({type:"complete"}),hL=({components:e})=>{const t=_.useAssistantState(n=>n.message.status??fL);return e?.Empty?h.jsx(e.Empty,{status:t}):h.jsx(pL,{status:t,component:e?.Text??kn.Text})},mL=$.memo(hL,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),Rf=({components:e})=>{const t=_.useAssistantState(({message:r})=>r.parts.length),n=uL(),i=$.useMemo(()=>t===0?h.jsx(mL,{components:e}):n.map(r=>{if(r.type==="single")return h.jsx(Fa,{index:r.index,components:e},r.index);if(r.type==="toolGroup"){const o=e?.ToolGroup??kn.ToolGroup;return h.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(a,s)=>h.jsx(Fa,{index:r.startIndex+s,components:e},s))},`tool-${r.startIndex}`)}else{const o=e?.ReasoningGroup??kn.ReasoningGroup;return h.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(a,s)=>h.jsx(Fa,{index:r.startIndex+s,components:e},s))},`reasoning-${r.startIndex}`)}}),[n,e,t]);return h.jsx(h.Fragment,{children:i})};Rf.displayName="MessagePrimitive.Parts";const gL=e=>_.useAssistantState(({message:t})=>{const{role:n,attachments:i,parts:r,branchCount:o,isLast:a,speech:s,isCopied:u,isHovering:l}=t;return!(e.hasBranches===!0&&o<2||e.user&&n!=="user"||e.assistant&&n!=="assistant"||e.system&&n!=="system"||e.lastOrHover===!0&&!l&&!a||e.last!==void 0&&e.last!==a||e.copied===!0&&!u||e.copied===!1&&u||e.speaking===!0&&s==null||e.speaking===!1&&s!=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)}),ys=({children:e,...t})=>gL(t)?e:null;ys.displayName="MessagePrimitive.If";const vL=(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}`)}},yL=({components:e})=>{const t=_.useAssistantState(({attachment:i})=>i);if(!t)return null;const n=vL(e,t);return n?h.jsx(n,{}):null},HE=$.memo(({index:e,components:t})=>h.jsx(oz,{index:e,children:h.jsx(yL,{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);HE.displayName="MessagePrimitive.AttachmentByIndex";const JE=({components:e})=>{const t=_.useAssistantState(({message:i})=>i.role!=="user"?0:i.attachments.length);return $.useMemo(()=>Array.from({length:t},(i,r)=>h.jsx(HE,{index:r,components:e},r)),[t,e])};JE.displayName="MessagePrimitive.Attachments";const WE=({children:e})=>_.useAssistantState(({message:n})=>n.status?.type==="incomplete"&&n.status.reason==="error")?e:null;WE.displayName="MessagePrimitive.Error";const GE=$.forwardRef(({hideWhenSingleBranch:e,...t},n)=>h.jsx(ys,{hasBranches:e?!0:void 0,children:h.jsx(ct.div,{...t,ref:n})}));GE.displayName="BranchPickerPrimitive.Root";const KE=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(i=>i.thread.isRunning||!i.composer.isEditing||i.composer.isEmpty),n=$.useCallback(()=>{e.composer().send()},[e]);return t?null:n},YE=_n("ComposerPrimitive.Send",KE),Of=$.forwardRef(({onSubmit:e,...t},n)=>{const i=KE(),r=o=>{o.preventDefault(),i&&i()};return h.jsx(ct.form,{...t,ref:n,onSubmit:Re(e,r)})});Of.displayName="ComposerPrimitive.Root";function Nc(){return Nc=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},Nc.apply(null,arguments)}function bL(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 _L=$.useLayoutEffect,wL=function(t){var n=$.useRef(t);return _L(function(){n.current=t}),n},sg=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},xL=function(t,n){var i=$.useRef();return $.useCallback(function(r){t.current=r,i.current&&sg(i.current,null),i.current=n,n&&sg(n,r)},[n])},lg={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},SL=function(t){Object.keys(lg).forEach(function(n){t.style.setProperty(n,lg[n],"important")})},ug=SL,ot=null,cg=function(t,n){var i=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?i+n.borderSize:i-n.paddingSize};function IL(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"),ug(ot)),ot.parentNode===null&&document.body.appendChild(ot);var r=e.paddingSize,o=e.borderSize,a=e.sizingStyle,s=a.boxSizing;Object.keys(a).forEach(function(f){var p=f;ot.style[p]=a[p]}),ug(ot),ot.value=t;var u=cg(ot,e);ot.value=t,u=cg(ot,e),ot.value="x";var l=ot.scrollHeight-r,c=l*n;s==="border-box"&&(c=c+r+o),u=Math.max(c,u);var d=l*i;return s==="border-box"&&(d=d+r+o),u=Math.min(d,u),[u,l]}var dg=function(){},kL=function(t,n){return t.reduce(function(i,r){return i[r]=n[r],i},{})},EL=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],TL=!!document.documentElement.currentStyle,$L=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var i=kL(EL,n),r=i.boxSizing;if(r==="")return null;TL&&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),a=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:o,borderSize:a}},CL=$L;function Nf(e,t,n){var i=wL(n);w.useLayoutEffect(function(){var r=function(a){return i.current(a)};if(e)return e.addEventListener(t,r),function(){return e.removeEventListener(t,r)}},[])}var AL=function(t,n){Nf(document.body,"reset",function(i){t.current.form===i.target&&n(i)})},PL=function(t){Nf(window,"resize",t)},RL=function(t){Nf(document.fonts,"loadingdone",t)},OL=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],NL=function(t,n){var i=t.cacheMeasurements,r=t.maxRows,o=t.minRows,a=t.onChange,s=a===void 0?dg:a,u=t.onHeightChange,l=u===void 0?dg:u,c=bL(t,OL),d=c.value!==void 0,f=w.useRef(null),p=xL(f,n),g=w.useRef(0),m=w.useRef(),y=function(){var S=f.current,b=i&&m.current?m.current:CL(S);if(b){m.current=b;var A=IL(b,S.value||S.placeholder||"x",o,r),E=A[0],C=A[1];g.current!==E&&(g.current=E,S.style.setProperty("height",E+"px","important"),l(E,{rowHeight:C}))}},v=function(S){d||y(),s(S)};return w.useLayoutEffect(y),AL(f,function(){if(!d){var x=f.current.value;requestAnimationFrame(function(){var S=f.current;S&&x!==S.value&&y()})}}),PL(y),RL(y),w.createElement("textarea",Nc({},c,{onChange:v,ref:p}))},jL=w.forwardRef(NL);const QE=e=>{const t=Et(e),n=Yi(i=>i.onScrollToBottom);$.useEffect(()=>n(t),[n,t])},jf=$.forwardRef(({autoFocus:e=!1,asChild:t,disabled:n,onChange:i,onKeyDown:r,onPaste:o,submitOnEnter:a=!0,cancelOnEscape:s=!0,unstable_focusOnRunStart:u=!0,unstable_focusOnScrollToBottom:l=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0,...f},p)=>{const g=_.useAssistantApi(),m=_.useAssistantState(({composer:P})=>P.isEditing?P.text:""),y=t?mf:jL,v=_.useAssistantState(({thread:P})=>P.isDisabled)||n,x=$.useRef(null),S=Ge(p,x);Fk(P=>{if(!s||!x.current?.contains(P.target))return;const j=g.composer();j.getState().canCancel&&(j.cancel(),P.preventDefault())});const b=P=>{v||!a||P.nativeEvent.isComposing||P.key==="Enter"&&P.shiftKey===!1&&(g.thread().getState().isRunning||(P.preventDefault(),x.current?.closest("form")?.requestSubmit()))},A=async P=>{if(!d)return;const j=g.thread().getState().capabilities,F=Array.from(P.clipboardData?.files||[]);if(j.attachments&&F.length>0)try{P.preventDefault(),await Promise.all(F.map(D=>g.composer().addAttachment(D)))}catch(D){console.error("Error adding attachment:",D)}},E=e&&!v,C=$.useCallback(()=>{const P=x.current;!P||!E||(P.focus({preventScroll:!0}),P.setSelectionRange(P.value.length,P.value.length))},[E]);return $.useEffect(()=>C(),[C]),QE(()=>{g.composer().getState().type==="thread"&&l&&C()}),$.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!u))return g.on("thread.run-start",C)},[u,C,g]),$.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!c))return g.on("thread-list-item.switched-to",C)},[c,C,g]),h.jsx(y,{name:"input",value:m,...f,ref:S,disabled:v,onChange:Re(i,P=>{g.composer().getState().isEditing&&_.flushSync(()=>{g.composer().setText(P.target.value)})}),onKeyDown:Re(r,b),onPaste:Re(o,A)})});jf.displayName="ComposerPrimitive.Input";const ML=()=>{const e=_.useAssistantApi(),t=_.useAssistantState(({composer:i})=>!i.canCancel),n=$.useCallback(()=>{e.composer().cancel()},[e]);return t?null:n},XE=_n("ComposerPrimitive.Cancel",ML),zL=({multiple:e=!0}={})=>{const t=_.useAssistantState(({composer:r})=>!r.isEditing),n=_.useAssistantApi(),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=a=>{const s=a.target.files;if(s){for(const u of s)n.composer().addAttachment(u);document.body.removeChild(r)}},r.oncancel=()=>{(!r.files||r.files.length===0)&&document.body.removeChild(r)},r.click()},[n,e]);return t?null:i},DL=_n("ComposerPrimitive.AddAttachment",zL,["multiple"]),UL=(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}`)}},LL=({components:e})=>{const t=_.useAssistantState(({attachment:i})=>i);if(!t)return null;const n=UL(e,t);return n?h.jsx(n,{}):null},eT=$.memo(({index:e,components:t})=>h.jsx(az,{index:e,children:h.jsx(LL,{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);eT.displayName="ComposerPrimitive.AttachmentByIndex";const tT=({components:e})=>{const t=_.useAssistantState(i=>i.composer.attachments.length);return $.useMemo(()=>Array.from({length:t},(i,r)=>h.jsx(eT,{index:r,components:e},r)),[t,e])};tT.displayName="ComposerPrimitive.Attachments";const nT=$.forwardRef((e,t)=>h.jsx(ct.div,{role:"alert",...e,ref:t}));nT.displayName="ErrorPrimitive.Root";const rT=$.forwardRef(({children:e,...t},n)=>{const i=_.useAssistantState(({message:r})=>r.status?.type==="incomplete"&&r.status.reason==="error"?r.status.error:void 0);return i===void 0?null:h.jsx(ct.span,{...t,ref:n,children:e??String(i)})});rT.displayName="ErrorPrimitive.Message";const iT=$.forwardRef((e,t)=>h.jsx(ct.div,{...e,ref:t}));iT.displayName="ThreadPrimitive.Root";const FL=e=>_.useAssistantState(({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)),no=({children:e,...t})=>FL(t)?e:null;no.displayName="ThreadPrimitive.If";const BL=e=>{const t=Et(e),n=$.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 Yo(n)},ZL=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:i=!0})=>{const r=$.useRef(null),o=Ml();e===void 0&&(e=o.getState().turnAnchor!=="top");const a=$.useRef(0),s=$.useRef(null),u=$.useCallback(p=>{const g=r.current;g&&(s.current=p,g.scrollTo({top:g.scrollHeight,behavior:p}))},[]),l=()=>{const p=r.current;if(!p)return;const g=o.getState().isAtBottom,m=Math.abs(p.scrollHeight-p.scrollTop-p.clientHeight)<1||p.scrollHeight<=p.clientHeight;!m&&a.current<p.scrollTop||(m&&(s.current=null),(m||s.current===null)&&m!==g&&Xi(o).setState({isAtBottom:m})),a.current=p.scrollTop},c=BL(()=>{const p=s.current;p?u(p):e&&o.getState().isAtBottom&&u("instant"),l()}),d=Yo(p=>(p.addEventListener("scroll",l),()=>{p.removeEventListener("scroll",l)}));return QE(({behavior:p})=>{u(p)}),hu("thread.run-start",()=>{t&&(s.current="auto",requestAnimationFrame(()=>{u("auto")}))}),hu("thread.initialize",()=>{n&&(s.current="instant",requestAnimationFrame(()=>{u("instant")}))}),hu("thread-list-item.switched-to",()=>{i&&(s.current="instant",requestAnimationFrame(()=>{u("instant")}))}),Ge(c,d,r)},qL=()=>{const e=Yi(n=>n.registerViewport),t=$.useCallback(n=>n.clientHeight,[]);return LE(e,t)},oT=$.forwardRef(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i,children:r,...o},a)=>{const s=ZL({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i}),u=qL(),l=Ge(a,s,u);return h.jsx(ct.div,{...o,ref:l,children:r})});oT.displayName="ThreadPrimitive.ViewportScrollable";const aT=$.forwardRef(({turnAnchor:e,...t},n)=>h.jsx(Pk,{options:{turnAnchor:e},children:h.jsx(oT,{...t,ref:n})}));aT.displayName="ThreadPrimitive.Viewport";const sT=(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,VL=()=>null,HL=(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??VL;default:const i=t;throw new Error(`Unknown message role: ${i}`)}},JL=({components:e})=>{const t=_.useAssistantState(({message:r})=>r.role),n=_.useAssistantState(({message:r})=>r.composer.isEditing),i=HL(e,t,n);return h.jsx(i,{})},lT=$.memo(({index:e,components:t})=>h.jsx(rz,{index:e,children:h.jsx(JL,{components:t})}),(e,t)=>e.index===t.index&&sT(e.components,t.components));lT.displayName="ThreadPrimitive.MessageByIndex";const uT=({components:e})=>{const t=_.useAssistantState(({thread:i})=>i.messages.length);return $.useMemo(()=>t===0?null:Array.from({length:t},(i,r)=>h.jsx(lT,{index:r,components:e},r)),[t,e])};uT.displayName="ThreadPrimitive.Messages";const WL=$.memo(uT,(e,t)=>sT(e.components,t.components)),GL=({behavior:e}={})=>{const t=Yi(r=>r.isAtBottom),n=Ml(),i=$.useCallback(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:i},KL=_n("ThreadPrimitive.ScrollToBottom",GL,["behavior"]),YL=({prompt:e,send:t,clearComposer:n=!0,autoSend:i,method:r})=>{const o=_.useAssistantApi(),a=_.useAssistantState(({thread:l})=>l.isDisabled),s=t??i??!1,u=$.useCallback(()=>{const l=o.thread().getState().isRunning;if(s&&!l)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,s,n,e]);return a?null:u},QL=_n("ThreadPrimitive.Suggestion",YL,["prompt","send","clearComposer","autoSend","method"]),XL=(e,t)=>{const n=$.useRef(null),i=$.useRef(null);return $.useEffect(()=>()=>{i.current?.()},[]),$.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 a=o.scrollTop,s=o.style.scrollbarWidth;o.style.scrollbarWidth="none";const u=()=>o.scrollTop=a;o.addEventListener("scroll",u);const l=setTimeout(()=>{o.removeEventListener("scroll",u),o.style.scrollbarWidth=s,i.current=null},t);i.current=()=>{clearTimeout(l),o.removeEventListener("scroll",u),o.style.scrollbarWidth=s}},[t,e])},e2=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof ts.ZodType?ts.toJSONSchema(n.parameters):n.parameters}])),t2=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let bs=null;function n2(e,t){bs={helpers:e,toolsRequiringApproval:new Set(t)}}function r2(){bs=null}const i2=(e,t)=>jM({...e,execute:async(n,i)=>{if(bs?.toolsRequiringApproval.has(t)){const{helpers:r}=bs,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 o2(e,t,n){if(!t||t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).map(([r,o])=>{if(!i.has(r))return[r,o];const a=o.execute;return a?[r,{...o,execute:async(s,u)=>{const l=u??{},c=l.toolCallId??"";return n.isToolApproved(r)||await n.requestApproval(r,c,s)?a(s,l):{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 a2=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],s2=_.createLucideIcon("arrow-down",a2);const l2=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],u2=_.createLucideIcon("arrow-up",l2);const c2=[["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"}]],d2=_.createLucideIcon("brain",c2);const p2=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Wn=_.createLucideIcon("check",p2);const f2=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_s=_.createLucideIcon("chevron-down",f2);const h2=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],m2=_.createLucideIcon("chevron-left",h2);const g2=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],cT=_.createLucideIcon("chevron-right",g2);const v2=[["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"}]],Mf=_.createLucideIcon("copy",v2);const y2=[["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"}]],b2=_.createLucideIcon("file-text",y2);const _2=[["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"}]],ws=_.createLucideIcon("loader",_2);const w2=[["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"}]],x2=_.createLucideIcon("maximize",w2);const S2=[["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"}]],I2=_.createLucideIcon("message-circle",S2);const k2=[["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"}]],E2=_.createLucideIcon("minimize",k2);const T2=[["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"}]],$2=_.createLucideIcon("panel-right-close",T2);const C2=[["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"}]],A2=_.createLucideIcon("panel-right-open",C2);const P2=[["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"}]],R2=_.createLucideIcon("pencil",P2);const O2=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N2=_.createLucideIcon("plus",O2);const j2=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],M2=_.createLucideIcon("refresh-cw",j2);const z2=[["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"}]],D2=_.createLucideIcon("settings-2",z2);const U2=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],L2=_.createLucideIcon("square",U2);const F2=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Qo=_.createLucideIcon("x",F2);var Xo=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new js({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},dT=Xo();function pg(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 lr(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 fg(e,...t){const n=new Headers(lr(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var B2=/"__proto__"\s*:/,Z2=/"constructor"\s*:/;function hg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||B2.test(e)===!1&&Z2.test(e)===!1?t:q2(t)}function q2(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 V2(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return hg(e)}try{return hg(e)}finally{Error.stackTraceLimit=t}}var xs=Symbol.for("vercel.ai.validator");function H2(e){return{[xs]:!0,validate:e}}function J2(e){return typeof e=="object"&&e!==null&&xs in e&&e[xs]===!0&&"validate"in e}function W2(e){let t;return()=>(t==null&&(t=e()),t)}function G2(e){return J2(e)?e:typeof e=="function"?e():K2(e)}function K2(e){return H2(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Cn({value:t,cause:n.issues})}})}async function mg({value:e,schema:t}){const n=await zf({value:e,schema:t});if(!n.success)throw Cn.wrap({value:e,cause:n.error});return n.value}async function zf({value:e,schema:t}){const n=G2(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:Cn.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:Cn.wrap({value:e,cause:i}),rawValue:e}}}async function Ss({text:e,schema:t}){try{const n=V2(e);return t==null?{success:!0,value:n,rawValue:n}:await zf({value:n,schema:t})}catch(n){return{success:!1,error:Gr.isInstance(n)?n:new Gr({text:e,cause:n}),rawValue:void 0}}}function Y2({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await Ss({text:n,schema:t}))}}))}async function jr(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}function Ba(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const n in t)t[n]=Ba(t[n])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Ba(t)):e.items=Ba(e.items)),e}var Q2=(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("/")},X2=Symbol("Let zodToJsonSchema decide on which parser to use"),gg={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"},e6=e=>typeof e=="string"?{...gg,name:e}:{...gg,...e};function Tt(){return{}}function t6(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)!==J.ZodAny&&(o.items=Ie(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 n6(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 r6(){return{type:"boolean"}}function pT(e,t){return Ie(e.type._def,t)}var i6=(e,t)=>Ie(e.innerType._def,t);function fT(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>fT(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 o6(e)}}var o6=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 a6(e,t){return{...Ie(e.innerType._def,t),default:e.defaultValue()}}function s6(e,t){return t.effectStrategy==="input"?Ie(e.schema._def,t):Tt()}function l6(e){return{type:"string",enum:Array.from(e.values)}}var u6=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function c6(e,t){const n=[Ie(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ie(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(u6(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:a,...s}=r;o=s}i.push(o)}}),i.length?{allOf:i}:void 0}function d6(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 $u=void 0,Vt={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:()=>($u===void 0&&($u=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$u),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 hT(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":Ht(n,"email",i.message,t);break;case"format:idn-email":Ht(n,"idn-email",i.message,t);break;case"pattern:zod":at(n,Vt.email,i.message,t);break}break;case"url":Ht(n,"uri",i.message,t);break;case"uuid":Ht(n,"uuid",i.message,t);break;case"regex":at(n,i.regex,i.message,t);break;case"cuid":at(n,Vt.cuid,i.message,t);break;case"cuid2":at(n,Vt.cuid2,i.message,t);break;case"startsWith":at(n,RegExp(`^${Cu(i.value,t)}`),i.message,t);break;case"endsWith":at(n,RegExp(`${Cu(i.value,t)}$`),i.message,t);break;case"datetime":Ht(n,"date-time",i.message,t);break;case"date":Ht(n,"date",i.message,t);break;case"time":Ht(n,"time",i.message,t);break;case"duration":Ht(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":{at(n,RegExp(Cu(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&Ht(n,"ipv4",i.message,t),i.version!=="v4"&&Ht(n,"ipv6",i.message,t);break}case"base64url":at(n,Vt.base64url,i.message,t);break;case"jwt":at(n,Vt.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&at(n,Vt.ipv4Cidr,i.message,t),i.version!=="v4"&&at(n,Vt.ipv6Cidr,i.message,t);break}case"emoji":at(n,Vt.emoji(),i.message,t);break;case"ulid":{at(n,Vt.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Ht(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{at(n,Vt.base64,i.message,t);break}}break}case"nanoid":at(n,Vt.nanoid,i.message,t)}return n}function Cu(e,t){return t.patternStrategy==="escape"?f6(e):e}var p6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function f6(e){let t="";for(let n=0;n<e.length;n++)p6.has(e[n])||(t+="\\"),t+=e[n];return t}function Ht(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 at(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:vg(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=vg(t,i)}function vg(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="",a=!1,s=!1,u=!1;for(let l=0;l<r.length;l++){if(a){o+=r[l],a=!1;continue}if(i.i){if(s){if(r[l].match(/[a-z]/)){u?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),u=!1):r[l+1]==="-"&&((n=r[l+2])!=null&&n.match(/[a-z]/))?(o+=r[l],u=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(i.m){if(r[l]==="^"){o+=`(^|(?<=[\r
|
|
72
|
+
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
|
|
73
|
+
]))`;continue}}if(i.s&&r[l]==="."){o+=s?`${r[l]}\r
|
|
74
|
+
`:`[${r[l]}\r
|
|
75
|
+
]`;continue}o+=r[l],r[l]==="\\"?a=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!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 mT(e,t){var n,i,r,o,a,s;const u={type:"object",additionalProperties:(n=Ie(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===J.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:l,...c}=hT(e.keyType._def,t);return{...u,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===J.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===J.ZodBranded&&e.keyType._def.type._def.typeName===J.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:l,...c}=pT(e.keyType._def,t);return{...u,propertyNames:c}}}return u}function h6(e,t){if(t.mapStrategy==="record")return mT(e,t);const n=Ie(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Tt(),i=Ie(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Tt();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function m6(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 g6(){return{not:Tt()}}function v6(){return{type:"null"}}var jc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function y6(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in jc&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const a=jc[o._def.typeName];return a&&!r.includes(a)?[...r,a]: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 a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];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,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._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 b6(e,t)}var b6=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>Ie(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 _6(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[jc[e.innerType._def.typeName],"null"]};const n=Ie(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function w6(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 x6(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const a in r){let s=r[a];if(s===void 0||s._def===void 0)continue;const u=I6(s),l=Ie(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);const o=S6(e,t);return o!==void 0&&(n.additionalProperties=o),n}function S6(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ie(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 I6(e){try{return e.isOptional()}catch{return!0}}var k6=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Ie(e.innerType._def,t);const i=Ie(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:Tt()},i]}:Tt()},E6=(e,t)=>{if(t.pipeStrategy==="input")return Ie(e.in._def,t);if(t.pipeStrategy==="output")return Ie(e.out._def,t);const n=Ie(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=Ie(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function T6(e,t){return Ie(e.type._def,t)}function $6(e,t){const i={type:"array",uniqueItems:!0,items:Ie(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 C6(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>Ie(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:Ie(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>Ie(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function A6(){return{not:Tt()}}function P6(){return Tt()}var R6=(e,t)=>Ie(e.innerType._def,t),O6=(e,t,n)=>{switch(t){case J.ZodString:return hT(e,n);case J.ZodNumber:return w6(e);case J.ZodObject:return x6(e,n);case J.ZodBigInt:return n6(e);case J.ZodBoolean:return r6();case J.ZodDate:return fT(e,n);case J.ZodUndefined:return A6();case J.ZodNull:return v6();case J.ZodArray:return t6(e,n);case J.ZodUnion:case J.ZodDiscriminatedUnion:return y6(e,n);case J.ZodIntersection:return c6(e,n);case J.ZodTuple:return C6(e,n);case J.ZodRecord:return mT(e,n);case J.ZodLiteral:return d6(e);case J.ZodEnum:return l6(e);case J.ZodNativeEnum:return m6(e);case J.ZodNullable:return _6(e,n);case J.ZodOptional:return k6(e,n);case J.ZodMap:return h6(e,n);case J.ZodSet:return $6(e,n);case J.ZodLazy:return()=>e.getter()._def;case J.ZodPromise:return T6(e,n);case J.ZodNaN:case J.ZodNever:return g6();case J.ZodEffects:return s6(e,n);case J.ZodAny:return Tt();case J.ZodUnknown:return P6();case J.ZodDefault:return a6(e,n);case J.ZodBranded:return pT(e,n);case J.ZodReadonly:return R6(e,n);case J.ZodCatch:return i6(e,n);case J.ZodPipeline:return E6(e,n);case J.ZodFunction:case J.ZodVoid:case J.ZodSymbol:return;default:return(i=>{})()}};function Ie(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const u=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(u!==X2)return u}if(r&&!n){const u=N6(r,t);if(u!==void 0)return u}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const a=O6(e,e.typeName,t),s=typeof a=="function"?Ie(a(),t):a;if(s&&j6(e,t,s),t.postProcess){const u=t.postProcess(s,e,t);return o.jsonSchema=s,u}return o.jsonSchema=s,s}var N6=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Q2(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`),Tt()):t.$refStrategy==="seen"?Tt():void 0}},j6=(e,t,n)=>(e.description&&(n.description=e.description),n),M6=e=>{const t=e6(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}]))}},z6=(e,t)=>{var n;const i=M6(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,d])=>{var f;return{...l,[c]:(f=Ie(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:Tt()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=Ie(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:Tt(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const u=o===void 0?r?{...a,[i.definitionPath]:r}:a:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:a}};return u.$schema="http://json-schema.org/draft-07/schema#",u},D6=z6;function U6(e,t){var n;const i=(n=void 0)!=null?n:!1;return Hl(()=>D6(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 L6(e,t){var n;const i=(n=void 0)!=null?n:!1;return Hl(()=>Ba(nl(e,{target:"draft-7",io:"input",reused:i?"ref":"inline"})),{validate:async r=>{const o=await rl(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function F6(e){return"_zod"in e}function gT(e,t){return F6(e)?L6(e):U6(e)}var Mc=Symbol.for("vercel.ai.schema");function Hl(e,{validate:t}={}){return{[Mc]:!0,_type:void 0,[xs]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function B6(e){return typeof e=="object"&&e!==null&&Mc in e&&e[Mc]===!0&&"jsonSchema"in e&&"validate"in e}function Z6(e){return e==null?Hl({properties:{},additionalProperties:!1}):B6(e)?e:typeof e=="function"?e():gT(e)}var q6=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},pr="1.9.0",yg=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function V6(e){var t=new Set([e]),n=new Set,i=e.match(yg);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(u){return u===e};function o(s){return n.add(s),!1}function a(s){return t.add(s),!0}return function(u){if(t.has(u))return!0;if(n.has(u))return!1;var l=u.match(yg);if(!l)return o(u);var c={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return c.prerelease!=null||r.major!==c.major?o(u):r.major===0?r.minor===c.minor&&r.patch<=c.patch?a(u):o(u):r.minor<=c.minor?a(u):o(u)}}var H6=V6(pr),J6=pr.split(".")[0],ro=Symbol.for("opentelemetry.js.api."+J6),io=q6;function Df(e,t,n,i){var r;i===void 0&&(i=!1);var o=io[ro]=(r=io[ro])!==null&&r!==void 0?r:{version:pr};if(!i&&o[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(o.version!==pr){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+pr);return n.error(a.stack||a.message),!1}return o[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+pr+"."),!0}function oo(e){var t,n,i=(t=io[ro])===null||t===void 0?void 0:t.version;if(!(!i||!H6(i)))return(n=io[ro])===null||n===void 0?void 0:n[e]}function Uf(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+pr+".");var n=io[ro];n&&delete n[e]}var W6=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},G6=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))},K6=(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 xi("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xi("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xi("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xi("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xi("verbose",this._namespace,t)},e})();function xi(e,t,n){var i=oo("diag");if(i)return n.unshift(t),i[e].apply(i,G6([],W6(n),!1))}var _t;(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"})(_t||(_t={}));function Y6(e,t){e<_t.NONE?e=_t.NONE:e>_t.ALL&&(e=_t.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",_t.ERROR),warn:n("warn",_t.WARN),info:n("info",_t.INFO),debug:n("debug",_t.DEBUG),verbose:n("verbose",_t.VERBOSE)}}var Q6=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},X6=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))},eF="diag",Is=(function(){function e(){function t(r){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var s=oo("diag");if(s)return s[r].apply(s,X6([],Q6(o),!1))}}var n=this,i=function(r,o){var a,s,u;if(o===void 0&&(o={logLevel:_t.INFO}),r===n){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof o=="number"&&(o={logLevel:o});var c=oo("diag"),d=Y6((s=o.logLevel)!==null&&s!==void 0?s:_t.INFO,r);if(c&&!o.suppressOverrideMessage){var f=(u=new Error().stack)!==null&&u!==void 0?u:"<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 Df("diag",d,n,!0)};n.setLogger=i,n.disable=function(){Uf(eF,n)},n.createComponentLogger=function(r){return new K6(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 tF(e){return Symbol.for(e)}var nF=(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})(),rF=new nF,iF=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},oF=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))},aF=(function(){function e(){}return e.prototype.active=function(){return rF},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,oF([i],iF(r),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),sF=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},lF=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))},Au="context",uF=new aF,vT=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Df(Au,t,Is.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,i){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(r=this._getContextManager()).with.apply(r,lF([t,n,i],sF(o),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return oo(Au)||uF},e.prototype.disable=function(){this._getContextManager().disable(),Uf(Au,Is.instance())},e})(),zc;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(zc||(zc={}));var yT="0000000000000000",bT="00000000000000000000000000000000",cF={traceId:bT,spanId:yT,traceFlags:zc.NONE},zi=(function(){function e(t){t===void 0&&(t=cF),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})(),Lf=tF("OpenTelemetry Context Key SPAN");function Ff(e){return e.getValue(Lf)||void 0}function dF(){return Ff(vT.getInstance().active())}function Bf(e,t){return e.setValue(Lf,t)}function pF(e){return e.deleteValue(Lf)}function fF(e,t){return Bf(e,new zi(t))}function _T(e){var t;return(t=Ff(e))===null||t===void 0?void 0:t.spanContext()}var hF=/^([0-9a-f]{32})$/i,mF=/^[0-9a-f]{16}$/i;function gF(e){return hF.test(e)&&e!==bT}function vF(e){return mF.test(e)&&e!==yT}function wT(e){return gF(e.traceId)&&vF(e.spanId)}function yF(e){return new zi(e)}var Pu=vT.getInstance(),xT=(function(){function e(){}return e.prototype.startSpan=function(t,n,i){i===void 0&&(i=Pu.active());var r=!!n?.root;if(r)return new zi;var o=i&&_T(i);return bF(o)&&wT(o)?new zi(o):new zi},e.prototype.startActiveSpan=function(t,n,i,r){var o,a,s;if(!(arguments.length<2)){arguments.length===2?s=n:arguments.length===3?(o=n,s=i):(o=n,a=i,s=r);var u=a??Pu.active(),l=this.startSpan(t,o,u),c=Bf(u,l);return Pu.with(c,s,void 0,l)}},e})();function bF(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var _F=new xT,wF=(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):_F},e})(),xF=(function(){function e(){}return e.prototype.getTracer=function(t,n,i){return new xT},e})(),SF=new xF,bg=(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 wF(this,t,n,i)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:SF},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})(),ks;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ks||(ks={}));var Ru="trace",IF=(function(){function e(){this._proxyTracerProvider=new bg,this.wrapSpanContext=yF,this.isSpanContextValid=wT,this.deleteSpan=pF,this.getSpan=Ff,this.getActiveSpan=dF,this.getSpanContext=_T,this.setSpan=Bf,this.setSpanContext=fF}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Df(Ru,this._proxyTracerProvider,Is.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return oo(Ru)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Uf(Ru,Is.instance()),this._proxyTracerProvider=new bg},e})(),kF=IF.getInstance(),EF=Object.defineProperty,TF=(e,t)=>{for(var n in t)EF(e,n,{get:t[n],enumerable:!0})},ST="AI_NoObjectGeneratedError",IT=`vercel.ai.error.${ST}`,$F=Symbol.for(IT),kT,_g=class extends ue{constructor({message:t="No object generated.",cause:n,text:i,response:r,usage:o,finishReason:a}){super({name:ST,message:t,cause:n}),this[kT]=!0,this.text=i,this.response=r,this.usage=o,this.finishReason=a}static isInstance(t){return ue.hasMarker(t,IT)}};kT=$F;var wg="5.0.116",ET=ae([k(),vn(Uint8Array),vn(ArrayBuffer),Fo(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]),ao=Uo(()=>ae([jo(),k(),ee(),Ee(),kt(k(),ao),W(ao)])),Fe=kt(k(),kt(k(),ao)),TT=O({type:L("text"),text:k(),providerOptions:Fe.optional()}),CF=O({type:L("image"),image:ae([ET,vn(URL)]),mediaType:k().optional(),providerOptions:Fe.optional()}),$T=O({type:L("file"),data:ae([ET,vn(URL)]),filename:k().optional(),mediaType:k(),providerOptions:Fe.optional()}),AF=O({type:L("reasoning"),text:k(),providerOptions:Fe.optional()}),PF=O({type:L("tool-call"),toolCallId:k(),toolName:k(),input:ze(),providerOptions:Fe.optional(),providerExecuted:Ee().optional()}),RF=kl("type",[O({type:L("text"),value:k()}),O({type:L("json"),value:ao}),O({type:L("error-text"),value:k()}),O({type:L("error-json"),value:ao}),O({type:L("content"),value:W(ae([O({type:L("text"),text:k()}),O({type:L("media"),data:k(),mediaType:k()})]))})]),CT=O({type:L("tool-result"),toolCallId:k(),toolName:k(),output:RF,providerOptions:Fe.optional()}),OF=O({role:L("system"),content:k(),providerOptions:Fe.optional()}),NF=O({role:L("user"),content:ae([k(),W(ae([TT,CF,$T]))]),providerOptions:Fe.optional()}),jF=O({role:L("assistant"),content:ae([k(),W(ae([TT,$T,AF,PF,CT]))]),providerOptions:Fe.optional()}),MF=O({role:L("tool"),content:W(CT),providerOptions:Fe.optional()});ae([OF,NF,jF,MF]);Xo({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
34
76
|
|
|
35
77
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
36
78
|
|
|
37
|
-
`)}})}});var HC=oP(()=>X_(G([_e({type:C("text-start"),id:w(),providerMetadata:ke.optional()}),_e({type:C("text-delta"),id:w(),delta:w(),providerMetadata:ke.optional()}),_e({type:C("text-end"),id:w(),providerMetadata:ke.optional()}),_e({type:C("error"),errorText:w()}),_e({type:C("tool-input-start"),toolCallId:w(),toolName:w(),providerExecuted:pe().optional(),dynamic:pe().optional()}),_e({type:C("tool-input-delta"),toolCallId:w(),inputTextDelta:w()}),_e({type:C("tool-input-available"),toolCallId:w(),toolName:w(),input:$e(),providerExecuted:pe().optional(),providerMetadata:ke.optional(),dynamic:pe().optional()}),_e({type:C("tool-input-error"),toolCallId:w(),toolName:w(),input:$e(),providerExecuted:pe().optional(),providerMetadata:ke.optional(),dynamic:pe().optional(),errorText:w()}),_e({type:C("tool-output-available"),toolCallId:w(),output:$e(),providerExecuted:pe().optional(),dynamic:pe().optional(),preliminary:pe().optional()}),_e({type:C("tool-output-error"),toolCallId:w(),errorText:w(),providerExecuted:pe().optional(),dynamic:pe().optional()}),_e({type:C("reasoning-start"),id:w(),providerMetadata:ke.optional()}),_e({type:C("reasoning-delta"),id:w(),delta:w(),providerMetadata:ke.optional()}),_e({type:C("reasoning-end"),id:w(),providerMetadata:ke.optional()}),_e({type:C("source-url"),sourceId:w(),url:w(),title:w().optional(),providerMetadata:ke.optional()}),_e({type:C("source-document"),sourceId:w(),mediaType:w(),title:w(),filename:w().optional(),providerMetadata:ke.optional()}),_e({type:C("file"),url:w(),mediaType:w(),providerMetadata:ke.optional()}),_e({type:So(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:w().optional(),data:$e(),transient:pe().optional()}),_e({type:C("start-step")}),_e({type:C("finish-step")}),_e({type:C("start"),messageId:w().optional(),messageMetadata:$e().optional()}),_e({type:C("finish"),finishReason:dr(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:$e().optional()}),_e({type:C("abort")}),_e({type:C("message-metadata"),messageMetadata:$e()})])));function GC(e){return e.type.startsWith("data-")}function fw(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)){const n=t[o];if(n===void 0)continue;const i=o in e?e[o]:void 0,a=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),s=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);a&&s?r[o]=fw(i,n):r[o]=n}return r}function KC(e){const t=["ROOT"];let r=-1,o=null;function n(l,u,c){switch(l){case'"':{r=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,o=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":{r=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{r=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{r=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":n(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=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":{n(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=l,t.pop();break}default:{r=l,n(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"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=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":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(o,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):r=l;break}}}let s=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(o,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function mw(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:KC(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Zr(e){return e.type.startsWith("tool-")}function YC(e){return e.type==="dynamic-tool"}function Op(e){return Zr(e)||YC(e)}function Np(e){return e.type.split("-").slice(1).join("-")}function QC({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function XC({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:o,onError:n,onToolCall:i,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,l){await o(async({state:u,write:c})=>{var d,f,p,g;function h(v){const N=u.message.parts.filter(Zr).find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(v){const N=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function y(v){var k;const N=u.message.parts.find(M=>Zr(M)&&M.toolCallId===v.toolCallId),I=v,O=N;N!=null?(N.state=v.state,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=I.rawInput,O.preliminary=I.preliminary,O.providerExecuted=(k=I.providerExecuted)!=null?k:N.providerExecuted,I.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:v.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function x(v){var k,N;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===v.toolCallId),O=v,M=I;I!=null?(I.state=v.state,M.toolName=v.toolName,M.input=O.input,M.output=O.output,M.errorText=O.errorText,M.rawInput=(k=O.rawInput)!=null?k:M.rawInput,M.preliminary=O.preliminary,M.providerExecuted=(N=O.providerExecuted)!=null?N:I.providerExecuted,O.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=O.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:v.toolName,toolCallId:v.toolCallId,state:v.state,input:O.input,output:O.output,errorText:O.errorText,preliminary:O.preliminary,providerExecuted:O.providerExecuted,...O.providerMetadata!=null?{callProviderMetadata:O.providerMetadata}:{}})}async function $(v){if(v!=null){const k=u.message.metadata!=null?fw(u.message.metadata,v):v;t!=null&&await xp({value:k,schema:t}),u.message.metadata=k}}switch(s.type){case"text-start":{const v={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeTextParts[s.id]=v,u.message.parts.push(v),c();break}case"text-delta":{const v=u.activeTextParts[s.id];v.text+=s.delta,v.providerMetadata=(d=s.providerMetadata)!=null?d:v.providerMetadata,c();break}case"text-end":{const v=u.activeTextParts[s.id];v.state="done",v.providerMetadata=(f=s.providerMetadata)!=null?f:v.providerMetadata,delete u.activeTextParts[s.id],c();break}case"reasoning-start":{const v={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeReasoningParts[s.id]=v,u.message.parts.push(v),c();break}case"reasoning-delta":{const v=u.activeReasoningParts[s.id];v.text+=s.delta,v.providerMetadata=(p=s.providerMetadata)!=null?p:v.providerMetadata,c();break}case"reasoning-end":{const v=u.activeReasoningParts[s.id];v.providerMetadata=(g=s.providerMetadata)!=null?g:v.providerMetadata,v.state="done",delete u.activeReasoningParts[s.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const v=u.message.parts.filter(Zr);u.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:v.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const v=u.partialToolCalls[s.toolCallId];v.text+=s.inputTextDelta;const{value:k}=await mw(v.text);v.dynamic?x({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}):y({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),i&&!s.providerExecuted&&await i({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-available",input:v.input,output:s.output,preliminary:s.preliminary})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Np(v),state:"output-available",input:v.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-error",input:v.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Np(v),state:"output-error",input:v.input,rawInput:v.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{s.messageId!=null&&(u.message.id=s.messageId),await $(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{s.finishReason!=null&&(u.finishReason=s.finishReason),await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{n?.(new Error(s.errorText));break}default:if(GC(s)){r?.[s.type]!=null&&await xp({value:s.data,schema:r[s.type]});const v=s;if(v.transient){a?.(v);break}const k=v.id!=null?u.message.parts.find(N=>v.type===N.type&&v.id===N.id):void 0;k!=null?k.data=v.data:u.message.parts.push(v),a?.(v),c()}}l.enqueue(s)})}}))}async function ej({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:o}=await r.read();if(o)break}}catch(o){t?.(o)}finally{r.releaseLock()}}To({prefix:"aitxt",size:24});To({prefix:"aiobj",size:24});var tj=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,r)=>{this.queue.push(async()=>{try{await e(),t()}catch(o){r(o)}}),this.processQueue()})}};To({prefix:"aiobj",size:24});var rj={};DC(rj,{object:()=>oj,text:()=>nj});var nj=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),oj=({schema:e})=>{const t=XP(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const o=await mw(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:o.value};default:{const n=o.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},o){const n=await Pi({text:r});if(!n.success)throw new Ep({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=await Cc({value:n.value,schema:t});if(!i.success)throw new Ep({message:"No object generated: response did not match schema.",cause:i.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value}}};async function ij(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:r,type:o}=t,n=await new Promise((i,a)=>{const s=new FileReader;s.onload=l=>{var u;i((u=l.target)==null?void 0:u.result)},s.onerror=l=>a(l),s.readAsDataURL(t)});return{type:"file",mediaType:o,filename:r,url:n}}))}var aj=class{constructor({api:e="/api/chat",credentials:t,headers:r,body:o,fetch:n,prepareSendMessagesRequest:i,prepareReconnectToStreamRequest:a}){this.api=e,this.credentials=t,this.headers=r,this.body=o,this.fetch=n,this.prepareSendMessagesRequest=i,this.prepareReconnectToStreamRequest=a}async sendMessages({abortSignal:e,...t}){var r,o,n,i,a;const s=await Ar(this.body),l=await Ar(this.headers),u=await Ar(this.credentials),c={...fr(l),...fr(t.headers)},d=await((r=this.prepareSendMessagesRequest)==null?void 0:r.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...s,...t.body},headers:c,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(o=d?.api)!=null?o:this.api,p=d?.headers!==void 0?fr(d.headers):c,g=d?.body!==void 0?d.body:{...s,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},h=(n=d?.credentials)!=null?n:u,y=await((i=this.fetch)!=null?i:globalThis.fetch)(f,{method:"POST",headers:_p({"Content-Type":"application/json",...p},`ai-sdk/${Tp}`,bp()),body:JSON.stringify(g),credentials:h,signal:e});if(!y.ok)throw new Error((a=await y.text())!=null?a:"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,r,o,n,i;const a=await Ar(this.body),s=await Ar(this.headers),l=await Ar(this.credentials),u={...fr(s),...fr(e.headers)},c=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...a,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),d=(r=c?.api)!=null?r:`${this.api}/${e.chatId}/stream`,f=c?.headers!==void 0?fr(c.headers):u,p=(o=c?.credentials)!=null?o:l,h=await((n=this.fetch)!=null?n:globalThis.fetch)(d,{method:"GET",headers:_p(f,`ai-sdk/${Tp}`,bp()),credentials:p});if(h.status===204)return null;if(!h.ok)throw new Error((i=await h.text())!=null?i:"Failed to fetch the chat response.");if(!h.body)throw new Error("The response body is empty.");return this.processResponseStream(h.body)}},hw=class extends aj{constructor(e={}){super(e)}processResponseStream(e){return sP({stream:e,schema:HC}).pipeThrough(new TransformStream({async transform(t,r){if(!t.success)throw t.error;r.enqueue(t.value)}}))}},sj=class{constructor({generateId:e=H_,id:t=e(),transport:r=new hw,messageMetadataSchema:o,dataPartSchemas:n,state:i,onError:a,onToolCall:s,onFinish:l,onData:u,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new tj,this.sendMessage=async(d,f)=>{var p,g,h,b;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 ij(d.files),..."text"in d&&d.text!=null?[{type:"text",text:d.text}]:[]]}:y=d,d.messageId!=null){const x=this.state.messages.findIndex($=>$.id===d.messageId);if(x===-1)throw new Error(`message with id ${d.messageId} not found`);if(this.state.messages[x].role!=="user")throw new Error(`message with id ${d.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,x+1),this.state.replaceMessage(x,{...y,id:d.messageId,role:(g=y.role)!=null?g:"user",metadata:d.metadata})}else this.state.pushMessage({...y,id:(h=y.id)!=null?h:this.generateId(),role:(b=y.role)!=null?b:"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(g=>g.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:g,errorText:h})=>this.jobExecutor.run(async()=>{var b,y;const x=this.state.messages,$=x[x.length-1];this.state.replaceMessage(x.length-1,{...$,parts:$.parts.map(v=>Op(v)&&v.toolCallId===p?{...v,state:d,output:g,errorText:h}:v)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(v=>Op(v)&&v.toolCallId===p?{...v,state:d,output:g,errorText:h}:v)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.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=r,this.generateId=e,this.messageMetadataSchema=o,this.dataPartSchemas=n,this.state=i,this.onError=a,this.onToolCall=s,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:r,body:o,messageId:n}){var i,a,s,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let c=!1,d=!1,f=!1;try{const p={state:QC({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{c=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:r,body:o});if(b==null){this.setStatus({status:"ready"});return}g=b}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:r,body:o,trigger:e,messageId:n});const h=b=>this.jobExecutor.run(()=>b({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 ej({stream:XC({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:h,onError:b=>{throw b}}),onError:b=>{throw b}}),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{(a=this.onFinish)==null||a.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,isDisconnect:d,isError:f,finishReason:(i=this.activeResponse)==null?void 0:i.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(s=this.sendAutomaticallyWhen)!=null&&s.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:r,body:o})}};const Pp=(e,t)=>{if(t==null)return[];let r=e.findIndex(o=>o.id===t);if(r===-1)throw new Error("useVercelAIThreadState: Message not found. This is likely an internal bug in assistant-ui.");for(;e[r+1]?.role==="assistant";)r++;return e.slice(0,r+1)},Cp=e=>{const r=[...e.content.filter(o=>o.type!=="file"),...e.attachments?.flatMap(o=>o.content.map(n=>({...n,filename:o.name})))??[]].map(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"file",url:o.image,...o.filename&&{filename:o.filename},mediaType:"image/png"};case"file":return{type:"file",url:o.data,mediaType:o.mimeType,...o.filename&&{filename:o.filename}};default:throw new Error(`Unsupported part type: ${o.type}`)}});return{role:e.role,parts:r}},uj=e=>new Promise((t,r)=>{const o=new FileReader;o.onload=()=>t(o.result),o.onerror=n=>r(n),o.readAsDataURL(e)}),lj={accept:"image/*, text/plain, text/html, text/markdown, text/csv, text/xml, text/json, text/css",async add({file:e}){return{id:H_(),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 uj(e.file)}]}},async remove(){}},jp=e=>L.getExternalStoreMessages(e);function cj(e){return e.replace(/[}\]"]+$/,"")}const Ss=(e,t)=>!e.parts||e.parts.length===0?[]:e.parts.filter(r=>r.type!=="step-start"&&r.type!=="file").map(r=>{const o=r.type;if(o==="text")return{type:"text",text:r.text};if(o==="reasoning")return{type:"reasoning",text:r.text};if(Zr(r)){const n=o.replace("tool-",""),i=r.toolCallId;let a={},s,l=!1;r.state==="input-streaming"||r.state==="input-available"?a=r.input||{}:r.state==="output-available"?(a=r.input||{},s=r.output):r.state==="output-error"&&(a=r.input||{},l=!0,s={error:r.errorText});let u=JSON.stringify(a);r.state==="input-streaming"&&(u=cj(u));const c=t.toolStatuses?.[i];return{type:"tool-call",toolName:n,toolCallId:i,argsText:u,args:a,result:s,isError:l,...c?.type==="interrupt"&&{interrupt:c.payload,status:{type:"requires-action",reason:"interrupt"}}}}if(o==="dynamic-tool"){const n=r.toolName,i=r.toolCallId;let a={},s,l=!1;r.state==="input-streaming"||r.state==="input-available"?a=r.input||{}:r.state==="output-available"?(a=r.input||{},s=r.output):r.state==="output-error"&&(a=r.input||{},l=!0,s={error:r.errorText});const u=t.toolStatuses?.[i];return{type:"tool-call",toolName:n,toolCallId:i,argsText:JSON.stringify(a),args:a,result:s,isError:l,...u?.type==="interrupt"&&{interrupt:u.payload,status:{type:"requires-action",reason:"interrupt"}}}}return o==="source-url"?{type:"source",sourceType:"url",id:r.sourceId,url:r.url,title:r.title||""}:o==="source-document"?(console.warn(`Source document part type ${o} is not yet supported in conversion`),null):o.startsWith("data-")?{type:"data",name:o.substring(5),data:r.data}:(console.warn(`Unsupported message part type: ${o}`),null)}).filter(Boolean),Ap=L.unstable_createMessageConverter((e,t)=>{const r=new Date;switch(e.role){case"user":return{role:"user",id:e.id,createdAt:r,content:Ss(e,t),attachments:e.parts?.filter(o=>o.type==="file").map((o,n)=>({id:n.toString(),type:o.mediaType.startsWith("image/")?"image":"file",name:o.filename??"file",content:[o.mediaType.startsWith("image/")?{type:"image",image:o.url,filename:o.filename}:{type:"file",filename:o.filename,data:o.url,mimeType:o.mediaType}],contentType:o.mediaType??"unknown/unknown",status:{type:"complete"}}))};case"system":return{role:"system",id:e.id,createdAt:r,content:Ss(e,t)};case"assistant":return{role:"assistant",id:e.id,createdAt:r,content:Ss(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}`),[]}}),dj={format:"ai-sdk/v5",encode({message:{id:e,parts:t,...r}}){return{...r,parts:t.filter(o=>o.type!=="file")}},decode(e){return{parentId:e.parent_id,message:{id:e.id,...e.content}}},getId(e){return e.id}},{MessageRepository:pj}=L.INTERNAL,fj=(e,t)=>({headId:t.headId,messages:t.messages.map(r=>{const o=e([r.message])[0];return{...r,message:o}})}),mj=(e,t,r,o,n)=>{const i=z.useRef(!1),a=L.useAssistantApi(),s=z.useCallback(()=>a.threadListItem.source?a.threadListItem():null,[a]),[l,u]=z.useState(!1),c=z.useRef(new Set),d=z.useRef(()=>n);return z.useEffect(()=>{d.current=n}),z.useEffect(()=>{if(!t||i.current)return;const f=async()=>{u(!0);try{const p=await t.withFormat?.(o).load();if(p&&p.messages.length>0){const g=fj(r,p);e.current.thread.import(g);const h=new pj;h.import(g);const b=h.getMessages();d.current(b.map(L.getExternalStoreMessages).flat()),c.current=new Set(g.messages.map(y=>y.message.id))}}catch(p){console.error("Failed to load message history:",p)}finally{u(!1)}};if(!i.current){if(i.current=!0,!s()?.getState().remoteId){u(!1);return}f()}},[a,t,o,r,e,s]),z.useEffect(()=>e.current.thread.subscribe(async()=>{const{messages:f,isRunning:p}=e.current.thread.getState();if(!p)for(let g=0;g<f.length;g++){const h=f[g];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 b=g>0?f[g-1].id:null;await t?.withFormat?.(o).append({parentId:b,message:L.getExternalStoreMessages(h)[0]})}}}),[t,o,e]),l},hj=(e,{adapters:t,toCreateMessage:r,cancelPendingToolCallsOnSend:o=!0}={})=>{const n=L.useRuntimeAdapters(),[i,a]=z.useState({}),s=Object.values(i).some(h=>h?.type==="executing"),l=e.status==="submitted"||e.status==="streaming"||s,u=Ap.useThreadMessages({isRunning:l,messages:e.messages,metadata:z.useMemo(()=>({toolStatuses:i,...e.error&&{error:e.error.message}}),[i,e.error])}),[c]=z.useState(()=>({get current(){return g}})),d=L.INTERNAL.useToolInvocations({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:a}),f=mj(c,t?.history??n?.history,Ap.toThreadMessages,dj,h=>{e.setMessages(h)}),p=async()=>{o&&(await d.abort(),e.setMessages(h=>{const b=h.at(-1);if(b?.role!=="assistant")return h;let y=!1;const x=b.parts?.map($=>!Zr($)||$.state==="output-available"||$.state==="output-error"?$:(y=!0,{...$,state:"output-error",errorText:"User cancelled tool call by sending a new message."}));return y?[...h.slice(0,-1),{...b,parts:x}]:h}))},g=L.useExternalStoreRuntime({isRunning:l,messages:u,setMessages:h=>e.setMessages(h.map(jp).filter(Boolean).flat()),onImport:h=>e.setMessages(h.map(jp).filter(Boolean).flat()),onCancel:async()=>{e.stop(),await d.abort()},onNew:async h=>{await p();const b=(r??Cp)(h);await e.sendMessage(b,{metadata:h.runConfig})},onEdit:async h=>{const b=Pp(e.messages,h.parentId);e.setMessages(b);const y=(r??Cp)(h);await e.sendMessage(y,{metadata:h.runConfig})},onReload:async(h,b)=>{const y=Pp(e.messages,h);e.setMessages(y),await e.regenerate({metadata:b.runConfig})},onAddToolResult:({toolCallId:h,result:b,isError:y})=>{y?e.addToolOutput({state:"output-error",tool:h,toolCallId:h,errorText:typeof b=="string"?b:JSON.stringify(b)}):e.addToolOutput({state:"output-available",tool:h,toolCallId:h,output:b})},onResumeToolCall:h=>d.resume(h.toolCallId,h.payload),adapters:{attachments:lj,...n,...t},isLoading:f});return g};var Is,Rp;function gj(){if(Rp)return Is;Rp=1;function e(t,r){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let o,n=0;return function(...a){clearTimeout(o);const s=Date.now(),l=s-n,u=r-l;u<=0?(n=s,t.apply(this,a)):o=setTimeout(()=>{n=Date.now(),t.apply(this,a)},u)}}return Is=e,Is}var vj=gj();const yj=eC(vj);var Vo={exports:{}},ks={};var zp;function bj(){if(zp)return ks;zp=1;var e=z;function t(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var r=typeof Object.is=="function"?Object.is:t,o=e.useState,n=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function s(d,f){var p=f(),g=o({inst:{value:p,getSnapshot:f}}),h=g[0].inst,b=g[1];return i(function(){h.value=p,h.getSnapshot=f,l(h)&&b({inst:h})},[d,p,f]),n(function(){return l(h)&&b({inst:h}),d(function(){l(h)&&b({inst:h})})},[d]),a(p),p}function l(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!r(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:s;return ks.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,ks}var Es={};var Mp;function _j(){return Mp||(Mp=1,process.env.NODE_ENV!=="production"&&(function(){function e(p,g){return p===g&&(p!==0||1/p===1/g)||p!==p&&g!==g}function t(p,g){c||n.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=g();if(!d){var b=g();i(h,b)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),d=!0)}b=a({inst:{value:h,getSnapshot:g}});var y=b[0].inst,x=b[1];return l(function(){y.value=h,y.getSnapshot=g,r(y)&&x({inst:y})},[p,h,g]),s(function(){return r(y)&&x({inst:y}),p(function(){r(y)&&x({inst:y})})},[p]),u(h),h}function r(p){var g=p.getSnapshot;p=p.value;try{var h=g();return!i(p,h)}catch{return!0}}function o(p,g){return g()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=z,i=typeof Object.is=="function"?Object.is:e,a=n.useState,s=n.useEffect,l=n.useLayoutEffect,u=n.useDebugValue,c=!1,d=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?o:t;Es.useSyncExternalStore=n.useSyncExternalStore!==void 0?n.useSyncExternalStore:f,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),Es}var Dp;function wj(){return Dp||(Dp=1,process.env.NODE_ENV==="production"?Vo.exports=bj():Vo.exports=_j()),Vo.exports}var xj=wj(),gw=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},we=(e,t,r)=>(gw(e,t,"read from private field"),r?r.call(e):t.get(e)),Ot=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Yt=(e,t,r,o)=>(gw(e,t,"write to private field"),t.set(e,r),r);function $j(e,t){return t!=null?yj(e,t):e}var it,ni,oi,kn,En,Tn,Dr,mu,hu,Sj=class{constructor(e=[]){Ot(this,it,void 0),Ot(this,ni,"ready"),Ot(this,oi,void 0),Ot(this,kn,new Set),Ot(this,En,new Set),Ot(this,Tn,new Set),this.pushMessage=t=>{Yt(this,it,we(this,it).concat(t)),we(this,Dr).call(this)},this.popMessage=()=>{Yt(this,it,we(this,it).slice(0,-1)),we(this,Dr).call(this)},this.replaceMessage=(t,r)=>{Yt(this,it,[...we(this,it).slice(0,t),this.snapshot(r),...we(this,it).slice(t+1)]),we(this,Dr).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,r)=>{const o=r?$j(t,r):t;return we(this,kn).add(o),()=>{we(this,kn).delete(o)}},this["~registerStatusCallback"]=t=>(we(this,En).add(t),()=>{we(this,En).delete(t)}),this["~registerErrorCallback"]=t=>(we(this,Tn).add(t),()=>{we(this,Tn).delete(t)}),Ot(this,Dr,()=>{we(this,kn).forEach(t=>t())}),Ot(this,mu,()=>{we(this,En).forEach(t=>t())}),Ot(this,hu,()=>{we(this,Tn).forEach(t=>t())}),Yt(this,it,e)}get status(){return we(this,ni)}set status(e){Yt(this,ni,e),we(this,mu).call(this)}get error(){return we(this,oi)}set error(e){Yt(this,oi,e),we(this,hu).call(this)}get messages(){return we(this,it)}set messages(e){Yt(this,it,[...e]),we(this,Dr).call(this)}};it=new WeakMap;ni=new WeakMap;oi=new WeakMap;kn=new WeakMap;En=new WeakMap;Tn=new WeakMap;Dr=new WeakMap;mu=new WeakMap;hu=new WeakMap;var Ur,Up=class extends sj{constructor({messages:t,...r}){const o=new Sj(t);super({...r,state:o}),Ot(this,Ur,void 0),this["~registerMessagesCallback"]=(n,i)=>we(this,Ur)["~registerMessagesCallback"](n,i),this["~registerStatusCallback"]=n=>we(this,Ur)["~registerStatusCallback"](n),this["~registerErrorCallback"]=n=>we(this,Ur)["~registerErrorCallback"](n),Yt(this,Ur,o)}};Ur=new WeakMap;function Ij({experimental_throttle:e,resume:t=!1,...r}={}){const o=z.useRef("chat"in r?r.chat:new Up(r));("chat"in r&&r.chat!==o.current||"id"in r&&o.current.id!==r.id)&&(o.current="chat"in r?r.chat:new Up(r));const i=z.useCallback(c=>o.current["~registerMessagesCallback"](c,e),[e,o.current.id]),a=z.useSyncExternalStore(i,()=>o.current.messages,()=>o.current.messages),s=z.useSyncExternalStore(o.current["~registerStatusCallback"],()=>o.current.status,()=>o.current.status),l=z.useSyncExternalStore(o.current["~registerErrorCallback"],()=>o.current.error,()=>o.current.error),u=z.useCallback(c=>{typeof c=="function"&&(c=c(o.current.messages)),o.current.messages=c},[o]);return z.useEffect(()=>{t&&o.current.resumeStream()},[t,o]),{id:o.current.id,messages:a,setMessages:u,sendMessage:o.current.sendMessage,regenerate:o.current.regenerate,clearError:o.current.clearError,stop:o.current.stop,error:l,resumeStream:o.current.resumeStream,status:s,addToolResult:o.current.addToolOutput,addToolOutput:o.current.addToolOutput}}const kj=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{...r.description?{description:r.description}:void 0,parameters:r.parameters instanceof vi.ZodType?vi.toJSONSchema(r.parameters):r.parameters}])),Ej=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));class Lp extends hw{runtime;constructor(t){super({...t,prepareSendMessagesRequest:async r=>{const o=this.runtime?.thread.getModelContext(),n=(await this.runtime?.threads.mainItem.initialize())?.remoteId??r.id,i={...r,body:{callSettings:o?.callSettings,system:o?.system,tools:kj(Ej(o?.tools??{})),...r?.body}},a=await t?.prepareSendMessagesRequest?.(i);return{...a,body:a?.body??{...i.body,id:n,messages:r.messages,trigger:r.trigger,messageId:r.messageId,metadata:r.requestMetadata}}}})}setRuntime(t){this.runtime=t}}const Tj=e=>{const t=z.useRef(e);return z.useEffect(()=>{t.current=e}),z.useMemo(()=>new Proxy(t.current,{get(o,n){const i=t.current[n];return typeof i=="function"?i.bind(t.current):i}}),[])},Oj=e=>{const{adapters:t,transport:r,toCreateMessage:o,...n}=e??{},i=Tj(r??new Lp),a=L.useAssistantState(({threadListItem:u})=>u.id),s=Ij({...n,id:a,transport:i}),l=hj(s,{adapters:t,...o&&{toCreateMessage:o}});return i instanceof Lp&&i.setRuntime(l),l},Nj=({cloud:e,...t}={})=>{const r=L.unstable_useCloudThreadListAdapter({cloud:e});return L.unstable_useRemoteThreadListRuntime({runtimeHook:function(){return Oj(t)},adapter:r,allowNesting:!0})},Pj=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{...r.description?{description:r.description}:void 0,inputSchema:Va(r.parameters)}]));var Cj=Object.defineProperty,jj=Object.defineProperties,Aj=Object.getOwnPropertyDescriptors,Zp=Object.getOwnPropertySymbols,Rj=Object.prototype.hasOwnProperty,zj=Object.prototype.propertyIsEnumerable,Fp=(e,t,r)=>t in e?Cj(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ue=(e,t)=>{for(var r in t||(t={}))Rj.call(t,r)&&Fp(e,r,t[r]);if(Zp)for(var r of Zp(t))zj.call(t,r)&&Fp(e,r,t[r]);return e},Ai=(e,t)=>jj(e,Aj(t)),vw="vercel.ai.error",Mj=Symbol.for(vw),yw,Dj=class bw extends Error{constructor({name:t,message:r,cause:o}){super(r),this[yw]=!0,this.name=t,this.cause=o}static isInstance(t){return bw.hasMarker(t,vw)}static hasMarker(t,r){const o=Symbol.for(r);return t!=null&&typeof t=="object"&&o in t&&typeof t[o]=="boolean"&&t[o]===!0}};yw=Mj;var Ne=Dj,_w="AI_APICallError",ww=`vercel.ai.error.${_w}`,Uj=Symbol.for(ww),xw,xt=class extends Ne{constructor({message:e,url:t,requestBodyValues:r,statusCode:o,responseHeaders:n,responseBody:i,cause:a,isRetryable:s=o!=null&&(o===408||o===409||o===429||o>=500),data:l}){super({name:_w,message:e,cause:a}),this[xw]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=o,this.responseHeaders=n,this.responseBody=i,this.isRetryable=s,this.data=l}static isInstance(e){return Ne.hasMarker(e,ww)}};xw=Uj;var $w="AI_EmptyResponseBodyError",Sw=`vercel.ai.error.${$w}`,Lj=Symbol.for(Sw),Iw,Zj=class extends Ne{constructor({message:e="Empty response body"}={}){super({name:$w,message:e}),this[Iw]=!0}static isInstance(e){return Ne.hasMarker(e,Sw)}};Iw=Lj;function kw(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Ew="AI_InvalidArgumentError",Tw=`vercel.ai.error.${Ew}`,Fj=Symbol.for(Tw),Ow,Nw=class extends Ne{constructor({message:t,cause:r,argument:o}){super({name:Ew,message:t,cause:r}),this[Ow]=!0,this.argument=o}static isInstance(t){return Ne.hasMarker(t,Tw)}};Ow=Fj;var Pw="AI_InvalidPromptError",Cw=`vercel.ai.error.${Pw}`,qj=Symbol.for(Cw),jw,Vj=class extends Ne{constructor({prompt:e,message:t,cause:r}){super({name:Pw,message:`Invalid prompt: ${t}`,cause:r}),this[jw]=!0,this.prompt=e}static isInstance(e){return Ne.hasMarker(e,Cw)}};jw=qj;var Aw="AI_InvalidResponseDataError",Rw=`vercel.ai.error.${Aw}`,Bj=Symbol.for(Rw),zw,wn=class extends Ne{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Aw,message:t}),this[zw]=!0,this.data=e}static isInstance(e){return Ne.hasMarker(e,Rw)}};zw=Bj;var Mw="AI_JSONParseError",Dw=`vercel.ai.error.${Mw}`,Jj=Symbol.for(Dw),Uw,Ri=class extends Ne{constructor({text:e,cause:t}){super({name:Mw,message:`JSON parsing failed: Text: ${e}.
|
|
38
|
-
Error message: ${
|
|
39
|
-
Error message: ${
|
|
40
|
-
`;break;case"id":s=
|
|
41
|
-
`)?
|
|
42
|
-
`,
|
|
43
|
-
`&&
|
|
79
|
+
`)}})}});var zF=W2(()=>gT(ae([je({type:L("text-start"),id:k(),providerMetadata:Fe.optional()}),je({type:L("text-delta"),id:k(),delta:k(),providerMetadata:Fe.optional()}),je({type:L("text-end"),id:k(),providerMetadata:Fe.optional()}),je({type:L("error"),errorText:k()}),je({type:L("tool-input-start"),toolCallId:k(),toolName:k(),providerExecuted:Ee().optional(),dynamic:Ee().optional()}),je({type:L("tool-input-delta"),toolCallId:k(),inputTextDelta:k()}),je({type:L("tool-input-available"),toolCallId:k(),toolName:k(),input:ze(),providerExecuted:Ee().optional(),providerMetadata:Fe.optional(),dynamic:Ee().optional()}),je({type:L("tool-input-error"),toolCallId:k(),toolName:k(),input:ze(),providerExecuted:Ee().optional(),providerMetadata:Fe.optional(),dynamic:Ee().optional(),errorText:k()}),je({type:L("tool-output-available"),toolCallId:k(),output:ze(),providerExecuted:Ee().optional(),dynamic:Ee().optional(),preliminary:Ee().optional()}),je({type:L("tool-output-error"),toolCallId:k(),errorText:k(),providerExecuted:Ee().optional(),dynamic:Ee().optional()}),je({type:L("reasoning-start"),id:k(),providerMetadata:Fe.optional()}),je({type:L("reasoning-delta"),id:k(),delta:k(),providerMetadata:Fe.optional()}),je({type:L("reasoning-end"),id:k(),providerMetadata:Fe.optional()}),je({type:L("source-url"),sourceId:k(),url:k(),title:k().optional(),providerMetadata:Fe.optional()}),je({type:L("source-document"),sourceId:k(),mediaType:k(),title:k(),filename:k().optional(),providerMetadata:Fe.optional()}),je({type:L("file"),url:k(),mediaType:k(),providerMetadata:Fe.optional()}),je({type:Fo(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:k().optional(),data:ze(),transient:Ee().optional()}),je({type:L("start-step")}),je({type:L("finish-step")}),je({type:L("start"),messageId:k().optional(),messageMetadata:ze().optional()}),je({type:L("finish"),finishReason:nr(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:ze().optional()}),je({type:L("abort")}),je({type:L("message-metadata"),messageMetadata:ze()})])));function DF(e){return e.type.startsWith("data-")}function AT(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,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&s?n[i]=AT(o,r):n[i]=r}return n}function UF(e){const t=["ROOT"];let n=-1,i=null;function r(u,l,c){switch(u){case'"':{n=l,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=l,i=l,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=l,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=l,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=l,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=l,t.pop();break}}}function a(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}}}for(let u=0;u<e.length;u++){const l=e[u];switch(t[t.length-1]){case"ROOT":r(l,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(l,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,u);break}case"INSIDE_STRING":{switch(l){case'"':{t.pop(),n=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=u}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{n=u,t.pop();break}default:{n=u,r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}default:{n=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=u;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,u+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u)):n=u;break}}}let s=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function PT(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ss({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ss({text:UF(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function qr(e){return e.type.startsWith("tool-")}function LF(e){return e.type==="dynamic-tool"}function xg(e){return qr(e)||LF(e)}function Sg(e){return e.type.split("-").slice(1).join("-")}function FF({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function BF({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,u){await i(async({state:l,write:c})=>{var d,f,p,g;function m(b){const E=l.message.parts.filter(qr).find(C=>C.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(b){const E=l.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function v(b){var A;const E=l.message.parts.find(j=>qr(j)&&j.toolCallId===b.toolCallId),C=b,P=E;E!=null?(E.state=b.state,P.input=C.input,P.output=C.output,P.errorText=C.errorText,P.rawInput=C.rawInput,P.preliminary=C.preliminary,P.providerExecuted=(A=C.providerExecuted)!=null?A:E.providerExecuted,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function x(b){var A,E;const C=l.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===b.toolCallId),P=b,j=C;C!=null?(C.state=b.state,j.toolName=b.toolName,j.input=P.input,j.output=P.output,j.errorText=P.errorText,j.rawInput=(A=P.rawInput)!=null?A:j.rawInput,j.preliminary=P.preliminary,j.providerExecuted=(E=P.providerExecuted)!=null?E:C.providerExecuted,P.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=P.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:P.input,output:P.output,errorText:P.errorText,preliminary:P.preliminary,providerExecuted:P.providerExecuted,...P.providerMetadata!=null?{callProviderMetadata:P.providerMetadata}:{}})}async function S(b){if(b!=null){const A=l.message.metadata!=null?AT(l.message.metadata,b):b;t!=null&&await mg({value:A,schema:t}),l.message.metadata=A}}switch(s.type){case"text-start":{const b={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeTextParts[s.id]=b,l.message.parts.push(b),c();break}case"text-delta":{const b=l.activeTextParts[s.id];b.text+=s.delta,b.providerMetadata=(d=s.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=l.activeTextParts[s.id];b.state="done",b.providerMetadata=(f=s.providerMetadata)!=null?f:b.providerMetadata,delete l.activeTextParts[s.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeReasoningParts[s.id]=b,l.message.parts.push(b),c();break}case"reasoning-delta":{const b=l.activeReasoningParts[s.id];b.text+=s.delta,b.providerMetadata=(p=s.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=l.activeReasoningParts[s.id];b.providerMetadata=(g=s.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete l.activeReasoningParts[s.id],c();break}case"file":{l.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const b=l.message.parts.filter(qr);l.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:b.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const b=l.partialToolCalls[s.toolCallId];b.text+=s.inputTextDelta;const{value:A}=await PT(b.text);b.dynamic?x({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:A}):v({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:A}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),o&&!s.providerExecuted&&await o({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const b=y(s.toolCallId);x({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:s.output,preliminary:s.preliminary})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:Sg(b),state:"output-available",input:b.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const b=y(s.toolCallId);x({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:Sg(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{s.messageId!=null&&(l.message.id=s.messageId),await S(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{s.finishReason!=null&&(l.finishReason=s.finishReason),await S(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await S(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(DF(s)){n?.[s.type]!=null&&await mg({value:s.data,schema:n[s.type]});const b=s;if(b.transient){a?.(b);break}const A=b.id!=null?l.message.parts.find(E=>b.type===E.type&&b.id===E.id):void 0;A!=null?A.data=b.data:l.message.parts.push(b),a?.(b),c()}}u.enqueue(s)})}}))}async function ZF({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()}}Xo({prefix:"aitxt",size:24});Xo({prefix:"aiobj",size:24});var qF=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()})}};Xo({prefix:"aiobj",size:24});var VF={};TF(VF,{object:()=>JF,text:()=>HF});var HF=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),JF=({schema:e})=>{const t=Z6(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await PT(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 Ss({text:n});if(!r.success)throw new _g({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 zf({value:r.value,schema:t});if(!o.success)throw new _g({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 WF(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,a)=>{const s=new FileReader;s.onload=u=>{var l;o((l=u.target)==null?void 0:l.result)},s.onerror=u=>a(u),s.readAsDataURL(t)});return{type:"file",mediaType:i,filename:n,url:r}}))}var GF=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:i,fetch:r,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:a}){this.api=e,this.credentials=t,this.headers=n,this.body=i,this.fetch=r,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=a}async sendMessages({abortSignal:e,...t}){var n,i,r,o,a;const s=await jr(this.body),u=await jr(this.headers),l=await jr(this.credentials),c={...lr(u),...lr(t.headers)},d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...s,...t.body},headers:c,credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(i=d?.api)!=null?i:this.api,p=d?.headers!==void 0?lr(d.headers):c,g=d?.body!==void 0?d.body:{...s,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(r=d?.credentials)!=null?r:l,v=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:fg({"Content-Type":"application/json",...p},`ai-sdk/${wg}`,pg()),body:JSON.stringify(g),credentials:m,signal:e});if(!v.ok)throw new Error((a=await v.text())!=null?a:"Failed to fetch the chat response.");if(!v.body)throw new Error("The response body is empty.");return this.processResponseStream(v.body)}async reconnectToStream(e){var t,n,i,r,o;const a=await jr(this.body),s=await jr(this.headers),u=await jr(this.credentials),l={...lr(s),...lr(e.headers)},c=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...a,...e.body},headers:l,credentials:u,requestMetadata:e.metadata})),d=(n=c?.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=c?.headers!==void 0?lr(c.headers):l,p=(i=c?.credentials)!=null?i:u,m=await((r=this.fetch)!=null?r:globalThis.fetch)(d,{method:"GET",headers:fg(f,`ai-sdk/${wg}`,pg()),credentials:p});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},RT=class extends GF{constructor(e={}){super(e)}processResponseStream(e){return Y2({stream:e,schema:zF}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},KF=class{constructor({generateId:e=dT,id:t=e(),transport:n=new RT,messageMetadataSchema:i,dataPartSchemas:r,state:o,onError:a,onToolCall:s,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new qF,this.sendMessage=async(d,f)=>{var p,g,m,y;if(d==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...f});return}let v;if("text"in d||"files"in d?v={parts:[...Array.isArray(d.files)?d.files:await WF(d.files),..."text"in d&&d.text!=null?[{type:"text",text:d.text}]:[]]}:v=d,d.messageId!=null){const x=this.state.messages.findIndex(S=>S.id===d.messageId);if(x===-1)throw new Error(`message with id ${d.messageId} not found`);if(this.state.messages[x].role!=="user")throw new Error(`message with id ${d.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,x+1),this.state.replaceMessage(x,{...v,id:d.messageId,role:(g=v.role)!=null?g:"user",metadata:d.metadata})}else this.state.pushMessage({...v,id:(m=v.id)!=null?m:this.generateId(),role:(y=v.role)!=null?y:"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(g=>g.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:g,errorText:m})=>this.jobExecutor.run(async()=>{var y,v;const x=this.state.messages,S=x[x.length-1];this.state.replaceMessage(x.length-1,{...S,parts:S.parts.map(b=>xg(b)&&b.toolCallId===p?{...b,state:d,output:g,errorText:m}:b)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(b=>xg(b)&&b.toolCallId===p?{...b,state:d,output:g,errorText:m}:b)),this.status!=="streaming"&&this.status!=="submitted"&&((y=this.sendAutomaticallyWhen)!=null&&y.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(v=this.lastMessage)==null?void 0:v.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=a,this.onToolCall=s,this.onFinish=u,this.onData=l,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,a,s,u;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let c=!1,d=!1,f=!1;try{const p={state:FF({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{c=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const y=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:i});if(y==null){this.setStatus({status:"ready"});return}g=y}else g=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 m=y=>this.jobExecutor.run(()=>y({state:p.state,write:()=>{var v;this.setStatus({status:"streaming"}),p.state.message.id===((v=this.lastMessage)==null?void 0:v.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await ZF({stream:BF({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:y=>{throw y}}),onError:y=>{throw y}}),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{(a=this.onFinish)==null||a.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}(s=this.sendAutomaticallyWhen)!=null&&s.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(u=this.lastMessage)==null?void 0:u.id,metadata:t,headers:n,body:i})}};const Ig=(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)},kg=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}},YF=e=>new Promise((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=r=>n(r),i.readAsDataURL(e)}),QF={accept:"image/*, text/plain, text/html, text/markdown, text/csv, text/xml, text/json, text/css",async add({file:e}){return{id:dT(),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 YF(e.file)}]}},async remove(){}},Eg=e=>hr(e);function XF(e){return e.replace(/[}\]"]+$/,"")}const Ou=(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(qr(n)){const r=i.replace("tool-",""),o=n.toolCallId;let a={},s,u=!1;n.state==="input-streaming"||n.state==="input-available"?a=n.input||{}:n.state==="output-available"?(a=n.input||{},s=n.output):n.state==="output-error"&&(a=n.input||{},u=!0,s={error:n.errorText});let l=JSON.stringify(a);n.state==="input-streaming"&&(l=XF(l));const c=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:l,args:a,result:s,isError:u,...c?.type==="interrupt"&&{interrupt:c.payload,status:{type:"requires-action",reason:"interrupt"}}}}if(i==="dynamic-tool"){const r=n.toolName,o=n.toolCallId;let a={},s,u=!1;n.state==="input-streaming"||n.state==="input-available"?a=n.input||{}:n.state==="output-available"?(a=n.input||{},s=n.output):n.state==="output-error"&&(a=n.input||{},u=!0,s={error:n.errorText});const l=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:JSON.stringify(a),args:a,result:s,isError:u,...l?.type==="interrupt"&&{interrupt:l.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),Tg=uz((e,t)=>{const n=new Date;switch(e.role){case"user":return{role:"user",id:e.id,createdAt:n,content:Ou(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:Ou(e,t)};case"assistant":return{role:"assistant",id:e.id,createdAt:n,content:Ou(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}`),[]}}),eB={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:tB}=Mk,nB=(e,t)=>({headId:t.headId,messages:t.messages.map(n=>{const i=e([n.message])[0];return{...n,message:i}})}),rB=(e,t,n,i,r)=>{const o=$.useRef(!1),a=_.useAssistantApi(),s=$.useCallback(()=>a.threadListItem.source?a.threadListItem():null,[a]),[u,l]=$.useState(!1),c=$.useRef(new Set),d=$.useRef(()=>r);return $.useEffect(()=>{d.current=r}),$.useEffect(()=>{if(!t||o.current)return;const f=async()=>{l(!0);try{const p=await t.withFormat?.(i).load();if(p&&p.messages.length>0){const g=nB(n,p);e.current.thread.import(g);const m=new tB;m.import(g);const y=m.getMessages();d.current(y.map(hr).flat()),c.current=new Set(g.messages.map(v=>v.message.id))}}catch(p){console.error("Failed to load message history:",p)}finally{l(!1)}};if(!o.current){if(o.current=!0,!s()?.getState().remoteId){l(!1);return}f()}},[a,t,i,n,e,s]),$.useEffect(()=>e.current.thread.subscribe(async()=>{const{messages:f,isRunning:p}=e.current.thread.getState();if(!p)for(let g=0;g<f.length;g++){const m=f[g];if(m.status===void 0||m.status.type==="complete"||m.status.type==="incomplete"){if(c.current.has(m.id))continue;c.current.add(m.id);const y=g>0?f[g-1].id:null;await t?.withFormat?.(i).append({parentId:y,message:hr(m)[0]})}}}),[t,i,e]),u},iB=(e,{adapters:t,toCreateMessage:n,cancelPendingToolCallsOnSend:i=!0}={})=>{const r=xk(),[o,a]=$.useState({}),s=Object.values(o).some(m=>m?.type==="executing"),u=e.status==="submitted"||e.status==="streaming"||s,l=Tg.useThreadMessages({isRunning:u,messages:e.messages,metadata:$.useMemo(()=>({toolStatuses:o,...e.error&&{error:e.error.message}}),[o,e.error])}),[c]=$.useState(()=>({get current(){return g}})),d=Ik({state:{messages:l,isRunning:u},getTools:()=>c.current.thread.getModelContext().tools,onResult:m=>{m.type==="add-tool-result"&&e.addToolResult({tool:m.toolName,toolCallId:m.toolCallId,output:m.result})},setToolStatuses:a}),f=rB(c,t?.history??r?.history,Tg.toThreadMessages,eB,m=>{e.setMessages(m)}),p=async()=>{i&&(await d.abort(),e.setMessages(m=>{const y=m.at(-1);if(y?.role!=="assistant")return m;let v=!1;const x=y.parts?.map(S=>!qr(S)||S.state==="output-available"||S.state==="output-error"?S:(v=!0,{...S,state:"output-error",errorText:"User cancelled tool call by sending a new message."}));return v?[...m.slice(0,-1),{...y,parts:x}]:m}))},g=PM({isRunning:u,messages:l,setMessages:m=>e.setMessages(m.map(Eg).filter(Boolean).flat()),onImport:m=>e.setMessages(m.map(Eg).filter(Boolean).flat()),onCancel:async()=>{e.stop(),await d.abort()},onNew:async m=>{await p();const y=(n??kg)(m);await e.sendMessage(y,{metadata:m.runConfig})},onEdit:async m=>{const y=Ig(e.messages,m.parentId);e.setMessages(y);const v=(n??kg)(m);await e.sendMessage(v,{metadata:m.runConfig})},onReload:async(m,y)=>{const v=Ig(e.messages,m);e.setMessages(v),await e.regenerate({metadata:y.runConfig})},onAddToolResult:({toolCallId:m,result:y,isError:v})=>{v?e.addToolOutput({state:"output-error",tool:m,toolCallId:m,errorText:typeof y=="string"?y:JSON.stringify(y)}):e.addToolOutput({state:"output-available",tool:m,toolCallId:m,output:y})},onResumeToolCall:m=>d.resume(m.toolCallId,m.payload),adapters:{attachments:QF,...r,...t},isLoading:f});return g};var Nu,$g;function oB(){if($g)return Nu;$g=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(...a){clearTimeout(i);const s=Date.now(),u=s-r,l=n-u;l<=0?(r=s,t.apply(this,a)):i=setTimeout(()=>{r=Date.now(),t.apply(this,a)},l)}}return Nu=e,Nu}var aB=oB();const sB=Ho(aB);var Ea={exports:{}},ju={};var Cg;function lB(){if(Cg)return ju;Cg=1;var e=$;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,a=e.useDebugValue;function s(d,f){var p=f(),g=i({inst:{value:p,getSnapshot:f}}),m=g[0].inst,y=g[1];return o(function(){m.value=p,m.getSnapshot=f,u(m)&&y({inst:m})},[d,p,f]),r(function(){return u(m)&&y({inst:m}),d(function(){u(m)&&y({inst:m})})},[d]),a(p),p}function u(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!n(d,p)}catch{return!0}}function l(d,f){return f()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:s;return ju.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,ju}var Mu={};var Ag;function uB(){return Ag||(Ag=1,process.env.NODE_ENV!=="production"&&(function(){function e(p,g){return p===g&&(p!==0||1/p===1/g)||p!==p&&g!==g}function t(p,g){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 m=g();if(!d){var y=g();o(m,y)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),d=!0)}y=a({inst:{value:m,getSnapshot:g}});var v=y[0].inst,x=y[1];return u(function(){v.value=m,v.getSnapshot=g,n(v)&&x({inst:v})},[p,m,g]),s(function(){return n(v)&&x({inst:v}),p(function(){n(v)&&x({inst:v})})},[p]),l(m),m}function n(p){var g=p.getSnapshot;p=p.value;try{var m=g();return!o(p,m)}catch{return!0}}function i(p,g){return g()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=$,o=typeof Object.is=="function"?Object.is:e,a=r.useState,s=r.useEffect,u=r.useLayoutEffect,l=r.useDebugValue,c=!1,d=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?i:t;Mu.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())})()),Mu}var Pg;function cB(){return Pg||(Pg=1,process.env.NODE_ENV==="production"?Ea.exports=lB():Ea.exports=uB()),Ea.exports}var dB=cB(),OT=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Me=(e,t,n)=>(OT(e,t,"read from private field"),n?n.call(e):t.get(e)),un=(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)},Zn=(e,t,n,i)=>(OT(e,t,"write to private field"),t.set(e,n),n);function pB(e,t){return t!=null?sB(e,t):e}var jt,Za,qa,Ri,Oi,Ni,Dr,Dc,Uc,fB=class{constructor(e=[]){un(this,jt,void 0),un(this,Za,"ready"),un(this,qa,void 0),un(this,Ri,new Set),un(this,Oi,new Set),un(this,Ni,new Set),this.pushMessage=t=>{Zn(this,jt,Me(this,jt).concat(t)),Me(this,Dr).call(this)},this.popMessage=()=>{Zn(this,jt,Me(this,jt).slice(0,-1)),Me(this,Dr).call(this)},this.replaceMessage=(t,n)=>{Zn(this,jt,[...Me(this,jt).slice(0,t),this.snapshot(n),...Me(this,jt).slice(t+1)]),Me(this,Dr).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const i=n?pB(t,n):t;return Me(this,Ri).add(i),()=>{Me(this,Ri).delete(i)}},this["~registerStatusCallback"]=t=>(Me(this,Oi).add(t),()=>{Me(this,Oi).delete(t)}),this["~registerErrorCallback"]=t=>(Me(this,Ni).add(t),()=>{Me(this,Ni).delete(t)}),un(this,Dr,()=>{Me(this,Ri).forEach(t=>t())}),un(this,Dc,()=>{Me(this,Oi).forEach(t=>t())}),un(this,Uc,()=>{Me(this,Ni).forEach(t=>t())}),Zn(this,jt,e)}get status(){return Me(this,Za)}set status(e){Zn(this,Za,e),Me(this,Dc).call(this)}get error(){return Me(this,qa)}set error(e){Zn(this,qa,e),Me(this,Uc).call(this)}get messages(){return Me(this,jt)}set messages(e){Zn(this,jt,[...e]),Me(this,Dr).call(this)}};jt=new WeakMap;Za=new WeakMap;qa=new WeakMap;Ri=new WeakMap;Oi=new WeakMap;Ni=new WeakMap;Dr=new WeakMap;Dc=new WeakMap;Uc=new WeakMap;var Ur,Rg=class extends KF{constructor({messages:t,...n}){const i=new fB(t);super({...n,state:i}),un(this,Ur,void 0),this["~registerMessagesCallback"]=(r,o)=>Me(this,Ur)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>Me(this,Ur)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Me(this,Ur)["~registerErrorCallback"](r),Zn(this,Ur,i)}};Ur=new WeakMap;function hB({experimental_throttle:e,resume:t=!1,...n}={}){const i=$.useRef("chat"in n?n.chat:new Rg(n));("chat"in n&&n.chat!==i.current||"id"in n&&i.current.id!==n.id)&&(i.current="chat"in n?n.chat:new Rg(n));const o=$.useCallback(c=>i.current["~registerMessagesCallback"](c,e),[e,i.current.id]),a=$.useSyncExternalStore(o,()=>i.current.messages,()=>i.current.messages),s=$.useSyncExternalStore(i.current["~registerStatusCallback"],()=>i.current.status,()=>i.current.status),u=$.useSyncExternalStore(i.current["~registerErrorCallback"],()=>i.current.error,()=>i.current.error),l=$.useCallback(c=>{typeof c=="function"&&(c=c(i.current.messages)),i.current.messages=c},[i]);return $.useEffect(()=>{t&&i.current.resumeStream()},[t,i]),{id:i.current.id,messages:a,setMessages:l,sendMessage:i.current.sendMessage,regenerate:i.current.regenerate,clearError:i.current.clearError,stop:i.current.stop,error:u,resumeStream:i.current.resumeStream,status:s,addToolResult:i.current.addToolOutput,addToolOutput:i.current.addToolOutput}}const mB=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof ts.ZodType?ts.toJSONSchema(n.parameters):n.parameters}])),gB=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));class Og extends RT{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:mB(gB(i?.tools??{})),...n?.body}},a=await t?.prepareSendMessagesRequest?.(o);return{...a,body:a?.body??{...o.body,id:r,messages:n.messages,trigger:n.trigger,messageId:n.messageId,metadata:n.requestMetadata}}}})}setRuntime(t){this.runtime=t}}const vB=e=>{const t=$.useRef(e);return $.useEffect(()=>{t.current=e}),$.useMemo(()=>new Proxy(t.current,{get(i,r){const o=t.current[r];return typeof o=="function"?o.bind(t.current):o}}),[])},yB=e=>{const{adapters:t,transport:n,toCreateMessage:i,...r}=e??{},o=vB(n??new Og),a=_.useAssistantState(({threadListItem:l})=>l.id),s=hB({...r,id:a,transport:o}),u=iB(s,{adapters:t,...i&&{toCreateMessage:i}});return o instanceof Og&&o.setRuntime(u),u},bB=({cloud:e,...t}={})=>{const n=kz({cloud:e});return Uz({runtimeHook:function(){return yB(t)},adapter:n,allowNesting:!0})},_B=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,inputSchema:Hl(n.parameters)}]));var wB=Object.defineProperty,xB=Object.defineProperties,SB=Object.getOwnPropertyDescriptors,Ng=Object.getOwnPropertySymbols,IB=Object.prototype.hasOwnProperty,kB=Object.prototype.propertyIsEnumerable,jg=(e,t,n)=>t in e?wB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Se=(e,t)=>{for(var n in t||(t={}))IB.call(t,n)&&jg(e,n,t[n]);if(Ng)for(var n of Ng(t))kB.call(t,n)&&jg(e,n,t[n]);return e},Es=(e,t)=>xB(e,SB(t)),NT="vercel.ai.error",EB=Symbol.for(NT),jT,TB=class MT extends Error{constructor({name:t,message:n,cause:i}){super(n),this[jT]=!0,this.name=t,this.cause=i}static isInstance(t){return MT.hasMarker(t,NT)}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}};jT=EB;var Ve=TB,zT="AI_APICallError",DT=`vercel.ai.error.${zT}`,$B=Symbol.for(DT),UT,Xt=class extends Ve{constructor({message:e,url:t,requestBodyValues:n,statusCode:i,responseHeaders:r,responseBody:o,cause:a,isRetryable:s=i!=null&&(i===408||i===409||i===429||i>=500),data:u}){super({name:zT,message:e,cause:a}),this[UT]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=i,this.responseHeaders=r,this.responseBody=o,this.isRetryable=s,this.data=u}static isInstance(e){return Ve.hasMarker(e,DT)}};UT=$B;var LT="AI_EmptyResponseBodyError",FT=`vercel.ai.error.${LT}`,CB=Symbol.for(FT),BT,AB=class extends Ve{constructor({message:e="Empty response body"}={}){super({name:LT,message:e}),this[BT]=!0}static isInstance(e){return Ve.hasMarker(e,FT)}};BT=CB;function ZT(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var qT="AI_InvalidArgumentError",VT=`vercel.ai.error.${qT}`,PB=Symbol.for(VT),HT,JT=class extends Ve{constructor({message:t,cause:n,argument:i}){super({name:qT,message:t,cause:n}),this[HT]=!0,this.argument=i}static isInstance(t){return Ve.hasMarker(t,VT)}};HT=PB;var WT="AI_InvalidPromptError",GT=`vercel.ai.error.${WT}`,RB=Symbol.for(GT),KT,OB=class extends Ve{constructor({prompt:e,message:t,cause:n}){super({name:WT,message:`Invalid prompt: ${t}`,cause:n}),this[KT]=!0,this.prompt=e}static isInstance(e){return Ve.hasMarker(e,GT)}};KT=RB;var YT="AI_InvalidResponseDataError",QT=`vercel.ai.error.${YT}`,NB=Symbol.for(QT),XT,Si=class extends Ve{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:YT,message:t}),this[XT]=!0,this.data=e}static isInstance(e){return Ve.hasMarker(e,QT)}};XT=NB;var e0="AI_JSONParseError",t0=`vercel.ai.error.${e0}`,jB=Symbol.for(t0),n0,Ts=class extends Ve{constructor({text:e,cause:t}){super({name:e0,message:`JSON parsing failed: Text: ${e}.
|
|
80
|
+
Error message: ${ZT(t)}`,cause:t}),this[n0]=!0,this.text=e}static isInstance(e){return Ve.hasMarker(e,t0)}};n0=jB;var r0="AI_LoadAPIKeyError",i0=`vercel.ai.error.${r0}`,MB=Symbol.for(i0),o0,Ta=class extends Ve{constructor({message:e}){super({name:r0,message:e}),this[o0]=!0}static isInstance(e){return Ve.hasMarker(e,i0)}};o0=MB;var a0="AI_NoContentGeneratedError",s0=`vercel.ai.error.${a0}`,zB=Symbol.for(s0),l0,u0=class extends Ve{constructor({message:e="No content generated."}={}){super({name:a0,message:e}),this[l0]=!0}static isInstance(e){return Ve.hasMarker(e,s0)}};l0=zB;var c0="AI_TypeValidationError",d0=`vercel.ai.error.${c0}`,DB=Symbol.for(d0),p0,UB=class Lc extends Ve{constructor({value:t,cause:n}){super({name:c0,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
81
|
+
Error message: ${ZT(n)}`,cause:n}),this[p0]=!0,this.value=t}static isInstance(t){return Ve.hasMarker(t,d0)}static wrap({value:t,cause:n}){return Lc.isInstance(n)&&n.value===t?n:new Lc({value:t,cause:n})}};p0=DB;var so=UB,f0="AI_UnsupportedFunctionalityError",h0=`vercel.ai.error.${f0}`,LB=Symbol.for(h0),m0,qn=class extends Ve{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:f0,message:t}),this[m0]=!0,this.functionality=e}static isInstance(e){return Ve.hasMarker(e,h0)}};m0=LB;var Mg=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 zu(e){}function FB(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=zu,onError:n=zu,onRetry:i=zu,onComment:r}=e;let o="",a=!0,s,u="",l="";function c(m){const y=a?m.replace(/^\xEF\xBB\xBF/,""):m,[v,x]=BB(`${o}${y}`);for(const S of v)d(S);o=x,a=!1}function d(m){if(m===""){p();return}if(m.startsWith(":")){r&&r(m.slice(m.startsWith(": ")?2:1));return}const y=m.indexOf(":");if(y!==-1){const v=m.slice(0,y),x=m[y+1]===" "?2:1,S=m.slice(y+x);f(v,S,m);return}f(m,"",m)}function f(m,y,v){switch(m){case"event":l=y;break;case"data":u=`${u}${y}
|
|
82
|
+
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?i(parseInt(y,10)):n(new Mg(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:n(new Mg(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:y,line:v}));break}}function p(){u.length>0&&t({id:s,event:l||void 0,data:u.endsWith(`
|
|
83
|
+
`)?u.slice(0,-1):u}),s=void 0,u="",l=""}function g(m={}){o&&m.consume&&d(o),a=!0,s=void 0,u="",l="",o=""}return{feed:c,reset:g}}function BB(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
84
|
+
`,i);let a=-1;if(r!==-1&&o!==-1?a=Math.min(r,o):r!==-1?a=r:o!==-1&&(a=o),a===-1){n=e.slice(i);break}else{const s=e.slice(i,a);t.push(s),i=a+1,e[i-1]==="\r"&&e[i]===`
|
|
85
|
+
`&&i++}}return[t,n]}var ZB=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let i;super({start(r){i=FB({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 lo(...e){return e.reduce((t,n)=>Se(Se({},t),n??{}),{})}function Jl(e){return Object.fromEntries([...e.headers])}var qB=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new JT({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},Gt=qB();function Fc(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var VB=["fetch failed","failed to fetch"];function HB({error:e,url:t,requestBodyValues:n}){if(Fc(e))return e;if(e instanceof TypeError&&VB.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new Xt({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function JB(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function WB({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:i}){if(typeof e=="string")return e;if(e!=null)throw new Ta({message:`${i} API key must be a string.`});if(typeof process>"u")throw new Ta({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 Ta({message:`${i} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ta({message:`${i} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var GB=/"__proto__"\s*:/,KB=/"constructor"\s*:/;function YB(e){const t=JSON.parse(e);return t===null||typeof t!="object"||GB.test(e)===!1&&KB.test(e)===!1?t:QB(t)}function QB(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 Zf(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return YB(e)}finally{Error.stackTraceLimit=t}}var Bc=Symbol.for("vercel.ai.validator");function XB(e){return{[Bc]:!0,validate:e}}function eZ(e){return typeof e=="object"&&e!==null&&Bc in e&&e[Bc]===!0&&"validate"in e}function tZ(e){return eZ(e)?e:nZ(e)}function nZ(e){return XB(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new so({value:t,cause:n.issues})}})}async function rZ({value:e,schema:t}){const n=await g0({value:e,schema:t});if(!n.success)throw so.wrap({value:e,cause:n.error});return n.value}async function g0({value:e,schema:t}){const n=tZ(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:so.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:so.wrap({value:e,cause:i}),rawValue:e}}}async function iZ({text:e,schema:t}){try{const n=Zf(e);return t==null?n:rZ({value:n,schema:t})}catch(n){throw Ts.isInstance(n)||so.isInstance(n)?n:new Ts({text:e,cause:n})}}async function v0({text:e,schema:t}){try{const n=Zf(e);return t==null?{success:!0,value:n,rawValue:n}:await g0({value:n,schema:t})}catch(n){return{success:!1,error:Ts.isInstance(n)?n:new Ts({text:e,cause:n}),rawValue:void 0}}}function Du(e){try{return Zf(e),!0}catch{return!1}}function oZ({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ZB).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await v0({text:n,schema:t}))}}))}var aZ=()=>globalThis.fetch,uo=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a})=>sZ({url:e,headers:Se({"Content-Type":"application/json"},t),body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a}),sZ=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:a=aZ()})=>{try{const s=await a(e,{method:"POST",headers:JB(t),body:n.content,signal:o}),u=Jl(s);if(!s.ok){let l;try{l=await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw Fc(c)||Xt.isInstance(c)?c:new Xt({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}throw l.value}try{return await i({response:s,url:e,requestBodyValues:n.values})}catch(l){throw l instanceof Error&&(Fc(l)||Xt.isInstance(l))?l:new Xt({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}}catch(s){throw HB({error:s,url:e,requestBodyValues:n.values})}},lZ=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const a=await i.text(),s=Jl(i);if(a.trim()==="")return{responseHeaders:s,value:new Xt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})};try{const u=await iZ({text:a,schema:e});return{responseHeaders:s,value:new Xt({message:t(u),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,data:u,isRetryable:n?.(i,u)})}}catch{return{responseHeaders:s,value:new Xt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})}}},y0=e=>async({response:t})=>{const n=Jl(t);if(t.body==null)throw new AB({});return{responseHeaders:n,value:oZ({stream:t.body,schema:e})}},qf=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await v0({text:r,schema:e}),a=Jl(t);if(!o.success)throw new Xt({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:a,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},{btoa:uZ}=globalThis;function cZ(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return uZ(t)}function dZ(e){return e?.replace(/\/$/,"")}function Uu(e){return e!=null}var b0=(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))(b0||{}),Vf=O({id:k().nullish(),format:nr(b0).nullish(),index:ee().optional()}).loose(),pZ=O({type:L("reasoning.summary"),summary:k()}).extend(Vf.shape),fZ=O({type:L("reasoning.encrypted"),data:k()}).extend(Vf.shape),hZ=O({type:L("reasoning.text"),text:k().nullish(),signature:k().nullish()}).extend(Vf.shape),Hf=ae([pZ,fZ,hZ]),Va=ae([Hf,ze().transform(()=>null)]),Jf=W(Va).transform(e=>e.filter(t=>!!t));ae([O({delta:O({reasoning_details:W(Va)})}).transform(e=>e.delta.reasoning_details.filter(Uu)),O({message:O({reasoning_details:W(Va)})}).transform(e=>e.message.reasoning_details.filter(Uu)),O({text:k(),reasoning_details:W(Va)}).transform(e=>e.reasoning_details.filter(Uu))]);var Wl=O({error:O({code:ae([k(),ee()]).nullable().optional().default(null),message:k(),type:k().nullable().optional().default(null),param:Je().nullable().optional().default(null)}).passthrough()}).passthrough(),co=lZ({errorSchema:Wl,errorToMessage:e=>e.error.message}),_0=O({type:L("file"),file:O({hash:k(),name:k(),content:W(O({type:k(),text:k().optional()}).catchall(Je())).optional()}).catchall(Je())}).catchall(Je()),mZ=O({provider:k(),reasoning_details:W(Hf).optional(),annotations:W(_0).optional(),usage:O({promptTokens:ee(),promptTokensDetails:O({cachedTokens:ee()}).catchall(Je()).optional(),completionTokens:ee(),completionTokensDetails:O({reasoningTokens:ee()}).catchall(Je()).optional(),totalTokens:ee(),cost:ee().optional(),costDetails:O({upstreamInferenceCost:ee()}).catchall(Je()).optional()}).catchall(Je())}).catchall(Je()),zg=O({openrouter:O({reasoning_details:W(Hf).optional(),annotations:W(_0).optional()}).optional()}).optional();function $s(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 gZ=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function Wf({url:e,protocols:t}){try{const n=new URL(e);return t.has(n.protocol)}catch{return!1}}function Zc({part:e,defaultMediaType:t}){var n,i;if(e.data instanceof Uint8Array){const o=cZ(e.data);return`data:${(n=e.mediaType)!=null?n:t};base64,${o}`}const r=e.data.toString();return Wf({url:r,protocols:new Set(["http:","https:"])})||r.startsWith("data:")?r:`data:${(i=e.mediaType)!=null?i:t};base64,${r}`}function Dg(e,t){var n;const i=e.match(/^data:([^;]+)/);return i&&(n=i[1])!=null?n:t}function qc(e){const t=e.match(/^data:[^;]*;base64,(.+)$/);return t?t[1]:e}var vZ={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 yZ(e){const t=Zc({part:e,defaultMediaType:"audio/mpeg"});if(Wf({url:t,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
44
86
|
|
|
45
87
|
OpenRouter requires audio to be base64-encoded. Please:
|
|
46
88
|
1. Download the audio file locally
|
|
@@ -49,28 +91,28 @@ OpenRouter requires audio to be base64-encoded. Please:
|
|
|
49
91
|
|
|
50
92
|
The AI SDK will automatically handle base64 encoding.
|
|
51
93
|
|
|
52
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const
|
|
94
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=qc(t),i=e.mediaType||"audio/mpeg",r=i.replace("audio/",""),o=vZ[r];if(o===void 0){const a=gZ.join(", ");throw new Error(`Unsupported audio format: "${i}"
|
|
53
95
|
|
|
54
96
|
OpenRouter supports the following audio formats: ${a}
|
|
55
97
|
|
|
56
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:r,format:i}}function Kt(e){var t,r,o;const n=e?.anthropic,i=e?.openrouter;return(o=(r=(t=i?.cacheControl)!=null?t:i?.cache_control)!=null?r:n?.cacheControl)!=null?o:n?.cache_control}function N1(e){var t,r,o,n,i,a,s,l,u,c;const d=[];for(const{role:f,content:p,providerOptions:g}of e)switch(f){case"system":{d.push({role:"system",content:p,cache_control:Kt(g)});break}case"user":{if(p.length===1&&((t=p[0])==null?void 0:t.type)==="text"){const y=(r=Kt(g))!=null?r:Kt(p[0].providerOptions),x=y?[{type:"text",text:p[0].text,cache_control:y}]:p[0].text;d.push({role:"user",content:x});break}const h=Kt(g),b=p.map(y=>{var x,$,v,k,N,I,O;const M=(x=Kt(y.providerOptions))!=null?x:h;switch(y.type){case"text":return{type:"text",text:y.text,cache_control:M};case"file":{if(($=y.mediaType)!=null&&$.startsWith("image/"))return{type:"image_url",image_url:{url:bu({part:y,defaultMediaType:"image/jpeg"})},cache_control:M};if((v=y.mediaType)!=null&&v.startsWith("audio/"))return{type:"input_audio",input_audio:O1(y),cache_control:M};const F=String((O=(I=(N=(k=y.providerOptions)==null?void 0:k.openrouter)==null?void 0:N.filename)!=null?I:y.filename)!=null?O:""),te=bu({part:y,defaultMediaType:"application/pdf"});return qc({url:te,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:F,file_data:te}}:{type:"file",file:{filename:F,file_data:te},cache_control:M}}default:return{type:"text",text:"",cache_control:M}}});d.push({role:"user",content:b});break}case"assistant":{let h="",b="";const y=[],x=[];for(const I of p)switch(I.type){case"text":{h+=I.text;break}case"tool-call":{const O=(o=I.providerOptions)==null?void 0:o.openrouter;O?.reasoning_details&&Array.isArray(O.reasoning_details)&&x.push(...O.reasoning_details),y.push({id:I.toolCallId,type:"function",function:{name:I.toolName,arguments:JSON.stringify(I.input)}});break}case"reasoning":{b+=I.text;const O=Vp.safeParse(I.providerOptions);O.success&&((i=(n=O.data)==null?void 0:n.openrouter)!=null&&i.reasoning_details)&&x.push(...O.data.openrouter.reasoning_details);break}}const $=Vp.safeParse(g),v=$.success?(s=(a=$.data)==null?void 0:a.openrouter)==null?void 0:s.reasoning_details:void 0,k=$.success?(u=(l=$.data)==null?void 0:l.openrouter)==null?void 0:u.annotations:void 0,N=v&&Array.isArray(v)&&v.length>0?v:x.length>0?x:void 0;d.push({role:"assistant",content:h,tool_calls:y.length>0?y:void 0,reasoning:b||void 0,reasoning_details:N,annotations:k,cache_control:Kt(g)});break}case"tool":{for(const h of p){const b=P1(h);d.push({role:"tool",tool_call_id:h.toolCallId,content:b,cache_control:(c=Kt(g))!=null?c:Kt(h.providerOptions)})}break}}return d}function P1(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}G([C("auto"),C("none"),C("required"),E({type:C("function"),function:E({name:w()})})]);function C1(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 Nw({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var j1=E({type:C("image_url"),image_url:E({url:w()}).passthrough()}).passthrough(),A1=G([j1,$e().transform(()=>null)]),ox=R(A1).transform(e=>e.filter(t=>!!t)),ix=E({id:w().optional(),model:w().optional(),provider:w().optional(),usage:E({prompt_tokens:q(),prompt_tokens_details:E({cached_tokens:q()}).passthrough().nullish(),completion_tokens:q(),completion_tokens_details:E({reasoning_tokens:q()}).passthrough().nullish(),total_tokens:q(),cost:q().optional(),cost_details:E({upstream_inference_cost:q().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),R1=G([ix.extend({choices:R(E({message:E({role:C("assistant"),content:w().nullable().optional(),reasoning:w().nullable().optional(),reasoning_details:Fc.nullish(),images:ox.nullish(),tool_calls:R(E({id:w().optional().nullable(),type:C("function"),function:E({name:w(),arguments:w()}).passthrough()}).passthrough()).optional(),annotations:R(G([E({type:C("url_citation"),url_citation:E({end_index:q(),start_index:q(),title:w(),url:w(),content:w().optional()}).passthrough()}).passthrough(),E({type:C("file_annotation"),file_annotation:E({file_id:w(),quote:w().optional()}).passthrough()}).passthrough(),E({type:C("file"),file:E({hash:w(),name:w(),content:R(E({type:w(),text:w().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:q().nullish(),logprobs:E({content:R(E({token:w(),logprob:q(),top_logprobs:R(E({token:w(),logprob:q()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:w().optional().nullable()}).passthrough())}),Ja.extend({user_id:w().optional()})]),z1=G([ix.extend({choices:R(E({delta:E({role:dr(["assistant"]).optional(),content:w().nullish(),reasoning:w().nullish().optional(),reasoning_details:Fc.nullish(),images:ox.nullish(),tool_calls:R(E({index:q().nullish(),id:w().nullish(),type:C("function").optional(),function:E({name:w().nullish(),arguments:w().nullish()}).passthrough()}).passthrough()).nullish(),annotations:R(G([E({type:C("url_citation"),url_citation:E({end_index:q(),start_index:q(),title:w(),url:w(),content:w().optional()}).passthrough()}).passthrough(),E({type:C("file_annotation"),file_annotation:E({file_id:w(),quote:w().optional()}).passthrough()}).passthrough(),E({type:C("file"),file:E({hash:w(),name:w(),content:R(E({type:w(),text:w().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:E({content:R(E({token:w(),logprob:q(),top_logprobs:R(E({token:w(),logprob:q()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:w().nullable().optional(),index:q().nullish()}).passthrough())}),Ja]),M1=class{constructor(e,t,r){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=r}getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:o,frequencyPenalty:n,presencePenalty:i,seed:a,stopSequences:s,responseFormat:l,topK:u,tools:c,toolChoice:d}){var f;const p=ue(ue({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:r,top_p:o,frequency_penalty:n,presence_penalty:i,seed:a,stop:s,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:ue({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:N1(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 g=c.filter(h=>h.type==="function").map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.inputSchema}}));return Ai(ue({},p),{tools:g,tool_choice:d?C1(d):void 0})}return p}async doGenerate(e){var t,r,o,n,i,a,s,l,u,c,d,f,p,g,h,b,y,x,$,v,k,N,I;const M=(e.providerOptions||{}).openrouter||{},F=ue(ue({},this.getArgs(e)),M),{value:te,responseHeaders:oe}=await Bn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vn(this.config.headers(),e.headers),body:F,failedResponseHandler:Jn,successfulResponseHandler:Uc(R1),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in te){const U=te.error;throw new xt({message:U.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:F,statusCode:200,responseHeaders:oe,data:U})}const J=te,V=J.choices[0];if(!V)throw new Jw({message:"No choice in response"});const ye=J.usage?{inputTokens:(t=J.usage.prompt_tokens)!=null?t:0,outputTokens:(r=J.usage.completion_tokens)!=null?r:0,totalTokens:((o=J.usage.prompt_tokens)!=null?o:0)+((n=J.usage.completion_tokens)!=null?n:0),reasoningTokens:(a=(i=J.usage.completion_tokens_details)==null?void 0:i.reasoning_tokens)!=null?a:0,cachedInputTokens:(l=(s=J.usage.prompt_tokens_details)==null?void 0:s.cached_tokens)!=null?l:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},ie=(u=V.message.reasoning_details)!=null?u:[],de=ie.length>0?ie.map(U=>{switch(U.type){case"reasoning.text":{if(U.text)return{type:"reasoning",text:U.text,providerMetadata:{openrouter:{reasoning_details:[U]}}};break}case"reasoning.summary":{if(U.summary)return{type:"reasoning",text:U.summary,providerMetadata:{openrouter:{reasoning_details:[U]}}};break}case"reasoning.encrypted":{if(U.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[U]}}};break}}return null}).filter(U=>U!==null):V.message.reasoning?[{type:"reasoning",text:V.message.reasoning}]:[],K=[];if(K.push(...de),V.message.content&&K.push({type:"text",text:V.message.content}),V.message.tool_calls)for(const U of V.message.tool_calls)K.push({type:"tool-call",toolCallId:(c=U.id)!=null?c:bt(),toolName:U.function.name,input:U.function.arguments,providerMetadata:{openrouter:{reasoning_details:ie}}});if(V.message.images)for(const U of V.message.images)K.push({type:"file",mediaType:Bp(U.image_url.url,"image/jpeg"),data:_u(U.image_url.url)});if(V.message.annotations)for(const U of V.message.annotations)U.type==="url_citation"&&K.push({type:"source",sourceType:"url",id:U.url_citation.url,url:U.url_citation.url,title:U.url_citation.title,providerMetadata:{openrouter:{content:U.url_citation.content||""}}});const fe=(d=V.message.annotations)==null?void 0:d.filter(U=>U.type==="file"),B=V.message.tool_calls&&V.message.tool_calls.length>0,Ue=ie.some(U=>U.type==="reasoning.encrypted"&&U.data),Le=B&&Ue&&V.finish_reason==="stop"?"tool-calls":zi(V.finish_reason);return{content:K,finishReason:Le,usage:ye,warnings:[],providerMetadata:{openrouter:k1.parse({provider:(f=J.provider)!=null?f:"",reasoning_details:(p=V.message.reasoning_details)!=null?p:[],annotations:fe&&fe.length>0?fe:void 0,usage:ue(ue(ue({promptTokens:(g=ye.inputTokens)!=null?g:0,completionTokens:(h=ye.outputTokens)!=null?h:0,totalTokens:(b=ye.totalTokens)!=null?b:0,cost:(y=J.usage)==null?void 0:y.cost},(($=(x=J.usage)==null?void 0:x.prompt_tokens_details)==null?void 0:$.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:J.usage.prompt_tokens_details.cached_tokens}}:{}),((k=(v=J.usage)==null?void 0:v.completion_tokens_details)==null?void 0:k.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:J.usage.completion_tokens_details.reasoning_tokens}}:{}),((I=(N=J.usage)==null?void 0:N.cost_details)==null?void 0:I.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:J.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:F},response:{id:J.id,modelId:J.model,headers:oe}}}async doStream(e){var t;const o=(e.providerOptions||{}).openrouter||{},n=ue(ue({},this.getArgs(e)),o),{value:i,responseHeaders:a}=await Bn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vn(this.config.headers(),e.headers),body:Ai(ue({},n),{stream:!0,stream_options:this.config.compatibility==="strict"?ue({include_usage:!0},(t=this.settings.usage)!=null&&t.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:Jn,successfulResponseHandler:tx(z1),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];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,g=!1,h,b,y,x;return{stream:i.pipeThrough(new TransformStream({transform($,v){var k,N,I,O,M,F,te,oe,J,V,ye,ie,de,K,fe;if(!$.success){l="error",v.enqueue({type:"error",error:$.error});return}const B=$.value;if("error"in B){l="error",v.enqueue({type:"error",error:B.error});return}if(B.provider&&(x=B.provider),B.id&&(y=B.id,v.enqueue({type:"response-metadata",id:B.id})),B.model&&v.enqueue({type:"response-metadata",modelId:B.model}),B.usage!=null){if(u.inputTokens=B.usage.prompt_tokens,u.outputTokens=B.usage.completion_tokens,u.totalTokens=B.usage.prompt_tokens+B.usage.completion_tokens,c.promptTokens=B.usage.prompt_tokens,B.usage.prompt_tokens_details){const Q=(k=B.usage.prompt_tokens_details.cached_tokens)!=null?k:0;u.cachedInputTokens=Q,c.promptTokensDetails={cachedTokens:Q}}if(c.completionTokens=B.usage.completion_tokens,B.usage.completion_tokens_details){const Q=(N=B.usage.completion_tokens_details.reasoning_tokens)!=null?N:0;u.reasoningTokens=Q,c.completionTokensDetails={reasoningTokens:Q}}c.cost=B.usage.cost,c.totalTokens=B.usage.total_tokens;const U=(I=B.usage.cost_details)==null?void 0:I.upstream_inference_cost;U!=null&&(c.costDetails={upstreamInferenceCost:U})}const Ue=B.choices[0];if(Ue?.finish_reason!=null&&(l=zi(Ue.finish_reason)),Ue?.delta==null)return;const be=Ue.delta,Le=(U,Q)=>{g||(b=y||bt(),v.enqueue({providerMetadata:Q,type:"reasoning-start",id:b}),g=!0),v.enqueue({providerMetadata:Q,type:"reasoning-delta",delta:U,id:b||bt()})};if(be.reasoning_details&&be.reasoning_details.length>0){for(const Q of be.reasoning_details)if(Q.type==="reasoning.text"){const me=d[d.length-1];me?.type==="reasoning.text"?(me.text=(me.text||"")+(Q.text||""),me.signature=me.signature||Q.signature,me.format=me.format||Q.format):d.push(ue({},Q))}else d.push(Q);const U={openrouter:{reasoning_details:be.reasoning_details}};for(const Q of be.reasoning_details)switch(Q.type){case"reasoning.text":{Q.text&&Le(Q.text,U);break}case"reasoning.encrypted":{Q.data&&Le("[REDACTED]",U);break}case"reasoning.summary":{Q.summary&&Le(Q.summary,U);break}}}else be.reasoning&&Le(be.reasoning);if(be.content&&(g&&!p&&(v.enqueue({type:"reasoning-end",id:b||bt()}),g=!1),p||(h=y||bt(),v.enqueue({type:"text-start",id:h}),p=!0),v.enqueue({type:"text-delta",delta:be.content,id:h||bt()})),be.annotations){for(const U of be.annotations)if(U.type==="url_citation")v.enqueue({type:"source",sourceType:"url",id:U.url_citation.url,url:U.url_citation.url,title:U.url_citation.title,providerMetadata:{openrouter:{content:U.url_citation.content||""}}});else if(U.type==="file"){const Q=U.file;Q&&typeof Q=="object"&&"hash"in Q&&"name"in Q&&f.push(U)}}if(be.tool_calls!=null)for(const U of be.tool_calls){const Q=(O=U.index)!=null?O:s.length-1;if(s[Q]==null){if(U.type!=="function")throw new wn({data:U,message:"Expected 'function' type."});if(U.id==null)throw new wn({data:U,message:"Expected 'id' to be a string."});if(((M=U.function)==null?void 0:M.name)==null)throw new wn({data:U,message:"Expected 'function.name' to be a string."});s[Q]={id:U.id,type:"function",function:{name:U.function.name,arguments:(F=U.function.arguments)!=null?F:""},inputStarted:!1,sent:!1};const xe=s[Q];if(xe==null)throw new wn({data:{index:Q,toolCallsLength:s.length},message:`Tool call at index ${Q} is missing after creation.`});((te=xe.function)==null?void 0:te.name)!=null&&((oe=xe.function)==null?void 0:oe.arguments)!=null&&Os(xe.function.arguments)&&(xe.inputStarted=!0,v.enqueue({type:"tool-input-start",id:xe.id,toolName:xe.function.name}),v.enqueue({type:"tool-input-delta",id:xe.id,delta:xe.function.arguments}),v.enqueue({type:"tool-input-end",id:xe.id}),v.enqueue({type:"tool-call",toolCallId:xe.id,toolName:xe.function.name,input:xe.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),xe.sent=!0);continue}const me=s[Q];if(me==null)throw new wn({data:{index:Q,toolCallsLength:s.length,toolCallDelta:U},message:`Tool call at index ${Q} is missing during merge.`});me.inputStarted||(me.inputStarted=!0,v.enqueue({type:"tool-input-start",id:me.id,toolName:me.function.name})),((J=U.function)==null?void 0:J.arguments)!=null&&(me.function.arguments+=(ye=(V=U.function)==null?void 0:V.arguments)!=null?ye:""),v.enqueue({type:"tool-input-delta",id:me.id,delta:(ie=U.function.arguments)!=null?ie:""}),((de=me.function)==null?void 0:de.name)!=null&&((K=me.function)==null?void 0:K.arguments)!=null&&Os(me.function.arguments)&&(v.enqueue({type:"tool-call",toolCallId:(fe=me.id)!=null?fe:bt(),toolName:me.function.name,input:me.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),me.sent=!0)}if(be.images!=null)for(const U of be.images)v.enqueue({type:"file",mediaType:Bp(U.image_url.url,"image/jpeg"),data:_u(U.image_url.url)})},flush($){var v;const k=s.length>0,N=d.some(O=>O.type==="reasoning.encrypted"&&O.data);if(k&&N&&l==="stop"&&(l="tool-calls"),l==="tool-calls")for(const O of s)O&&!O.sent&&($.enqueue({type:"tool-call",toolCallId:(v=O.id)!=null?v:bt(),toolName:O.function.name,input:Os(O.function.arguments)?O.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:d}}}),O.sent=!0);g&&$.enqueue({type:"reasoning-end",id:b||bt()}),p&&$.enqueue({type:"text-end",id:h||bt()});const I={usage:c};x!==void 0&&(I.provider=x),d.length>0&&(I.reasoning_details=d),f.length>0&&(I.annotations=f),$.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:I}})}})),warnings:[],request:{body:n},response:{headers:a}}}};function D1({prompt:e,inputFormat:t,user:r="user",assistant:o="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 n="";e[0]&&e[0].role==="system"&&(n+=`${e[0].content}
|
|
98
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:n,format:o}}function Ln(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 bZ(e){var t,n,i,r,o,a,s,u,l,c;const d=[];for(const{role:f,content:p,providerOptions:g}of e)switch(f){case"system":{d.push({role:"system",content:p,cache_control:Ln(g)});break}case"user":{if(p.length===1&&((t=p[0])==null?void 0:t.type)==="text"){const v=(n=Ln(g))!=null?n:Ln(p[0].providerOptions),x=v?[{type:"text",text:p[0].text,cache_control:v}]:p[0].text;d.push({role:"user",content:x});break}const m=Ln(g),y=p.map(v=>{var x,S,b,A,E,C,P;const j=(x=Ln(v.providerOptions))!=null?x:m;switch(v.type){case"text":return{type:"text",text:v.text,cache_control:j};case"file":{if((S=v.mediaType)!=null&&S.startsWith("image/"))return{type:"image_url",image_url:{url:Zc({part:v,defaultMediaType:"image/jpeg"})},cache_control:j};if((b=v.mediaType)!=null&&b.startsWith("audio/"))return{type:"input_audio",input_audio:yZ(v),cache_control:j};const F=String((P=(C=(E=(A=v.providerOptions)==null?void 0:A.openrouter)==null?void 0:E.filename)!=null?C:v.filename)!=null?P:""),D=Zc({part:v,defaultMediaType:"application/pdf"});return Wf({url:D,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:F,file_data:D}}:{type:"file",file:{filename:F,file_data:D},cache_control:j}}default:return{type:"text",text:"",cache_control:j}}});d.push({role:"user",content:y});break}case"assistant":{let m="",y="";const v=[],x=[];for(const C of p)switch(C.type){case"text":{m+=C.text;break}case"tool-call":{const P=(i=C.providerOptions)==null?void 0:i.openrouter;P?.reasoning_details&&Array.isArray(P.reasoning_details)&&x.push(...P.reasoning_details),v.push({id:C.toolCallId,type:"function",function:{name:C.toolName,arguments:JSON.stringify(C.input)}});break}case"reasoning":{y+=C.text;const P=zg.safeParse(C.providerOptions);P.success&&((o=(r=P.data)==null?void 0:r.openrouter)!=null&&o.reasoning_details)&&x.push(...P.data.openrouter.reasoning_details);break}}const S=zg.safeParse(g),b=S.success?(s=(a=S.data)==null?void 0:a.openrouter)==null?void 0:s.reasoning_details:void 0,A=S.success?(l=(u=S.data)==null?void 0:u.openrouter)==null?void 0:l.annotations:void 0,E=b&&Array.isArray(b)&&b.length>0?b:x.length>0?x:void 0;d.push({role:"assistant",content:m,tool_calls:v.length>0?v:void 0,reasoning:y||void 0,reasoning_details:E,annotations:A,cache_control:Ln(g)});break}case"tool":{for(const m of p){const y=_Z(m);d.push({role:"tool",tool_call_id:m.toolCallId,content:y,cache_control:(c=Ln(g))!=null?c:Ln(m.providerOptions)})}break}}return d}function _Z(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}ae([L("auto"),L("none"),L("required"),O({type:L("function"),function:O({name:k()})})]);function wZ(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 JT({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var xZ=O({type:L("image_url"),image_url:O({url:k()}).passthrough()}).passthrough(),SZ=ae([xZ,ze().transform(()=>null)]),w0=W(SZ).transform(e=>e.filter(t=>!!t)),x0=O({id:k().optional(),model:k().optional(),provider:k().optional(),usage:O({prompt_tokens:ee(),prompt_tokens_details:O({cached_tokens:ee()}).passthrough().nullish(),completion_tokens:ee(),completion_tokens_details:O({reasoning_tokens:ee()}).passthrough().nullish(),total_tokens:ee(),cost:ee().optional(),cost_details:O({upstream_inference_cost:ee().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),IZ=ae([x0.extend({choices:W(O({message:O({role:L("assistant"),content:k().nullable().optional(),reasoning:k().nullable().optional(),reasoning_details:Jf.nullish(),images:w0.nullish(),tool_calls:W(O({id:k().optional().nullable(),type:L("function"),function:O({name:k(),arguments:k()}).passthrough()}).passthrough()).optional(),annotations:W(ae([O({type:L("url_citation"),url_citation:O({end_index:ee(),start_index:ee(),title:k(),url:k(),content:k().optional()}).passthrough()}).passthrough(),O({type:L("file_annotation"),file_annotation:O({file_id:k(),quote:k().optional()}).passthrough()}).passthrough(),O({type:L("file"),file:O({hash:k(),name:k(),content:W(O({type:k(),text:k().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:ee().nullish(),logprobs:O({content:W(O({token:k(),logprob:ee(),top_logprobs:W(O({token:k(),logprob:ee()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:k().optional().nullable()}).passthrough())}),Wl.extend({user_id:k().optional()})]),kZ=ae([x0.extend({choices:W(O({delta:O({role:nr(["assistant"]).optional(),content:k().nullish(),reasoning:k().nullish().optional(),reasoning_details:Jf.nullish(),images:w0.nullish(),tool_calls:W(O({index:ee().nullish(),id:k().nullish(),type:L("function").optional(),function:O({name:k().nullish(),arguments:k().nullish()}).passthrough()}).passthrough()).nullish(),annotations:W(ae([O({type:L("url_citation"),url_citation:O({end_index:ee(),start_index:ee(),title:k(),url:k(),content:k().optional()}).passthrough()}).passthrough(),O({type:L("file_annotation"),file_annotation:O({file_id:k(),quote:k().optional()}).passthrough()}).passthrough(),O({type:L("file"),file:O({hash:k(),name:k(),content:W(O({type:k(),text:k().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:O({content:W(O({token:k(),logprob:ee(),top_logprobs:W(O({token:k(),logprob:ee()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:k().nullable().optional(),index:ee().nullish()}).passthrough())}),Wl]),EZ=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:a,stopSequences:s,responseFormat:u,topK:l,tools:c,toolChoice:d}){var f;const p=Se(Se({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:a,stop:s,response_format:u?.type==="json"?u.schema!=null?{type:"json_schema",json_schema:Se({schema:u.schema,strict:!0,name:(f=u.name)!=null?f:"response"},u.description&&{description:u.description})}:{type:"json_object"}:void 0,top_k:l,messages:bZ(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 g=c.filter(m=>m.type==="function").map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema}}));return Es(Se({},p),{tools:g,tool_choice:d?wZ(d):void 0})}return p}async doGenerate(e){var t,n,i,r,o,a,s,u,l,c,d,f,p,g,m,y,v,x,S,b,A,E,C;const j=(e.providerOptions||{}).openrouter||{},F=Se(Se({},this.getArgs(e)),j),{value:D,responseHeaders:V}=await uo({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:lo(this.config.headers(),e.headers),body:F,failedResponseHandler:co,successfulResponseHandler:qf(IZ),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in D){const H=D.error;throw new Xt({message:H.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:F,statusCode:200,responseHeaders:V,data:H})}const G=D,z=G.choices[0];if(!z)throw new u0({message:"No choice in response"});const U=G.usage?{inputTokens:(t=G.usage.prompt_tokens)!=null?t:0,outputTokens:(n=G.usage.completion_tokens)!=null?n:0,totalTokens:((i=G.usage.prompt_tokens)!=null?i:0)+((r=G.usage.completion_tokens)!=null?r:0),reasoningTokens:(a=(o=G.usage.completion_tokens_details)==null?void 0:o.reasoning_tokens)!=null?a:0,cachedInputTokens:(u=(s=G.usage.prompt_tokens_details)==null?void 0:s.cached_tokens)!=null?u:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},Q=(l=z.message.reasoning_details)!=null?l:[],ie=Q.length>0?Q.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):z.message.reasoning?[{type:"reasoning",text:z.message.reasoning}]:[],X=[];if(X.push(...ie),z.message.content&&X.push({type:"text",text:z.message.content}),z.message.tool_calls)for(const H of z.message.tool_calls)X.push({type:"tool-call",toolCallId:(c=H.id)!=null?c:Gt(),toolName:H.function.name,input:H.function.arguments,providerMetadata:{openrouter:{reasoning_details:Q}}});if(z.message.images)for(const H of z.message.images)X.push({type:"file",mediaType:Dg(H.image_url.url,"image/jpeg"),data:qc(H.image_url.url)});if(z.message.annotations)for(const H of z.message.annotations)H.type==="url_citation"&&X.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 me=(d=z.message.annotations)==null?void 0:d.filter(H=>H.type==="file"),I=z.message.tool_calls&&z.message.tool_calls.length>0,Te=Q.some(H=>H.type==="reasoning.encrypted"&&H.data),T=I&&Te&&z.finish_reason==="stop"?"tool-calls":$s(z.finish_reason);return{content:X,finishReason:T,usage:U,warnings:[],providerMetadata:{openrouter:mZ.parse({provider:(f=G.provider)!=null?f:"",reasoning_details:(p=z.message.reasoning_details)!=null?p:[],annotations:me&&me.length>0?me:void 0,usage:Se(Se(Se({promptTokens:(g=U.inputTokens)!=null?g:0,completionTokens:(m=U.outputTokens)!=null?m:0,totalTokens:(y=U.totalTokens)!=null?y:0,cost:(v=G.usage)==null?void 0:v.cost},((S=(x=G.usage)==null?void 0:x.prompt_tokens_details)==null?void 0:S.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:G.usage.prompt_tokens_details.cached_tokens}}:{}),((A=(b=G.usage)==null?void 0:b.completion_tokens_details)==null?void 0:A.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:G.usage.completion_tokens_details.reasoning_tokens}}:{}),((C=(E=G.usage)==null?void 0:E.cost_details)==null?void 0:C.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:G.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:F},response:{id:G.id,modelId:G.model,headers:V}}}async doStream(e){var t;const i=(e.providerOptions||{}).openrouter||{},r=Se(Se({},this.getArgs(e)),i),{value:o,responseHeaders:a}=await uo({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:lo(this.config.headers(),e.headers),body:Es(Se({},r),{stream:!0,stream_options:this.config.compatibility==="strict"?Se({include_usage:!0},(t=this.settings.usage)!=null&&t.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:co,successfulResponseHandler:y0(kZ),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let u="other";const l={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},c={},d=[],f=[];let p=!1,g=!1,m,y,v,x;return{stream:o.pipeThrough(new TransformStream({transform(S,b){var A,E,C,P,j,F,D,V,G,z,U,Q,ie,X,me;if(!S.success){u="error",b.enqueue({type:"error",error:S.error});return}const I=S.value;if("error"in I){u="error",b.enqueue({type:"error",error:I.error});return}if(I.provider&&(x=I.provider),I.id&&(v=I.id,b.enqueue({type:"response-metadata",id:I.id})),I.model&&b.enqueue({type:"response-metadata",modelId:I.model}),I.usage!=null){if(l.inputTokens=I.usage.prompt_tokens,l.outputTokens=I.usage.completion_tokens,l.totalTokens=I.usage.prompt_tokens+I.usage.completion_tokens,c.promptTokens=I.usage.prompt_tokens,I.usage.prompt_tokens_details){const te=(A=I.usage.prompt_tokens_details.cached_tokens)!=null?A:0;l.cachedInputTokens=te,c.promptTokensDetails={cachedTokens:te}}if(c.completionTokens=I.usage.completion_tokens,I.usage.completion_tokens_details){const te=(E=I.usage.completion_tokens_details.reasoning_tokens)!=null?E:0;l.reasoningTokens=te,c.completionTokensDetails={reasoningTokens:te}}c.cost=I.usage.cost,c.totalTokens=I.usage.total_tokens;const H=(C=I.usage.cost_details)==null?void 0:C.upstream_inference_cost;H!=null&&(c.costDetails={upstreamInferenceCost:H})}const Te=I.choices[0];if(Te?.finish_reason!=null&&(u=$s(Te.finish_reason)),Te?.delta==null)return;const ve=Te.delta,T=(H,te)=>{g||(y=v||Gt(),b.enqueue({providerMetadata:te,type:"reasoning-start",id:y}),g=!0),b.enqueue({providerMetadata:te,type:"reasoning-delta",delta:H,id:y||Gt()})};if(ve.reasoning_details&&ve.reasoning_details.length>0){for(const te of ve.reasoning_details)if(te.type==="reasoning.text"){const le=d[d.length-1];le?.type==="reasoning.text"?(le.text=(le.text||"")+(te.text||""),le.signature=le.signature||te.signature,le.format=le.format||te.format):d.push(Se({},te))}else d.push(te);const H={openrouter:{reasoning_details:ve.reasoning_details}};for(const te of ve.reasoning_details)switch(te.type){case"reasoning.text":{te.text&&T(te.text,H);break}case"reasoning.encrypted":{te.data&&T("[REDACTED]",H);break}case"reasoning.summary":{te.summary&&T(te.summary,H);break}}}else ve.reasoning&&T(ve.reasoning);if(ve.content&&(g&&!p&&(b.enqueue({type:"reasoning-end",id:y||Gt()}),g=!1),p||(m=v||Gt(),b.enqueue({type:"text-start",id:m}),p=!0),b.enqueue({type:"text-delta",delta:ve.content,id:m||Gt()})),ve.annotations){for(const H of ve.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 te=H.file;te&&typeof te=="object"&&"hash"in te&&"name"in te&&f.push(H)}}if(ve.tool_calls!=null)for(const H of ve.tool_calls){const te=(P=H.index)!=null?P:s.length-1;if(s[te]==null){if(H.type!=="function")throw new Si({data:H,message:"Expected 'function' type."});if(H.id==null)throw new Si({data:H,message:"Expected 'id' to be a string."});if(((j=H.function)==null?void 0:j.name)==null)throw new Si({data:H,message:"Expected 'function.name' to be a string."});s[te]={id:H.id,type:"function",function:{name:H.function.name,arguments:(F=H.function.arguments)!=null?F:""},inputStarted:!1,sent:!1};const we=s[te];if(we==null)throw new Si({data:{index:te,toolCallsLength:s.length},message:`Tool call at index ${te} is missing after creation.`});((D=we.function)==null?void 0:D.name)!=null&&((V=we.function)==null?void 0:V.arguments)!=null&&Du(we.function.arguments)&&(we.inputStarted=!0,b.enqueue({type:"tool-input-start",id:we.id,toolName:we.function.name}),b.enqueue({type:"tool-input-delta",id:we.id,delta:we.function.arguments}),b.enqueue({type:"tool-input-end",id:we.id}),b.enqueue({type:"tool-call",toolCallId:we.id,toolName:we.function.name,input:we.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),we.sent=!0);continue}const le=s[te];if(le==null)throw new Si({data:{index:te,toolCallsLength:s.length,toolCallDelta:H},message:`Tool call at index ${te} is missing during merge.`});le.inputStarted||(le.inputStarted=!0,b.enqueue({type:"tool-input-start",id:le.id,toolName:le.function.name})),((G=H.function)==null?void 0:G.arguments)!=null&&(le.function.arguments+=(U=(z=H.function)==null?void 0:z.arguments)!=null?U:""),b.enqueue({type:"tool-input-delta",id:le.id,delta:(Q=H.function.arguments)!=null?Q:""}),((ie=le.function)==null?void 0:ie.name)!=null&&((X=le.function)==null?void 0:X.arguments)!=null&&Du(le.function.arguments)&&(b.enqueue({type:"tool-call",toolCallId:(me=le.id)!=null?me:Gt(),toolName:le.function.name,input:le.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),le.sent=!0)}if(ve.images!=null)for(const H of ve.images)b.enqueue({type:"file",mediaType:Dg(H.image_url.url,"image/jpeg"),data:qc(H.image_url.url)})},flush(S){var b;const A=s.length>0,E=d.some(P=>P.type==="reasoning.encrypted"&&P.data);if(A&&E&&u==="stop"&&(u="tool-calls"),u==="tool-calls")for(const P of s)P&&!P.sent&&(S.enqueue({type:"tool-call",toolCallId:(b=P.id)!=null?b:Gt(),toolName:P.function.name,input:Du(P.function.arguments)?P.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:d}}}),P.sent=!0);g&&S.enqueue({type:"reasoning-end",id:y||Gt()}),p&&S.enqueue({type:"text-end",id:m||Gt()});const C={usage:c};x!==void 0&&(C.provider=x),d.length>0&&(C.reasoning_details=d),f.length>0&&(C.annotations=f),S.enqueue({type:"finish",finishReason:u,usage:l,providerMetadata:{openrouter:C}})}})),warnings:[],request:{body:r},response:{headers:a}}}};function TZ({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}
|
|
57
99
|
|
|
58
|
-
`,e=e.slice(1));for(const{role:
|
|
100
|
+
`,e=e.slice(1));for(const{role:o,content:a}of e)switch(o){case"system":throw new OB({message:`Unexpected system message in prompt: ${a}`,prompt:e});case"user":{const s=a.map(u=>{switch(u.type){case"text":return u.text;case"file":throw new qn({functionality:"file attachments"});default:return""}}).join("");r+=`${n}:
|
|
59
101
|
${s}
|
|
60
102
|
|
|
61
|
-
`;break}case"assistant":{const s=a.map(
|
|
103
|
+
`;break}case"assistant":{const s=a.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new qn({functionality:"tool-call messages"});case"tool-result":throw new qn({functionality:"tool-result messages"});case"reasoning":throw new qn({functionality:"reasoning messages"});case"file":throw new qn({functionality:"file attachments"});default:return""}}).join("");r+=`${i}:
|
|
62
104
|
${s}
|
|
63
105
|
|
|
64
|
-
`;break}case"tool":throw new
|
|
65
|
-
`,{prompt:n}}var Jp=G([E({id:w().optional(),model:w().optional(),choices:R(E({text:w(),reasoning:w().nullish().optional(),reasoning_details:Fc.nullish(),finish_reason:w().nullish(),index:q().nullish(),logprobs:E({tokens:R(w()),token_logprobs:R(q()),top_logprobs:R(Xe(w(),q())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:E({prompt_tokens:q(),prompt_tokens_details:E({cached_tokens:q()}).passthrough().nullish(),completion_tokens:q(),completion_tokens_details:E({reasoning_tokens:q()}).passthrough().nullish(),total_tokens:q(),cost:q().optional(),cost_details:E({upstream_inference_cost:q().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Ja]),U1=class{constructor(e,t,r){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=r}getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:o,frequencyPenalty:n,presencePenalty:i,seed:a,responseFormat:s,topK:l,stopSequences:u,tools:c,toolChoice:d}){const{prompt:f}=D1({prompt:e,inputFormat:"prompt"});if(c?.length)throw new Xt({functionality:"tools"});if(d)throw new Xt({functionality:"toolChoice"});return ue(ue({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:r,top_p:o,frequency_penalty:n,presence_penalty:i,seed:a,stop:u,response_format:s,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,r,o,n,i,a,s,l,u,c,d,f,p,g,h;const y=(e.providerOptions||{}).openrouter||{},x=ue(ue({},this.getArgs(e)),y),{value:$,responseHeaders:v}=await Bn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Vn(this.config.headers(),e.headers),body:x,failedResponseHandler:Jn,successfulResponseHandler:Uc(Jp),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in $){const N=$.error;throw new xt({message:N.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:x,statusCode:200,responseHeaders:v,data:N})}const k=$.choices[0];if(!k)throw new Jw({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=k.text)!=null?t:""}],finishReason:zi(k.finish_reason),usage:{inputTokens:(o=(r=$.usage)==null?void 0:r.prompt_tokens)!=null?o:0,outputTokens:(i=(n=$.usage)==null?void 0:n.completion_tokens)!=null?i:0,totalTokens:((s=(a=$.usage)==null?void 0:a.prompt_tokens)!=null?s:0)+((u=(l=$.usage)==null?void 0:l.completion_tokens)!=null?u:0),reasoningTokens:(f=(d=(c=$.usage)==null?void 0:c.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:0,cachedInputTokens:(h=(g=(p=$.usage)==null?void 0:p.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?h:0},warnings:[],response:{headers:v}}}async doStream(e){const r=(e.providerOptions||{}).openrouter||{},o=ue(ue({},this.getArgs(e)),r),{value:n,responseHeaders:i}=await Bn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Vn(this.config.headers(),e.headers),body:Ai(ue({},o),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:Jn,successfulResponseHandler:tx(Jp),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="other";const s={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},l={};return{stream:n.pipeThrough(new TransformStream({transform(u,c){var d,f,p;if(!u.success){a="error",c.enqueue({type:"error",error:u.error});return}const g=u.value;if("error"in g){a="error",c.enqueue({type:"error",error:g.error});return}if(g.usage!=null){if(s.inputTokens=g.usage.prompt_tokens,s.outputTokens=g.usage.completion_tokens,s.totalTokens=g.usage.prompt_tokens+g.usage.completion_tokens,l.promptTokens=g.usage.prompt_tokens,g.usage.prompt_tokens_details){const y=(d=g.usage.prompt_tokens_details.cached_tokens)!=null?d:0;s.cachedInputTokens=y,l.promptTokensDetails={cachedTokens:y}}if(l.completionTokens=g.usage.completion_tokens,g.usage.completion_tokens_details){const y=(f=g.usage.completion_tokens_details.reasoning_tokens)!=null?f:0;s.reasoningTokens=y,l.completionTokensDetails={reasoningTokens:y}}l.cost=g.usage.cost,l.totalTokens=g.usage.total_tokens;const b=(p=g.usage.cost_details)==null?void 0:p.upstream_inference_cost;b!=null&&(l.costDetails={upstreamInferenceCost:b})}const h=g.choices[0];h?.finish_reason!=null&&(a=zi(h.finish_reason)),h?.text!=null&&c.enqueue({type:"text-delta",delta:h.text,id:bt()})},flush(u){u.enqueue({type:"finish",finishReason:a,usage:s,providerMetadata:{openrouter:{usage:l}}})}})),response:{headers:i}}}},L1=E({prompt_tokens:q(),total_tokens:q(),cost:q().optional()}),Z1=E({object:C("embedding"),embedding:R(q()),index:q().optional()}),F1=E({id:w().optional(),object:C("list"),data:R(Z1),model:w(),usage:L1.optional()}),q1=class{constructor(e,t,r){this.specificationVersion="v2",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=t,this.config=r}async doEmbed(e){var t;const{values:r,abortSignal:o,headers:n}=e,i=ue(ue({model:this.modelId,input:r,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:a,responseHeaders:s}=await Bn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Vn(this.config.headers(),n),body:i,failedResponseHandler:Jn,successfulResponseHandler:Uc(F1),abortSignal:o,fetch:this.config.fetch});return{embeddings:a.data.map(l=>l.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,providerMetadata:(t=a.usage)!=null&&t.cost?{openrouter:{usage:{cost:a.usage.cost}}}:void 0,response:{headers:s,body:a}}}};function V1(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null))}function B1(e,...t){const r=V1(e??{}),n=[r["user-agent"]||"",...t].filter(Boolean).join(" ");return Ai(ue({},r),{"user-agent":n})}var J1="1.5.4";function ax(e={}){var t,r,o;const n=(r=x1((t=e.baseURL)!=null?t:e.baseUrl))!=null?r:"https://openrouter.ai/api/v1",i=(o=e.compatibility)!=null?o:"compatible",a=()=>B1(ue(ue({Authorization:`Bearer ${i1({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/${J1}`),s=(f,p={})=>new M1(f,p,{provider:"openrouter.chat",url:({path:g})=>`${n}${g}`,headers:a,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),l=(f,p={})=>new U1(f,p,{provider:"openrouter.completion",url:({path:g})=>`${n}${g}`,headers:a,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),u=(f,p={})=>new q1(f,p,{provider:"openrouter.embedding",url:({path:g})=>`${n}${g}`,headers:a,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):s(f,p)},d=(f,p)=>c(f,p);return d.languageModel=c,d.chat=s,d.completion=l,d.textEmbeddingModel=u,d.embedding=u,d}ax({compatibility:"strict"});function wu(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function sx(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((o,n)=>{if(r?.aborted){n(Wp());return}const i=setTimeout(()=>{a(),o()},e),a=()=>{clearTimeout(i),r?.removeEventListener("abort",s)},s=()=>{a(),n(Wp())};r?.addEventListener("abort",s)})}function Wp(){return new DOMException("Delay was aborted","AbortError")}function Oo(e){return Object.fromEntries([...e.headers])}var No=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const n=()=>{const i=r.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=r[Math.random()*i|0];return a.join("")};if(e==null)return n;if(r.includes(o))throw new Ji({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${r}".`});return()=>`${e}${o}${n()}`},W1=No();function ux(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function wr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var H1=["fetch failed","failed to fetch"];function lx({error:e,url:t,requestBodyValues:r}){if(wr(e))return e;if(e instanceof TypeError&&H1.includes(e.message.toLowerCase())){const o=e.cause;if(o!=null)return new Be({message:`Cannot connect to API: ${o.message}`,cause:o,url:t,requestBodyValues:r,isRetryable:!0})}return e}function Vc(e=globalThis){var t,r,o;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(r=e.process)==null?void 0:r.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function G1(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,o)=>{t[o.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,o]of e)o!=null&&(t[r.toLowerCase()]=o)}return t}function Wa(e,...t){const r=new Headers(G1(e)),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var cx="3.0.16",K1=()=>globalThis.fetch,Hp=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:o,abortSignal:n,fetch:i=K1()})=>{try{const a=await i(e,{method:"GET",headers:Wa(t,`ai-sdk/provider-utils/${cx}`,Vc()),signal:n}),s=Oo(a);if(!a.ok){let l;try{l=await o({response:a,url:e,requestBodyValues:{}})}catch(u){throw wr(u)||Be.isInstance(u)?u:new Be({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(wr(l)||Be.isInstance(l))?l:new Be({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(a){throw lx({error:a,url:e,requestBodyValues:{}})}};function Y1({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([o,n])=>{const i=o.toLowerCase();return i==="*"||i==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:i.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:o})=>e.startsWith(o)).flatMap(({regexes:o})=>o).some(o=>o.test(t))}function ai({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 Q1=/"__proto__"\s*:/,X1=/"constructor"\s*:/;function eA(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Q1.test(e)===!1&&X1.test(e)===!1?t:tA(t)}function tA(e){let t=[e];for(;t.length;){const r=t;t=[];for(const o of r){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in o){const i=o[n];i&&typeof i=="object"&&t.push(i)}}}return e}function dx(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return eA(e)}finally{Error.stackTraceLimit=t}}var Mi=Symbol.for("vercel.ai.validator");function rA(e){return{[Mi]:!0,validate:e}}function nA(e){return typeof e=="object"&&e!==null&&Mi in e&&e[Mi]===!0&&"validate"in e}function cn(e){let t;return()=>(t==null&&(t=e()),t)}function oA(e){return nA(e)?e:typeof e=="function"?e():iA(e)}function iA(e){return rA(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Ft({value:t,cause:r.issues})}})}async function xu({value:e,schema:t}){const r=await sr({value:e,schema:t});if(!r.success)throw Ft.wrap({value:e,cause:r.error});return r.value}async function sr({value:e,schema:t}){const r=oA(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:Ft.wrap({value:e,cause:o.error}),rawValue:e}}catch(o){return{success:!1,error:Ft.wrap({value:e,cause:o}),rawValue:e}}}async function aA({text:e,schema:t}){try{const r=dx(e);return t==null?r:xu({value:r,schema:t})}catch(r){throw Jr.isInstance(r)||Ft.isInstance(r)?r:new Jr({text:e,cause:r})}}async function xr({text:e,schema:t}){try{const r=dx(e);return t==null?{success:!0,value:r,rawValue:r}:await sr({value:r,schema:t})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:e,cause:r}),rawValue:void 0}}}function sA({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Pn).pipeThrough(new TransformStream({async transform({data:r},o){r!=="[DONE]"&&o.enqueue(await xr({text:r,schema:t}))}}))}var uA=()=>globalThis.fetch,$u=async({url:e,headers:t,body:r,failedResponseHandler:o,successfulResponseHandler:n,abortSignal:i,fetch:a})=>lA({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:o,successfulResponseHandler:n,abortSignal:i,fetch:a}),lA=async({url:e,headers:t={},body:r,successfulResponseHandler:o,failedResponseHandler:n,abortSignal:i,fetch:a=uA()})=>{try{const s=await a(e,{method:"POST",headers:Wa(t,`ai-sdk/provider-utils/${cx}`,Vc()),body:r.content,signal:i}),l=Oo(s);if(!s.ok){let u;try{u=await n({response:s,url:e,requestBodyValues:r.values})}catch(c){throw wr(c)||Be.isInstance(c)?c:new Be({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await o({response:s,url:e,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(wr(u)||Be.isInstance(u))?u:new Be({message:"Failed to process successful response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw lx({error:s,url:e,requestBodyValues:r.values})}};async function tr(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Wn=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:o,url:n,requestBodyValues:i})=>{const a=await o.text(),s=Oo(o);if(a.trim()==="")return{responseHeaders:s,value:new Be({message:o.statusText,url:n,requestBodyValues:i,statusCode:o.status,responseHeaders:s,responseBody:a,isRetryable:r?.(o)})};try{const l=await aA({text:a,schema:e});return{responseHeaders:s,value:new Be({message:t(l),url:n,requestBodyValues:i,statusCode:o.status,responseHeaders:s,responseBody:a,data:l,isRetryable:r?.(o,l)})}}catch{return{responseHeaders:s,value:new Be({message:o.statusText,url:n,requestBodyValues:i,statusCode:o.status,responseHeaders:s,responseBody:a,isRetryable:r?.(o)})}}},cA=e=>async({response:t})=>{const r=Oo(t);if(t.body==null)throw new T0({});return{responseHeaders:r,value:sA({stream:t.body,schema:e})}},Di=e=>async({response:t,url:r,requestBodyValues:o})=>{const n=await t.text(),i=await xr({text:n,schema:e}),a=Oo(t);if(!i.success)throw new Be({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:a,responseBody:n,url:r,requestBodyValues:o});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}},dA=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},pA=Symbol("Let zodToJsonSchema decide on which parser to use"),Gp={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"},fA=e=>typeof e=="string"?{...Gp,name:e}:{...Gp,...e};function tt(){return{}}function mA(e,t){var r,o,n;const i={type:"array"};return(r=e.type)!=null&&r._def&&((n=(o=e.type)==null?void 0:o._def)==null?void 0:n.typeName)!==A.ZodAny&&(i.items=ce(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}function hA(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function gA(){return{type:"boolean"}}function px(e,t){return ce(e.type._def,t)}var vA=(e,t)=>ce(e.innerType._def,t);function fx(e,t,r){const o=r??t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>fx(e,t,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return yA(e)}}var yA=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function bA(e,t){return{...ce(e.innerType._def,t),default:e.defaultValue()}}function _A(e,t){return t.effectStrategy==="input"?ce(e.schema._def,t):tt()}function wA(e){return{type:"string",enum:Array.from(e.values)}}var xA=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function $A(e,t){const r=[ce(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ce(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(n=>!!n),o=[];return r.forEach(n=>{if(xA(n))o.push(...n.allOf);else{let i=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:a,...s}=n;i=s}o.push(i)}}),o.length?{allOf:o}:void 0}function SA(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 Ps=void 0,vt={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:()=>(Ps===void 0&&(Ps=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ps),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 mx(e,t){const r={type:"string"};if(e.checks)for(const o of e.checks)switch(o.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value;break;case"email":switch(t.emailStrategy){case"format:email":yt(r,"email",o.message,t);break;case"format:idn-email":yt(r,"idn-email",o.message,t);break;case"pattern:zod":qe(r,vt.email,o.message,t);break}break;case"url":yt(r,"uri",o.message,t);break;case"uuid":yt(r,"uuid",o.message,t);break;case"regex":qe(r,o.regex,o.message,t);break;case"cuid":qe(r,vt.cuid,o.message,t);break;case"cuid2":qe(r,vt.cuid2,o.message,t);break;case"startsWith":qe(r,RegExp(`^${Cs(o.value,t)}`),o.message,t);break;case"endsWith":qe(r,RegExp(`${Cs(o.value,t)}$`),o.message,t);break;case"datetime":yt(r,"date-time",o.message,t);break;case"date":yt(r,"date",o.message,t);break;case"time":yt(r,"time",o.message,t);break;case"duration":yt(r,"duration",o.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value;break;case"includes":{qe(r,RegExp(Cs(o.value,t)),o.message,t);break}case"ip":{o.version!=="v6"&&yt(r,"ipv4",o.message,t),o.version!=="v4"&&yt(r,"ipv6",o.message,t);break}case"base64url":qe(r,vt.base64url,o.message,t);break;case"jwt":qe(r,vt.jwt,o.message,t);break;case"cidr":{o.version!=="v6"&&qe(r,vt.ipv4Cidr,o.message,t),o.version!=="v4"&&qe(r,vt.ipv6Cidr,o.message,t);break}case"emoji":qe(r,vt.emoji(),o.message,t);break;case"ulid":{qe(r,vt.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{yt(r,"binary",o.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{qe(r,vt.base64,o.message,t);break}}break}case"nanoid":qe(r,vt.nanoid,o.message,t)}return r}function Cs(e,t){return t.patternStrategy==="escape"?kA(e):e}var IA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function kA(e){let t="";for(let r=0;r<e.length;r++)IA.has(e[r])||(t+="\\"),t+=e[r];return t}function yt(e,t,r,o){var n;e.format||(n=e.anyOf)!=null&&n.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&o.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function qe(e,t,r,o){var n;e.pattern||(n=e.allOf)!=null&&n.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Kp(t,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Kp(t,o)}function Kp(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const o={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=o.i?e.source.toLowerCase():e.source;let i="",a=!1,s=!1,l=!1;for(let u=0;u<n.length;u++){if(a){i+=n[u],a=!1;continue}if(o.i){if(s){if(n[u].match(/[a-z]/)){l?(i+=n[u],i+=`${n[u-2]}-${n[u]}`.toUpperCase(),l=!1):n[u+1]==="-"&&((r=n[u+2])!=null&&r.match(/[a-z]/))?(i+=n[u],l=!0):i+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){i+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(o.m){if(n[u]==="^"){i+=`(^|(?<=[\r
|
|
66
|
-
]))`;continue}else if(
|
|
67
|
-
]))`;continue}}if(
|
|
68
|
-
`:`[${
|
|
69
|
-
]`;continue}i+=n[u],n[u]==="\\"?a=!0:s&&n[u]==="]"?s=!1:!s&&n[u]==="["&&(s=!0)}try{new RegExp(i)}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 i}function hx(e,t){var r,o,n,i,a,s;const l={type:"object",additionalProperties:(r=ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((o=e.keyType)==null?void 0:o._def.typeName)===A.ZodString&&((n=e.keyType._def.checks)!=null&&n.length)){const{type:u,...c}=mx(e.keyType._def,t);return{...l,propertyNames:c}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===A.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===A.ZodBranded&&e.keyType._def.type._def.typeName===A.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:u,...c}=px(e.keyType._def,t);return{...l,propertyNames:c}}}return l}function EA(e,t){if(t.mapStrategy==="record")return hx(e,t);const r=ce(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||tt(),o=ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||tt();return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function TA(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function OA(){return{not:tt()}}function NA(){return{type:"null"}}var Su={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function PA(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(o=>o._def.typeName in Su&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=Su[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return CA(e,t)}var CA=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>ce(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function jA(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Su[e.innerType._def.typeName],"null"]};const r=ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function AA(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function RA(e,t){const r={type:"object",properties:{}},o=[],n=e.shape();for(const a in n){let s=n[a];if(s===void 0||s._def===void 0)continue;const l=MA(s),u=ce(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,l||o.push(a))}o.length&&(r.required=o);const i=zA(e,t);return i!==void 0&&(r.additionalProperties=i),r}function zA(e,t){if(e.catchall._def.typeName!=="ZodNever")return ce(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 MA(e){try{return e.isOptional()}catch{return!0}}var DA=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return ce(e.innerType._def,t);const o=ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return o?{anyOf:[{not:tt()},o]}:tt()},UA=(e,t)=>{if(t.pipeStrategy==="input")return ce(e.in._def,t);if(t.pipeStrategy==="output")return ce(e.out._def,t);const r=ce(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=ce(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function LA(e,t){return ce(e.type._def,t)}function ZA(e,t){const o={type:"array",uniqueItems:!0,items:ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(o.minItems=e.minSize.value),e.maxSize&&(o.maxItems=e.maxSize.value),o}function FA(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:ce(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function qA(){return{not:tt()}}function VA(){return tt()}var BA=(e,t)=>ce(e.innerType._def,t),JA=(e,t,r)=>{switch(t){case A.ZodString:return mx(e,r);case A.ZodNumber:return AA(e);case A.ZodObject:return RA(e,r);case A.ZodBigInt:return hA(e);case A.ZodBoolean:return gA();case A.ZodDate:return fx(e,r);case A.ZodUndefined:return qA();case A.ZodNull:return NA();case A.ZodArray:return mA(e,r);case A.ZodUnion:case A.ZodDiscriminatedUnion:return PA(e,r);case A.ZodIntersection:return $A(e,r);case A.ZodTuple:return FA(e,r);case A.ZodRecord:return hx(e,r);case A.ZodLiteral:return SA(e);case A.ZodEnum:return wA(e);case A.ZodNativeEnum:return TA(e);case A.ZodNullable:return jA(e,r);case A.ZodOptional:return DA(e,r);case A.ZodMap:return EA(e,r);case A.ZodSet:return ZA(e,r);case A.ZodLazy:return()=>e.getter()._def;case A.ZodPromise:return LA(e,r);case A.ZodNaN:case A.ZodNever:return OA();case A.ZodEffects:return _A(e,r);case A.ZodAny:return tt();case A.ZodUnknown:return VA();case A.ZodDefault:return bA(e,r);case A.ZodBranded:return px(e,r);case A.ZodReadonly:return BA(e,r);case A.ZodCatch:return vA(e,r);case A.ZodPipeline:return UA(e,r);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(o=>{})()}};function ce(e,t,r=!1){var o;const n=t.seen.get(e);if(t.override){const l=(o=t.override)==null?void 0:o.call(t,e,t,n,r);if(l!==pA)return l}if(n&&!r){const l=WA(n,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=JA(e,e.typeName,t),s=typeof a=="function"?ce(a(),t):a;if(s&&HA(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return i.jsonSchema=s,l}return i.jsonSchema=s,s}var WA=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:dA(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),tt()):t.$refStrategy==="seen"?tt():void 0}},HA=(e,t,r)=>(e.description&&(r.description=e.description),r),GA=e=>{const t=fA(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([o,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,o],jsonSchema:void 0}]))}},KA=(e,t)=>{var r;const o=GA(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,d])=>{var f;return{...u,[c]:(f=ce(d._def,{...o,currentPath:[...o.basePath,o.definitionPath,c]},!0))!=null?f:tt()}},{}):void 0;const i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=ce(e._def,i===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,i]},!1))!=null?r:tt(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const l=i===void 0?n?{...a,[o.definitionPath]:n}:a:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,i].join("/"),[o.definitionPath]:{...n,[i]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},YA=KA;function QA(e,t){var r;const o=(r=void 0)!=null?r:!1;return Bc(()=>YA(e,{$refStrategy:o?"root":"none"}),{validate:async n=>{const i=await e.safeParseAsync(n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function XA(e,t){var r;const o=(r=void 0)!=null?r:!1;return Bc(()=>fa(e,{target:"draft-7",io:"output",reused:o?"ref":"inline"}),{validate:async n=>{const i=await ma(e,n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function eR(e){return"_zod"in e}function Or(e,t){return eR(e)?XA(e):QA(e)}var Iu=Symbol.for("vercel.ai.schema");function Bc(e,{validate:t}={}){return{[Iu]:!0,_type:void 0,[Mi]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function tR(e){return typeof e=="object"&&e!==null&&Iu in e&&e[Iu]===!0&&"jsonSchema"in e&&"validate"in e}function Ha(e){return e==null?Bc({properties:{},additionalProperties:!1}):tR(e)?e:typeof e=="function"?e():Or(e)}var{btoa:rR,atob:nR}=globalThis;function Jc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=nR(t);return Uint8Array.from(r,o=>o.codePointAt(0))}function ku(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return rR(t)}function oR(e){return e?.replace(/\/$/,"")}function iR(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*aR({execute:e,input:t,options:r}){const o=e(t,r);if(iR(o)){let n;for await(const i of o)n=i,yield{type:"preliminary",output:i};yield{type:"final",output:n}}else yield{type:"final",output:await o}}var js,Yp;function sR(){if(Yp)return js;Yp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,n=(c,d)=>{for(var f in d)e(c,f,{get:d[f],enumerable:!0})},i=(c,d,f,p)=>{if(d&&typeof d=="object"||typeof d=="function")for(let g of r(d))!o.call(c,g)&&g!==f&&e(c,g,{get:()=>d[g],enumerable:!(p=t(d,g))||p.enumerable});return c},a=c=>i(e({},"__esModule",{value:!0}),c),s={};n(s,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>u}),js=a(s);const l=Symbol.for("@vercel/request-context");function u(){return globalThis[l]?.get?.()??{}}return js}var As,Qp;function uR(){if(Qp)return As;Qp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,n=(d,f)=>{for(var p in f)e(d,p,{get:f[p],enumerable:!0})},i=(d,f,p,g)=>{if(f&&typeof f=="object"||typeof f=="function")for(let h of r(f))!o.call(d,h)&&h!==p&&e(d,h,{get:()=>f[h],enumerable:!(g=t(f,h))||g.enumerable});return d},a=d=>i(e({},"__esModule",{value:!0}),d),s={};n(s,{getContext:()=>l.getContext,getVercelOidcToken:()=>u,getVercelOidcTokenSync:()=>c}),As=a(s);var l=sR();async function u(){return""}function c(){return""}return As}var gx=uR(),lR="vercel.ai.gateway.error",Rs=Symbol.for(lR),Xp,ef,rt=class vx extends(ef=Error,Xp=Rs,ef){constructor({message:t,statusCode:r=500,cause:o}){super(t),this[Xp]=!0,this.statusCode=r,this.cause=o}static isInstance(t){return vx.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Rs in t&&t[Rs]===!0}},yx="GatewayAuthenticationError",cR=`vercel.ai.gateway.error.${yx}`,tf=Symbol.for(cR),rf,nf,Wc=class bx extends(nf=rt,rf=tf,nf){constructor({message:t="Authentication failed",statusCode:r=401,cause:o}={}){super({message:t,statusCode:r,cause:o}),this[rf]=!0,this.name=yx,this.type="authentication_error"}static isInstance(t){return rt.hasMarker(t)&&tf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:o="Authentication failed",statusCode:n=401,cause:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
106
|
+
`;break}case"tool":throw new qn({functionality:"tool messages"})}return r+=`${i}:
|
|
107
|
+
`,{prompt:r}}var Ug=ae([O({id:k().optional(),model:k().optional(),choices:W(O({text:k(),reasoning:k().nullish().optional(),reasoning_details:Jf.nullish(),finish_reason:k().nullish(),index:ee().nullish(),logprobs:O({tokens:W(k()),token_logprobs:W(ee()),top_logprobs:W(kt(k(),ee())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:O({prompt_tokens:ee(),prompt_tokens_details:O({cached_tokens:ee()}).passthrough().nullish(),completion_tokens:ee(),completion_tokens_details:O({reasoning_tokens:ee()}).passthrough().nullish(),total_tokens:ee(),cost:ee().optional(),cost_details:O({upstream_inference_cost:ee().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Wl]),$Z=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:a,responseFormat:s,topK:u,stopSequences:l,tools:c,toolChoice:d}){const{prompt:f}=TZ({prompt:e,inputFormat:"prompt"});if(c?.length)throw new qn({functionality:"tools"});if(d)throw new qn({functionality:"toolChoice"});return Se(Se({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:a,stop:l,response_format:s,top_k:u,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,a,s,u,l,c,d,f,p,g,m;const v=(e.providerOptions||{}).openrouter||{},x=Se(Se({},this.getArgs(e)),v),{value:S,responseHeaders:b}=await uo({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:lo(this.config.headers(),e.headers),body:x,failedResponseHandler:co,successfulResponseHandler:qf(Ug),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in S){const E=S.error;throw new Xt({message:E.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:x,statusCode:200,responseHeaders:b,data:E})}const A=S.choices[0];if(!A)throw new u0({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=A.text)!=null?t:""}],finishReason:$s(A.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:((s=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?s:0)+((l=(u=S.usage)==null?void 0:u.completion_tokens)!=null?l:0),reasoningTokens:(f=(d=(c=S.usage)==null?void 0:c.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:0,cachedInputTokens:(m=(g=(p=S.usage)==null?void 0:p.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?m:0},warnings:[],response:{headers:b}}}async doStream(e){const n=(e.providerOptions||{}).openrouter||{},i=Se(Se({},this.getArgs(e)),n),{value:r,responseHeaders:o}=await uo({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:lo(this.config.headers(),e.headers),body:Es(Se({},i),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:co,successfulResponseHandler:y0(Ug),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="other";const s={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},u={};return{stream:r.pipeThrough(new TransformStream({transform(l,c){var d,f,p;if(!l.success){a="error",c.enqueue({type:"error",error:l.error});return}const g=l.value;if("error"in g){a="error",c.enqueue({type:"error",error:g.error});return}if(g.usage!=null){if(s.inputTokens=g.usage.prompt_tokens,s.outputTokens=g.usage.completion_tokens,s.totalTokens=g.usage.prompt_tokens+g.usage.completion_tokens,u.promptTokens=g.usage.prompt_tokens,g.usage.prompt_tokens_details){const v=(d=g.usage.prompt_tokens_details.cached_tokens)!=null?d:0;s.cachedInputTokens=v,u.promptTokensDetails={cachedTokens:v}}if(u.completionTokens=g.usage.completion_tokens,g.usage.completion_tokens_details){const v=(f=g.usage.completion_tokens_details.reasoning_tokens)!=null?f:0;s.reasoningTokens=v,u.completionTokensDetails={reasoningTokens:v}}u.cost=g.usage.cost,u.totalTokens=g.usage.total_tokens;const y=(p=g.usage.cost_details)==null?void 0:p.upstream_inference_cost;y!=null&&(u.costDetails={upstreamInferenceCost:y})}const m=g.choices[0];m?.finish_reason!=null&&(a=$s(m.finish_reason)),m?.text!=null&&c.enqueue({type:"text-delta",delta:m.text,id:Gt()})},flush(l){l.enqueue({type:"finish",finishReason:a,usage:s,providerMetadata:{openrouter:{usage:u}}})}})),response:{headers:o}}}},CZ=O({prompt_tokens:ee(),total_tokens:ee(),cost:ee().optional()}),AZ=O({object:L("embedding"),embedding:W(ee()),index:ee().optional()}),PZ=O({id:k().optional(),object:L("list"),data:W(AZ),model:k(),usage:CZ.optional()}),RZ=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=Se(Se({model:this.modelId,input:n,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:a,responseHeaders:s}=await uo({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:lo(this.config.headers(),r),body:o,failedResponseHandler:co,successfulResponseHandler:qf(PZ),abortSignal:i,fetch:this.config.fetch});return{embeddings:a.data.map(u=>u.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,providerMetadata:(t=a.usage)!=null&&t.cost?{openrouter:{usage:{cost:a.usage.cost}}}:void 0,response:{headers:s,body:a}}}};function OZ(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null))}function NZ(e,...t){const n=OZ(e??{}),r=[n["user-agent"]||"",...t].filter(Boolean).join(" ");return Es(Se({},n),{"user-agent":r})}var jZ="1.5.4";function S0(e={}){var t,n,i;const r=(n=dZ((t=e.baseURL)!=null?t:e.baseUrl))!=null?n:"https://openrouter.ai/api/v1",o=(i=e.compatibility)!=null?i:"compatible",a=()=>NZ(Se(Se({Authorization:`Bearer ${WB({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/${jZ}`),s=(f,p={})=>new EZ(f,p,{provider:"openrouter.chat",url:({path:g})=>`${r}${g}`,headers:a,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),u=(f,p={})=>new $Z(f,p,{provider:"openrouter.completion",url:({path:g})=>`${r}${g}`,headers:a,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),l=(f,p={})=>new RZ(f,p,{provider:"openrouter.embedding",url:({path:g})=>`${r}${g}`,headers:a,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"?u(f,p):s(f,p)},d=(f,p)=>c(f,p);return d.languageModel=c,d.chat=s,d.completion=u,d.textEmbeddingModel=l,d.embedding=l,d}S0({compatibility:"strict"});function Vc(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function I0(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((i,r)=>{if(n?.aborted){r(Lg());return}const o=setTimeout(()=>{a(),i()},e),a=()=>{clearTimeout(o),n?.removeEventListener("abort",s)},s=()=>{a(),r(Lg())};n?.addEventListener("abort",s)})}function Lg(){return new DOMException("Delay was aborted","AbortError")}function ea(e){return Object.fromEntries([...e.headers])}var ta=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new js({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},MZ=ta();function k0(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function br(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var zZ=["fetch failed","failed to fetch"];function E0({error:e,url:t,requestBodyValues:n}){if(br(e))return e;if(e instanceof TypeError&&zZ.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new ut({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Gf(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 DZ(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 Gl(e,...t){const n=new Headers(DZ(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var T0="3.0.16",UZ=()=>globalThis.fetch,Fg=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:i,abortSignal:r,fetch:o=UZ()})=>{try{const a=await o(e,{method:"GET",headers:Gl(t,`ai-sdk/provider-utils/${T0}`,Gf()),signal:r}),s=ea(a);if(!a.ok){let u;try{u=await i({response:a,url:e,requestBodyValues:{}})}catch(l){throw br(l)||ut.isInstance(l)?l:new ut({message:"Failed to process error response",cause:l,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw u.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(u){throw u instanceof Error&&(br(u)||ut.isInstance(u))?u:new ut({message:"Failed to process successful response",cause:u,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(a){throw E0({error:a,url:e,requestBodyValues:{}})}};function LZ({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 Ha({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 FZ=/"__proto__"\s*:/,BZ=/"constructor"\s*:/;function ZZ(e){const t=JSON.parse(e);return t===null||typeof t!="object"||FZ.test(e)===!1&&BZ.test(e)===!1?t:qZ(t)}function qZ(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 $0(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ZZ(e)}finally{Error.stackTraceLimit=t}}var Cs=Symbol.for("vercel.ai.validator");function VZ(e){return{[Cs]:!0,validate:e}}function HZ(e){return typeof e=="object"&&e!==null&&Cs in e&&e[Cs]===!0&&"validate"in e}function gi(e){let t;return()=>(t==null&&(t=e()),t)}function JZ(e){return HZ(e)?e:typeof e=="function"?e():WZ(e)}function WZ(e){return VZ(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Cn({value:t,cause:n.issues})}})}async function Hc({value:e,schema:t}){const n=await er({value:e,schema:t});if(!n.success)throw Cn.wrap({value:e,cause:n.error});return n.value}async function er({value:e,schema:t}){const n=JZ(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:Cn.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:Cn.wrap({value:e,cause:i}),rawValue:e}}}async function GZ({text:e,schema:t}){try{const n=$0(e);return t==null?n:Hc({value:n,schema:t})}catch(n){throw Gr.isInstance(n)||Cn.isInstance(n)?n:new Gr({text:e,cause:n})}}async function _r({text:e,schema:t}){try{const n=$0(e);return t==null?{success:!0,value:n,rawValue:n}:await er({value:n,schema:t})}catch(n){return{success:!1,error:Gr.isInstance(n)?n:new Gr({text:e,cause:n}),rawValue:void 0}}}function KZ({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await _r({text:n,schema:t}))}}))}var YZ=()=>globalThis.fetch,Jc=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a})=>QZ({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a}),QZ=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:a=YZ()})=>{try{const s=await a(e,{method:"POST",headers:Gl(t,`ai-sdk/provider-utils/${T0}`,Gf()),body:n.content,signal:o}),u=ea(s);if(!s.ok){let l;try{l=await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw br(c)||ut.isInstance(c)?c:new ut({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}throw l.value}try{return await i({response:s,url:e,requestBodyValues:n.values})}catch(l){throw l instanceof Error&&(br(l)||ut.isInstance(l))?l:new ut({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}}catch(s){throw E0({error:s,url:e,requestBodyValues:n.values})}};async function Hn(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var po=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const a=await i.text(),s=ea(i);if(a.trim()==="")return{responseHeaders:s,value:new ut({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})};try{const u=await GZ({text:a,schema:e});return{responseHeaders:s,value:new ut({message:t(u),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,data:u,isRetryable:n?.(i,u)})}}catch{return{responseHeaders:s,value:new ut({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})}}},XZ=e=>async({response:t})=>{const n=ea(t);if(t.body==null)throw new $A({});return{responseHeaders:n,value:KZ({stream:t.body,schema:e})}},As=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await _r({text:r,schema:e}),a=ea(t);if(!o.success)throw new ut({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:a,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},eq=(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("/")},tq=Symbol("Let zodToJsonSchema decide on which parser to use"),Bg={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"},nq=e=>typeof e=="string"?{...Bg,name:e}:{...Bg,...e};function $t(){return{}}function rq(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)!==J.ZodAny&&(o.items=ke(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 iq(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 oq(){return{type:"boolean"}}function C0(e,t){return ke(e.type._def,t)}var aq=(e,t)=>ke(e.innerType._def,t);function A0(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>A0(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 sq(e)}}var sq=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 lq(e,t){return{...ke(e.innerType._def,t),default:e.defaultValue()}}function uq(e,t){return t.effectStrategy==="input"?ke(e.schema._def,t):$t()}function cq(e){return{type:"string",enum:Array.from(e.values)}}var dq=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function pq(e,t){const n=[ke(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ke(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(dq(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:a,...s}=r;o=s}i.push(o)}}),i.length?{allOf:i}:void 0}function fq(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 Lu=void 0,Jt={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:()=>(Lu===void 0&&(Lu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Lu),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 P0(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":Wt(n,"email",i.message,t);break;case"format:idn-email":Wt(n,"idn-email",i.message,t);break;case"pattern:zod":st(n,Jt.email,i.message,t);break}break;case"url":Wt(n,"uri",i.message,t);break;case"uuid":Wt(n,"uuid",i.message,t);break;case"regex":st(n,i.regex,i.message,t);break;case"cuid":st(n,Jt.cuid,i.message,t);break;case"cuid2":st(n,Jt.cuid2,i.message,t);break;case"startsWith":st(n,RegExp(`^${Fu(i.value,t)}`),i.message,t);break;case"endsWith":st(n,RegExp(`${Fu(i.value,t)}$`),i.message,t);break;case"datetime":Wt(n,"date-time",i.message,t);break;case"date":Wt(n,"date",i.message,t);break;case"time":Wt(n,"time",i.message,t);break;case"duration":Wt(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":{st(n,RegExp(Fu(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&Wt(n,"ipv4",i.message,t),i.version!=="v4"&&Wt(n,"ipv6",i.message,t);break}case"base64url":st(n,Jt.base64url,i.message,t);break;case"jwt":st(n,Jt.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&st(n,Jt.ipv4Cidr,i.message,t),i.version!=="v4"&&st(n,Jt.ipv6Cidr,i.message,t);break}case"emoji":st(n,Jt.emoji(),i.message,t);break;case"ulid":{st(n,Jt.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Wt(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{st(n,Jt.base64,i.message,t);break}}break}case"nanoid":st(n,Jt.nanoid,i.message,t)}return n}function Fu(e,t){return t.patternStrategy==="escape"?mq(e):e}var hq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mq(e){let t="";for(let n=0;n<e.length;n++)hq.has(e[n])||(t+="\\"),t+=e[n];return t}function Wt(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 st(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:Zg(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Zg(t,i)}function Zg(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="",a=!1,s=!1,u=!1;for(let l=0;l<r.length;l++){if(a){o+=r[l],a=!1;continue}if(i.i){if(s){if(r[l].match(/[a-z]/)){u?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),u=!1):r[l+1]==="-"&&((n=r[l+2])!=null&&n.match(/[a-z]/))?(o+=r[l],u=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(i.m){if(r[l]==="^"){o+=`(^|(?<=[\r
|
|
108
|
+
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
|
|
109
|
+
]))`;continue}}if(i.s&&r[l]==="."){o+=s?`${r[l]}\r
|
|
110
|
+
`:`[${r[l]}\r
|
|
111
|
+
]`;continue}o+=r[l],r[l]==="\\"?a=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!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 R0(e,t){var n,i,r,o,a,s;const u={type:"object",additionalProperties:(n=ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===J.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:l,...c}=P0(e.keyType._def,t);return{...u,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===J.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===J.ZodBranded&&e.keyType._def.type._def.typeName===J.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:l,...c}=C0(e.keyType._def,t);return{...u,propertyNames:c}}}return u}function gq(e,t){if(t.mapStrategy==="record")return R0(e,t);const n=ke(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||$t(),i=ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||$t();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function vq(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 yq(){return{not:$t()}}function bq(){return{type:"null"}}var Wc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _q(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in Wc&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const a=Wc[o._def.typeName];return a&&!r.includes(a)?[...r,a]: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 a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];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,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._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 wq(e,t)}var wq=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>ke(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 xq(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Wc[e.innerType._def.typeName],"null"]};const n=ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Sq(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 Iq(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const a in r){let s=r[a];if(s===void 0||s._def===void 0)continue;const u=Eq(s),l=ke(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);const o=kq(e,t);return o!==void 0&&(n.additionalProperties=o),n}function kq(e,t){if(e.catchall._def.typeName!=="ZodNever")return ke(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 Eq(e){try{return e.isOptional()}catch{return!0}}var Tq=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return ke(e.innerType._def,t);const i=ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:$t()},i]}:$t()},$q=(e,t)=>{if(t.pipeStrategy==="input")return ke(e.in._def,t);if(t.pipeStrategy==="output")return ke(e.out._def,t);const n=ke(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=ke(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function Cq(e,t){return ke(e.type._def,t)}function Aq(e,t){const i={type:"array",uniqueItems:!0,items:ke(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 Pq(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>ke(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:ke(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>ke(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function Rq(){return{not:$t()}}function Oq(){return $t()}var Nq=(e,t)=>ke(e.innerType._def,t),jq=(e,t,n)=>{switch(t){case J.ZodString:return P0(e,n);case J.ZodNumber:return Sq(e);case J.ZodObject:return Iq(e,n);case J.ZodBigInt:return iq(e);case J.ZodBoolean:return oq();case J.ZodDate:return A0(e,n);case J.ZodUndefined:return Rq();case J.ZodNull:return bq();case J.ZodArray:return rq(e,n);case J.ZodUnion:case J.ZodDiscriminatedUnion:return _q(e,n);case J.ZodIntersection:return pq(e,n);case J.ZodTuple:return Pq(e,n);case J.ZodRecord:return R0(e,n);case J.ZodLiteral:return fq(e);case J.ZodEnum:return cq(e);case J.ZodNativeEnum:return vq(e);case J.ZodNullable:return xq(e,n);case J.ZodOptional:return Tq(e,n);case J.ZodMap:return gq(e,n);case J.ZodSet:return Aq(e,n);case J.ZodLazy:return()=>e.getter()._def;case J.ZodPromise:return Cq(e,n);case J.ZodNaN:case J.ZodNever:return yq();case J.ZodEffects:return uq(e,n);case J.ZodAny:return $t();case J.ZodUnknown:return Oq();case J.ZodDefault:return lq(e,n);case J.ZodBranded:return C0(e,n);case J.ZodReadonly:return Nq(e,n);case J.ZodCatch:return aq(e,n);case J.ZodPipeline:return $q(e,n);case J.ZodFunction:case J.ZodVoid:case J.ZodSymbol:return;default:return(i=>{})()}};function ke(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const u=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(u!==tq)return u}if(r&&!n){const u=Mq(r,t);if(u!==void 0)return u}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const a=jq(e,e.typeName,t),s=typeof a=="function"?ke(a(),t):a;if(s&&zq(e,t,s),t.postProcess){const u=t.postProcess(s,e,t);return o.jsonSchema=s,u}return o.jsonSchema=s,s}var Mq=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:eq(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`),$t()):t.$refStrategy==="seen"?$t():void 0}},zq=(e,t,n)=>(e.description&&(n.description=e.description),n),Dq=e=>{const t=nq(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}]))}},Uq=(e,t)=>{var n;const i=Dq(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,d])=>{var f;return{...l,[c]:(f=ke(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:$t()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=ke(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:$t(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const u=o===void 0?r?{...a,[i.definitionPath]:r}:a:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:a}};return u.$schema="http://json-schema.org/draft-07/schema#",u},Lq=Uq;function Fq(e,t){var n;const i=(n=void 0)!=null?n:!1;return Kf(()=>Lq(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 Bq(e,t){var n;const i=(n=void 0)!=null?n:!1;return Kf(()=>nl(e,{target:"draft-7",io:"output",reused:i?"ref":"inline"}),{validate:async r=>{const o=await rl(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Zq(e){return"_zod"in e}function Tr(e,t){return Zq(e)?Bq(e):Fq(e)}var Gc=Symbol.for("vercel.ai.schema");function Kf(e,{validate:t}={}){return{[Gc]:!0,_type:void 0,[Cs]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function qq(e){return typeof e=="object"&&e!==null&&Gc in e&&e[Gc]===!0&&"jsonSchema"in e&&"validate"in e}function Kl(e){return e==null?Kf({properties:{},additionalProperties:!1}):qq(e)?e:typeof e=="function"?e():Tr(e)}var{btoa:Vq,atob:Hq}=globalThis;function Yf(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Hq(t);return Uint8Array.from(n,i=>i.codePointAt(0))}function Kc(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Vq(t)}function Jq(e){return e?.replace(/\/$/,"")}function Wq(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Gq({execute:e,input:t,options:n}){const i=e(t,n);if(Wq(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 Bu,qg;function Kq(){if(qg)return Bu;qg=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 g of n(d))!i.call(c,g)&&g!==f&&e(c,g,{get:()=>d[g],enumerable:!(p=t(d,g))||p.enumerable});return c},a=c=>o(e({},"__esModule",{value:!0}),c),s={};r(s,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>l}),Bu=a(s);const u=Symbol.for("@vercel/request-context");function l(){return globalThis[u]?.get?.()??{}}return Bu}var Zu,Vg;function Yq(){if(Vg)return Zu;Vg=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,g)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!i.call(d,m)&&m!==p&&e(d,m,{get:()=>f[m],enumerable:!(g=t(f,m))||g.enumerable});return d},a=d=>o(e({},"__esModule",{value:!0}),d),s={};r(s,{getContext:()=>u.getContext,getVercelOidcToken:()=>l,getVercelOidcTokenSync:()=>c}),Zu=a(s);var u=Kq();async function l(){return""}function c(){return""}return Zu}var O0=Yq(),Qq="vercel.ai.gateway.error",qu=Symbol.for(Qq),Hg,Jg,Ct=class N0 extends(Jg=Error,Hg=qu,Jg){constructor({message:t,statusCode:n=500,cause:i}){super(t),this[Hg]=!0,this.statusCode=n,this.cause=i}static isInstance(t){return N0.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&qu in t&&t[qu]===!0}},j0="GatewayAuthenticationError",Xq=`vercel.ai.gateway.error.${j0}`,Wg=Symbol.for(Xq),Gg,Kg,Qf=class M0 extends(Kg=Ct,Gg=Wg,Kg){constructor({message:t="Authentication failed",statusCode:n=401,cause:i}={}){super({message:t,statusCode:n,cause:i}),this[Gg]=!0,this.name=j0,this.type="authentication_error"}static isInstance(t){return Ct.hasMarker(t)&&Wg in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:i="Authentication failed",statusCode:r=401,cause:o}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
70
112
|
|
|
71
113
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
72
114
|
|
|
73
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:
|
|
115
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
|
|
74
116
|
|
|
75
117
|
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
76
118
|
|
|
@@ -81,64 +123,37 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
81
123
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
82
124
|
|
|
83
125
|
Option 2 - OIDC token:
|
|
84
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new bx({message:a,statusCode:n,cause:i})}},_x="GatewayInvalidRequestError",dR=`vercel.ai.gateway.error.${_x}`,of=Symbol.for(dR),af,sf,pR=class extends(sf=rt,af=of,sf){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[af]=!0,this.name=_x,this.type="invalid_request_error"}static isInstance(e){return rt.hasMarker(e)&&of in e}},wx="GatewayRateLimitError",fR=`vercel.ai.gateway.error.${wx}`,uf=Symbol.for(fR),lf,cf,mR=class extends(cf=rt,lf=uf,cf){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[lf]=!0,this.name=wx,this.type="rate_limit_exceeded"}static isInstance(e){return rt.hasMarker(e)&&uf in e}},xx="GatewayModelNotFoundError",hR=`vercel.ai.gateway.error.${xx}`,df=Symbol.for(hR),gR=cn(()=>Or(E({modelId:w()}))),pf,ff,$x=class extends(ff=rt,pf=df,ff){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[pf]=!0,this.name=xx,this.type="model_not_found",this.modelId=r}static isInstance(e){return rt.hasMarker(e)&&df in e}},Sx="GatewayInternalServerError",vR=`vercel.ai.gateway.error.${Sx}`,mf=Symbol.for(vR),hf,gf,vf=class extends(gf=rt,hf=mf,gf){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[hf]=!0,this.name=Sx,this.type="internal_server_error"}static isInstance(e){return rt.hasMarker(e)&&mf in e}},Ix="GatewayResponseError",yR=`vercel.ai.gateway.error.${Ix}`,yf=Symbol.for(yR),bf,_f,bR=class extends(_f=rt,bf=yf,_f){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:o,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[bf]=!0,this.name=Ix,this.type="response_error",this.response=r,this.validationError=o}static isInstance(e){return rt.hasMarker(e)&&yf in e}};async function wf({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:o,authMethod:n}){const i=await sr({value:e,schema:_R});if(!i.success)return new bR({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:o});const a=i.value,s=a.error.type,l=a.error.message;switch(s){case"authentication_error":return Wc.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:t,cause:o});case"invalid_request_error":return new pR({message:l,statusCode:t,cause:o});case"rate_limit_exceeded":return new mR({message:l,statusCode:t,cause:o});case"model_not_found":{const u=await sr({value:a.error.param,schema:gR});return new $x({message:l,statusCode:t,modelId:u.success?u.value.modelId:void 0,cause:o})}case"internal_server_error":return new vf({message:l,statusCode:t,cause:o});default:return new vf({message:l,statusCode:t,cause:o})}}var _R=cn(()=>Or(E({error:E({message:w(),type:w().nullish(),param:$e().nullish(),code:G([w(),q()]).nullish()})})));function $r(e,t){var r;return rt.isInstance(e)?e:Be.isInstance(e)?wf({response:wR(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):wf({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function wR(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 kx="ai-gateway-auth-method";async function Hn(e){const t=await sr({value:e[kx],schema:xR});return t.success?t.value:void 0}var xR=cn(()=>Or(G([C("api-key"),C("oidc")]))),xf=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Hp({url:`${this.config.baseURL}/config`,headers:await tr(this.config.headers()),successfulResponseHandler:Di($R),failedResponseHandler:Wn({errorSchema:Pe(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await $r(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Hp({url:`${e.origin}/v1/credits`,headers:await tr(this.config.headers()),successfulResponseHandler:Di(SR),failedResponseHandler:Wn({errorSchema:Pe(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await $r(e)}}},$R=cn(()=>Or(E({models:R(E({id:w(),name:w(),description:w().nullish(),pricing:E({input:w(),output:w(),input_cache_read:w().nullish(),input_cache_write:w().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:o})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...o?{cacheCreationInputTokens:o}:{}})).nullish(),specification:E({specificationVersion:C("v2"),provider:w(),modelId:w()}),modelType:dr(["language","embedding","image"]).nullish()}))}))),SR=cn(()=>Or(E({balance:w(),total_used:w()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),IR=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,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:o}=e,n=await tr(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:s}=await $u({url:this.getUrl(),headers:wu(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await tr(this.config.o11yHeaders)),body:t,successfulResponseHandler:Di(Pe()),failedResponseHandler:Wn({errorSchema:Pe(),errorToMessage:l=>l}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:i,body:s},warnings:r}}catch(i){throw await $r(i,await Hn(n))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:o}=e,n=await tr(this.config.headers());try{const{value:i,responseHeaders:a}=await $u({url:this.getUrl(),headers:wu(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await tr(this.config.o11yHeaders)),body:t,successfulResponseHandler:cA(Pe()),failedResponseHandler:Wn({errorSchema:Pe(),errorToMessage:s=>s}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(s){r.length>0&&s.enqueue({type:"stream-start",warnings:r})},transform(s,l){if(s.success){const u=s.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(s.error)}})),request:{body:t},response:{headers:a}}}catch(i){throw await $r(i,await Hn(n))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const o=r;if(o.data instanceof Uint8Array){const n=Uint8Array.from(o.data),i=Buffer.from(n).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${i}`)}}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)}}},kR=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:r,providerOptions:o}){var n;const i=await tr(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:l}=await $u({url:this.getUrl(),headers:wu(i,t??{},this.getModelConfigHeaders(),await tr(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...o?{providerOptions:o}:{}},successfulResponseHandler:Di(ER),failedResponseHandler:Wn({errorSchema:Pe(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(n=s.usage)!=null?n:void 0,providerMetadata:s.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await $r(a,await Hn(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},ER=cn(()=>Or(E({embeddings:R(R(q())),usage:E({tokens:q()}).nullish(),providerMetadata:Xe(w(),Xe(w(),$e())).optional()})));async function TR(){var e;return(e=gx.getContext().headers)==null?void 0:e["x-vercel-id"]}var OR="2.0.7",NR="0.0.1";function PR(e={}){var t,r;let o=null,n=null;const i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const s=(r=oR(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const g=await jR(e);if(g)return Wa({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":NR,[kx]:g.authMethod,...e.headers},`ai-sdk/gateway/${OR}`);throw Wc.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const g=ai({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),h=ai({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=ai({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await TR();return{...g&&{"ai-o11y-deployment-id":g},...h&&{"ai-o11y-environment":h},...b&&{"ai-o11y-region":b},...y&&{"ai-o11y-request-id":y}}}},c=g=>new IR(g,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),d=async()=>{var g,h,b;const y=(b=(h=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:h.call(g).getTime())!=null?b:Date.now();return(!o||y-a>i)&&(a=y,o=new xf({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then(x=>(n=x,x)).catch(async x=>{throw await $r(x,await Hn(await l()))})),n?Promise.resolve(n):o},f=async()=>new xf({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async g=>{throw await $r(g,await Hn(await l()))}),p=function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(g)};return p.getAvailableModels=d,p.getCredits=f,p.imageModel=g=>{throw new j0({modelId:g,modelType:"imageModel"})},p.languageModel=c,p.textEmbeddingModel=g=>new kR(g,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),p}var CR=PR();async function jR(e){const t=ai({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await gx.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var AR=Object.defineProperty,RR=(e,t)=>{for(var r in t)AR(e,r,{get:t[r],enumerable:!0})},Ex="AI_NoOutputSpecifiedError",Tx=`vercel.ai.error.${Ex}`,zR=Symbol.for(Tx),Ox,MR=class extends Y{constructor({message:e="No output specified."}={}){super({name:Ex,message:e}),this[Ox]=!0}static isInstance(e){return Y.hasMarker(e,Tx)}};Ox=zR;function DR(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let o=`${t} The tool "${r}" is not supported by this model`;return e.details&&(o+=` - ${e.details}`),o}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var UR="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",$f=!1,LR=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}$f||($f=!0,console.info(UR));for(const r of e)console.warn(DR(r))}},Nx="AI_InvalidArgumentError",Px=`vercel.ai.error.${Nx}`,ZR=Symbol.for(Px),Cx,Nt=class extends Y{constructor({parameter:e,value:t,message:r}){super({name:Nx,message:`Invalid argument for parameter ${e}: ${r}`}),this[Cx]=!0,this.parameter=e,this.value=t}static isInstance(e){return Y.hasMarker(e,Px)}};Cx=ZR;var jx="AI_InvalidToolInputError",Ax=`vercel.ai.error.${jx}`,FR=Symbol.for(Ax),Rx,zx=class extends Y{constructor({toolInput:e,toolName:t,cause:r,message:o=`Invalid input for tool ${t}: ${sn(r)}`}){super({name:jx,message:o,cause:r}),this[Rx]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return Y.hasMarker(e,Ax)}};Rx=FR;var Mx="AI_NoObjectGeneratedError",Dx=`vercel.ai.error.${Mx}`,qR=Symbol.for(Dx),Ux,Sf=class extends Y{constructor({message:e="No object generated.",cause:t,text:r,response:o,usage:n,finishReason:i}){super({name:Mx,message:e,cause:t}),this[Ux]=!0,this.text=r,this.response=o,this.usage=n,this.finishReason=i}static isInstance(e){return Y.hasMarker(e,Dx)}};Ux=qR;var Lx="AI_NoOutputGeneratedError",Zx=`vercel.ai.error.${Lx}`,VR=Symbol.for(Zx),Fx,BR=class extends Y{constructor({message:e="No output generated.",cause:t}={}){super({name:Lx,message:e,cause:t}),this[Fx]=!0}static isInstance(e){return Y.hasMarker(e,Zx)}};Fx=VR;var qx="AI_NoSuchToolError",Vx=`vercel.ai.error.${qx}`,JR=Symbol.for(Vx),Bx,Eu=class extends Y{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:qx,message:r}),this[Bx]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return Y.hasMarker(e,Vx)}};Bx=JR;var Jx="AI_ToolCallRepairError",Wx=`vercel.ai.error.${Jx}`,WR=Symbol.for(Wx),Hx,HR=class extends Y{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${sn(e)}`}){super({name:Jx,message:r,cause:e}),this[Hx]=!0,this.originalError=t}static isInstance(e){return Y.hasMarker(e,Wx)}};Hx=WR;var GR=class extends Y{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}},Gx="AI_InvalidMessageRoleError",Kx=`vercel.ai.error.${Gx}`,KR=Symbol.for(Kx),Yx,YR=class extends Y{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Gx,message:t}),this[Yx]=!0,this.role=e}static isInstance(e){return Y.hasMarker(e,Kx)}};Yx=KR;var Qx="AI_MessageConversionError",Xx=`vercel.ai.error.${Qx}`,QR=Symbol.for(Xx),e$,XR=class extends Y{constructor({originalMessage:e,message:t}){super({name:Qx,message:t}),this[e$]=!0,this.originalMessage=e}static isInstance(e){return Y.hasMarker(e,Xx)}};e$=QR;var t$="AI_DownloadError",r$=`vercel.ai.error.${t$}`,ez=Symbol.for(r$),n$,zs=class extends Y{constructor({url:e,statusCode:t,statusText:r,cause:o,message:n=o==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${o}`}){super({name:t$,message:n,cause:o}),this[n$]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return Y.hasMarker(e,r$)}};n$=ez;var o$="AI_RetryError",i$=`vercel.ai.error.${o$}`,tz=Symbol.for(i$),a$,If=class extends Y{constructor({message:e,reason:t,errors:r}){super({name:o$,message:e}),this[a$]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return Y.hasMarker(e,i$)}};a$=tz;function s$(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new GR({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return rz().languageModel(e)}function rz(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:CR}var nz=[{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]}],oz=e=>{const t=typeof e=="string"?Jc(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function iz(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?oz(e):e}function az({data:e,signatures:t}){const r=iz(e),o=typeof r=="string"?Jc(r.substring(0,Math.min(r.length,24))):r;for(const n of t)if(o.length>=n.bytesPrefix.length&&n.bytesPrefix.every((i,a)=>i===null||o[a]===i))return n.mediaType}var sz="5.0.90",uz=async({url:e})=>{var t;const r=e.toString();try{const o=await fetch(r,{headers:Wa({},`ai-sdk/${sz}`,Vc())});if(!o.ok)throw new zs({url:r,statusCode:o.status,statusText:o.statusText});return{data:new Uint8Array(await o.arrayBuffer()),mediaType:(t=o.headers.get("content-type"))!=null?t:void 0}}catch(o){throw zs.isInstance(o)?o:new zs({url:r,cause:o})}},lz=(e=uz)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function cz(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var u$=G([w(),Rt(Uint8Array),Rt(ArrayBuffer),So(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function l$(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:r}=cz(e.toString());if(t==null||r==null)throw new Y({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function dz(e){return typeof e=="string"?e:e instanceof ArrayBuffer?ku(new Uint8Array(e)):ku(e)}async function pz({prompt:e,supportedUrls:t,download:r=lz()}){const o=await mz(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(n=>fz({message:n,downloadedAssets:o}))]}function fz({message:e,downloadedAssets:t}){const r=e.role;switch(r){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(o=>hz(o,t)).filter(o=>o.type!=="text"||o.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(o=>o.type!=="text"||o.text!==""||o.providerOptions!=null).map(o=>{const n=o.providerOptions;switch(o.type){case"file":{const{data:i,mediaType:a}=l$(o.data);return{type:"file",data:i,filename:o.filename,mediaType:a??o.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:o.text,providerOptions:n};case"text":return{type:"text",text:o.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:o.output,providerOptions:n}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:o.output,providerOptions:o.providerOptions})),providerOptions:e.providerOptions};default:{const o=r;throw new YR({role:o})}}}async function mz(e,t,r){const o=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var a;const s=(a=i.mediaType)!=null?a:i.type==="image"?"image/*":void 0;let l=i.type==="image"?i.image:i.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:s,data:l}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&Y1({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:r})})),n=await t(o);return Object.fromEntries(n.map((i,a)=>i==null?null:[o[a].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}function hz(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let o;const n=e.type;switch(n){case"image":o=e.image;break;case"file":o=e.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:i,mediaType:a}=l$(o);let s=a??e.mediaType,l=i;if(l instanceof URL){const u=t[l.toString()];u&&(l=u.data,s??(s=u.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(r=az({data:l,signatures:nz}))!=null?r:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function gz({maxOutputTokens:e,temperature:t,topP:r,topK:o,presencePenalty:n,frequencyPenalty:i,seed:a,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new Nt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Nt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Nt({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Nt({parameter:"topP",value:r,message:"topP must be a number"});if(o!=null&&typeof o!="number")throw new Nt({parameter:"topK",value:o,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new Nt({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new Nt({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Nt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:o,presencePenalty:n,frequencyPenalty:i,stopSequences:s,seed:a}}function vz(e){return e!=null&&Object.keys(e).length>0}function yz({tools:e,toolChoice:t,activeTools:r}){return vz(e)?{tools:(r!=null?Object.entries(e).filter(([n])=>r.includes(n)):Object.entries(e)).map(([n,i])=>{const a=i.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:i.description,inputSchema:Ha(i.inputSchema).jsonSchema,providerOptions:i.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:i.id,args:i.args};default:{const s=a;throw new Error(`Unsupported tool type: ${s}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Gn=xo(()=>G([yo(),w(),q(),pe(),Xe(w(),Gn),R(Gn)])),Mt=Xe(w(),Xe(w(),Gn)),c$=E({type:C("text"),text:w(),providerOptions:Mt.optional()}),bz=E({type:C("image"),image:G([u$,Rt(URL)]),mediaType:w().optional(),providerOptions:Mt.optional()}),d$=E({type:C("file"),data:G([u$,Rt(URL)]),filename:w().optional(),mediaType:w(),providerOptions:Mt.optional()}),_z=E({type:C("reasoning"),text:w(),providerOptions:Mt.optional()}),wz=E({type:C("tool-call"),toolCallId:w(),toolName:w(),input:$e(),providerOptions:Mt.optional(),providerExecuted:pe().optional()}),xz=za("type",[E({type:C("text"),value:w()}),E({type:C("json"),value:Gn}),E({type:C("error-text"),value:w()}),E({type:C("error-json"),value:Gn}),E({type:C("content"),value:R(G([E({type:C("text"),text:w()}),E({type:C("media"),data:w(),mediaType:w()})]))})]),p$=E({type:C("tool-result"),toolCallId:w(),toolName:w(),output:xz,providerOptions:Mt.optional()}),$z=E({role:C("system"),content:w(),providerOptions:Mt.optional()}),Sz=E({role:C("user"),content:G([w(),R(G([c$,bz,d$]))]),providerOptions:Mt.optional()}),Iz=E({role:C("assistant"),content:G([w(),R(G([c$,d$,_z,wz,p$]))]),providerOptions:Mt.optional()}),kz=E({role:C("tool"),content:R(p$),providerOptions:Mt.optional()}),Ez=G([$z,Sz,Iz,kz]);async function Tz(e){if(e.prompt==null&&e.messages==null)throw new jr({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new jr({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new jr({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 jr({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new jr({prompt:e,message:"messages must not be empty"});const r=await sr({value:t,schema:R(Ez)});if(!r.success)throw new jr({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function Oz(e){return Wc.isInstance(e)||$x.isInstance(e)?new Y({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 Tu({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 Nz({model:e,settings:t,telemetry:r,headers:o}){var n;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[a,s])=>(i[`ai.settings.${a}`]=s,i),{}),...Object.entries((n=r?.metadata)!=null?n:{}).reduce((i,[a,s])=>(i[`ai.telemetry.metadata.${a}`]=s,i),{}),...Object.entries(o??{}).reduce((i,[a,s])=>(s!==void 0&&(i[`ai.request.headers.${a}`]=s),i),{})}}var Pz={startSpan(){return Jo},startActiveSpan(e,t,r,o){if(typeof t=="function")return t(Jo);if(typeof r=="function")return r(Jo);if(typeof o=="function")return o(Jo)}},Jo={spanContext(){return Cz},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}},Cz={traceId:"",spanId:"",traceFlags:0};function jz({isEnabled:e=!1,tracer:t}={}){return e?t||zC.getTracer("ai"):Pz}function Ou({name:e,tracer:t,attributes:r,fn:o,endWhenDone:n=!0}){return t.startActiveSpan(e,{attributes:r},async i=>{try{const a=await o(i);return n&&i.end(),a}catch(a){try{f$(i,a)}finally{i.end()}throw a}})}function f$(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ji.ERROR,message:t.message})):e.setStatus({code:ji.ERROR})}function Lr({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((r,[o,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if(e?.recordInputs===!1)return r;const i=n.input();return i==null?r:{...r,[o]:i}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if(e?.recordOutputs===!1)return r;const i=n.output();return i==null?r:{...r,[o]:i}}return{...r,[o]:n}},{})}function Az(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?dz(r.data):r.data}:r)})))}function Rz(e,t){return{inputTokens:xn(e.inputTokens,t.inputTokens),outputTokens:xn(e.outputTokens,t.outputTokens),totalTokens:xn(e.totalTokens,t.totalTokens),reasoningTokens:xn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:xn(e.cachedInputTokens,t.cachedInputTokens)}}function xn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function kf(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function zz({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let o;const n=r["retry-after-ms"];if(n){const a=parseFloat(n);Number.isNaN(a)||(o=a)}const i=r["retry-after"];if(i&&o===void 0){const a=parseFloat(i);Number.isNaN(a)?o=Date.parse(i)-Date.now():o=a*1e3}return o!=null&&!Number.isNaN(o)&&0<=o&&(o<60*1e3||o<t)?o:t}var Mz=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:o}={})=>async n=>m$(n,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:o});async function m$(e,{maxRetries:t,delayInMs:r,backoffFactor:o,abortSignal:n},i=[]){try{return await e()}catch(a){if(wr(a)||t===0)throw a;const s=ux(a),l=[...i,a],u=l.length;if(u>t)throw new If({message:`Failed after ${u} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Be.isInstance(a)&&a.isRetryable===!0&&u<=t)return await sx(zz({error:a,exponentialBackoffDelay:r}),{abortSignal:n}),m$(e,{maxRetries:t,delayInMs:o*r,backoffFactor:o,abortSignal:n},l);throw u===1?a:new If({message:`Failed after ${u} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function Dz({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Nt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Nt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:Mz({maxRetries:r,abortSignal:t})}}var Uz=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=ku(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Jc(this.base64Data)),this.uint8ArrayData}},Lz=class extends Uz{constructor(e){super(e),this.type="file"}};async function Zz({toolCall:e,tools:t,repairToolCall:r,system:o,messages:n}){try{if(t==null)throw new Eu({toolName:e.toolName});try{return await Ef({toolCall:e,tools:t})}catch(i){if(r==null||!(Eu.isInstance(i)||zx.isInstance(i)))throw i;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:({toolName:s})=>{const{inputSchema:l}=t[s];return Ha(l).jsonSchema},system:o,messages:n,error:i})}catch(s){throw new HR({cause:s,originalError:i})}if(a==null)throw i;return await Ef({toolCall:a,tools:t})}}catch(i){const a=await xr({text:e.input}),s=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:i}}}async function Ef({toolCall:e,tools:t}){const r=e.toolName,o=t[r];if(o==null)throw new Eu({toolName:e.toolName,availableTools:Object.keys(t)});const n=Ha(o.inputSchema),i=e.input.trim()===""?await sr({value:{},schema:n}):await xr({text:e.input,schema:n});if(i.success===!1)throw new zx({toolName:r,toolInput:e.input,cause:i.error});return o.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var Fz=class{constructor({content:e,finishReason:t,usage:r,warnings:o,request:n,response:i,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=o,this.request=n,this.response=i,this.providerMetadata=a}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 h$(e){return({steps:t})=>t.length===e}async function qz({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function Nn({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:sn(e)}:r==="json"?{type:"error-json",value:Tf(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:Tf(e)}}function Tf(e){return e===void 0?null:e}function Of({content:e,tools:t}){const r=[],o=e.filter(i=>i.type!=="source").filter(i=>(i.type!=="tool-result"||i.providerExecuted)&&(i.type!=="tool-error"||i.providerExecuted)).filter(i=>i.type!=="text"||i.text.length>0).map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,providerOptions:i.providerMetadata};case"reasoning":return{type:"reasoning",text:i.text,providerOptions:i.providerMetadata};case"file":return{type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Nn({tool:t?.[i.toolName],output:i.output,errorMode:"none"}),providerExecuted:!0,providerOptions:i.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Nn({tool:t?.[i.toolName],output:i.error,errorMode:"json"}),providerOptions:i.providerMetadata}}});o.length>0&&r.push({role:"assistant",content:o});const n=e.filter(i=>i.type==="tool-result"||i.type==="tool-error").filter(i=>!i.providerExecuted).map(i=>({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Nn({tool:t?.[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}No({prefix:"aitxt",size:24});function Ga(e,t){const r=new Headers(e??{});for(const[o,n]of Object.entries(t))r.has(o)||r.set(o,n);return r}function Vz({status:e,statusText:t,headers:r,textStream:o}){return new Response(o.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Ga(r,{"content-type":"text/plain; charset=utf-8"})})}function g$({response:e,status:t,statusText:r,headers:o,stream:n}){e.writeHead(t??200,r,o);const i=n.getReader();(async()=>{try{for(;;){const{done:s,value:l}=await i.read();if(s)break;e.write(l)||await new Promise(c=>{e.once("drain",c)})}}catch(s){throw s}finally{e.end()}})()}function Bz({response:e,status:t,statusText:r,headers:o,textStream:n}){g$({response:e,status:t,statusText:r,headers:Object.fromEntries(Ga(o,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var v$=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
126
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new M0({message:a,statusCode:r,cause:o})}},z0="GatewayInvalidRequestError",eV=`vercel.ai.gateway.error.${z0}`,Yg=Symbol.for(eV),Qg,Xg,tV=class extends(Xg=Ct,Qg=Yg,Xg){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Qg]=!0,this.name=z0,this.type="invalid_request_error"}static isInstance(e){return Ct.hasMarker(e)&&Yg in e}},D0="GatewayRateLimitError",nV=`vercel.ai.gateway.error.${D0}`,ev=Symbol.for(nV),tv,nv,rV=class extends(nv=Ct,tv=ev,nv){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[tv]=!0,this.name=D0,this.type="rate_limit_exceeded"}static isInstance(e){return Ct.hasMarker(e)&&ev in e}},U0="GatewayModelNotFoundError",iV=`vercel.ai.gateway.error.${U0}`,rv=Symbol.for(iV),oV=gi(()=>Tr(O({modelId:k()}))),iv,ov,L0=class extends(ov=Ct,iv=rv,ov){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:i}={}){super({message:e,statusCode:t,cause:i}),this[iv]=!0,this.name=U0,this.type="model_not_found",this.modelId=n}static isInstance(e){return Ct.hasMarker(e)&&rv in e}},F0="GatewayInternalServerError",aV=`vercel.ai.gateway.error.${F0}`,av=Symbol.for(aV),sv,lv,uv=class extends(lv=Ct,sv=av,lv){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[sv]=!0,this.name=F0,this.type="internal_server_error"}static isInstance(e){return Ct.hasMarker(e)&&av in e}},B0="GatewayResponseError",sV=`vercel.ai.gateway.error.${B0}`,cv=Symbol.for(sV),dv,pv,lV=class extends(pv=Ct,dv=cv,pv){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:i,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[dv]=!0,this.name=B0,this.type="response_error",this.response=n,this.validationError=i}static isInstance(e){return Ct.hasMarker(e)&&cv in e}};async function fv({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:i,authMethod:r}){const o=await er({value:e,schema:uV});if(!o.success)return new lV({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:o.error,cause:i});const a=o.value,s=a.error.type,u=a.error.message;switch(s){case"authentication_error":return Qf.createContextualError({apiKeyProvided:r==="api-key",oidcTokenProvided:r==="oidc",statusCode:t,cause:i});case"invalid_request_error":return new tV({message:u,statusCode:t,cause:i});case"rate_limit_exceeded":return new rV({message:u,statusCode:t,cause:i});case"model_not_found":{const l=await er({value:a.error.param,schema:oV});return new L0({message:u,statusCode:t,modelId:l.success?l.value.modelId:void 0,cause:i})}case"internal_server_error":return new uv({message:u,statusCode:t,cause:i});default:return new uv({message:u,statusCode:t,cause:i})}}var uV=gi(()=>Tr(O({error:O({message:k(),type:k().nullish(),param:ze().nullish(),code:ae([k(),ee()]).nullish()})})));function wr(e,t){var n;return Ct.isInstance(e)?e:ut.isInstance(e)?fv({response:cV(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):fv({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function cV(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 Z0="ai-gateway-auth-method";async function fo(e){const t=await er({value:e[Z0],schema:dV});return t.success?t.value:void 0}var dV=gi(()=>Tr(ae([L("api-key"),L("oidc")]))),hv=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Fg({url:`${this.config.baseURL}/config`,headers:await Hn(this.config.headers()),successfulResponseHandler:As(pV),failedResponseHandler:po({errorSchema:Je(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await wr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Fg({url:`${e.origin}/v1/credits`,headers:await Hn(this.config.headers()),successfulResponseHandler:As(fV),failedResponseHandler:po({errorSchema:Je(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await wr(e)}}},pV=gi(()=>Tr(O({models:W(O({id:k(),name:k(),description:k().nullish(),pricing:O({input:k(),output:k(),input_cache_read:k().nullish(),input_cache_write:k().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:O({specificationVersion:L("v2"),provider:k(),modelId:k()}),modelType:nr(["language","embedding","image"]).nullish()}))}))),fV=gi(()=>Tr(O({balance:k(),total_used:k()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),hV=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 Hn(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:s}=await Jc({url:this.getUrl(),headers:Vc(r,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Hn(this.config.o11yHeaders)),body:t,successfulResponseHandler:As(Je()),failedResponseHandler:po({errorSchema:Je(),errorToMessage:u=>u}),...i&&{abortSignal:i},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:o,body:s},warnings:n}}catch(o){throw await wr(o,await fo(r))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:i}=e,r=await Hn(this.config.headers());try{const{value:o,responseHeaders:a}=await Jc({url:this.getUrl(),headers:Vc(r,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Hn(this.config.o11yHeaders)),body:t,successfulResponseHandler:XZ(Je()),failedResponseHandler:po({errorSchema:Je(),errorToMessage:s=>s}),...i&&{abortSignal:i},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(s){n.length>0&&s.enqueue({type:"stream-start",warnings:n})},transform(s,u){if(s.success){const l=s.value;if(l.type==="raw"&&!e.includeRawChunks)return;l.type==="response-metadata"&&l.timestamp&&typeof l.timestamp=="string"&&(l.timestamp=new Date(l.timestamp)),u.enqueue(l)}else u.error(s.error)}})),request:{body:t},response:{headers:a}}}catch(o){throw await wr(o,await fo(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)}}},mV=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 Hn(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:u}=await Jc({url:this.getUrl(),headers:Vc(o,t??{},this.getModelConfigHeaders(),await Hn(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...i?{providerOptions:i}:{}},successfulResponseHandler:As(gV),failedResponseHandler:po({errorSchema:Je(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(r=s.usage)!=null?r:void 0,providerMetadata:s.providerMetadata,response:{headers:a,body:u}}}catch(a){throw await wr(a,await fo(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},gV=gi(()=>Tr(O({embeddings:W(W(ee())),usage:O({tokens:ee()}).nullish(),providerMetadata:kt(k(),kt(k(),ze())).optional()})));async function vV(){var e;return(e=O0.getContext().headers)==null?void 0:e["x-vercel-id"]}var yV="2.0.7",bV="0.0.1";function _V(e={}){var t,n;let i=null,r=null;const o=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const s=(n=Jq(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",u=async()=>{const g=await xV(e);if(g)return Gl({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":bV,[Z0]:g.authMethod,...e.headers},`ai-sdk/gateway/${yV}`);throw Qf.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{const g=Ha({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),m=Ha({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=Ha({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await vV();return{...g&&{"ai-o11y-deployment-id":g},...m&&{"ai-o11y-environment":m},...y&&{"ai-o11y-region":y},...v&&{"ai-o11y-request-id":v}}}},c=g=>new hV(g,{provider:"gateway",baseURL:s,headers:u,fetch:e.fetch,o11yHeaders:l()}),d=async()=>{var g,m,y;const v=(y=(m=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:m.call(g).getTime())!=null?y:Date.now();return(!i||v-a>o)&&(a=v,i=new hv({baseURL:s,headers:u,fetch:e.fetch}).getAvailableModels().then(x=>(r=x,x)).catch(async x=>{throw await wr(x,await fo(await u()))})),r?Promise.resolve(r):i},f=async()=>new hv({baseURL:s,headers:u,fetch:e.fetch}).getCredits().catch(async g=>{throw await wr(g,await fo(await u()))}),p=function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(g)};return p.getAvailableModels=d,p.getCredits=f,p.imageModel=g=>{throw new OA({modelId:g,modelType:"imageModel"})},p.languageModel=c,p.textEmbeddingModel=g=>new mV(g,{provider:"gateway",baseURL:s,headers:u,fetch:e.fetch,o11yHeaders:l()}),p}var wV=_V();async function xV(e){const t=Ha({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await O0.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var SV=Object.defineProperty,IV=(e,t)=>{for(var n in t)SV(e,n,{get:t[n],enumerable:!0})},q0="AI_NoOutputSpecifiedError",V0=`vercel.ai.error.${q0}`,kV=Symbol.for(V0),H0,EV=class extends ue{constructor({message:e="No output specified."}={}){super({name:q0,message:e}),this[H0]=!0}static isInstance(e){return ue.hasMarker(e,V0)}};H0=kV;function TV(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 $V="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",mv=!1,CV=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}mv||(mv=!0,console.info($V));for(const n of e)console.warn(TV(n))}},J0="AI_InvalidArgumentError",W0=`vercel.ai.error.${J0}`,AV=Symbol.for(W0),G0,cn=class extends ue{constructor({parameter:e,value:t,message:n}){super({name:J0,message:`Invalid argument for parameter ${e}: ${n}`}),this[G0]=!0,this.parameter=e,this.value=t}static isInstance(e){return ue.hasMarker(e,W0)}};G0=AV;var K0="AI_InvalidToolInputError",Y0=`vercel.ai.error.${K0}`,PV=Symbol.for(Y0),Q0,X0=class extends ue{constructor({toolInput:e,toolName:t,cause:n,message:i=`Invalid input for tool ${t}: ${ci(n)}`}){super({name:K0,message:i,cause:n}),this[Q0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ue.hasMarker(e,Y0)}};Q0=PV;var e$="AI_NoObjectGeneratedError",t$=`vercel.ai.error.${e$}`,RV=Symbol.for(t$),n$,gv=class extends ue{constructor({message:e="No object generated.",cause:t,text:n,response:i,usage:r,finishReason:o}){super({name:e$,message:e,cause:t}),this[n$]=!0,this.text=n,this.response=i,this.usage=r,this.finishReason=o}static isInstance(e){return ue.hasMarker(e,t$)}};n$=RV;var r$="AI_NoOutputGeneratedError",i$=`vercel.ai.error.${r$}`,OV=Symbol.for(i$),o$,NV=class extends ue{constructor({message:e="No output generated.",cause:t}={}){super({name:r$,message:e,cause:t}),this[o$]=!0}static isInstance(e){return ue.hasMarker(e,i$)}};o$=OV;var a$="AI_NoSuchToolError",s$=`vercel.ai.error.${a$}`,jV=Symbol.for(s$),l$,Yc=class extends ue{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:a$,message:n}),this[l$]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ue.hasMarker(e,s$)}};l$=jV;var u$="AI_ToolCallRepairError",c$=`vercel.ai.error.${u$}`,MV=Symbol.for(c$),d$,zV=class extends ue{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${ci(e)}`}){super({name:u$,message:n,cause:e}),this[d$]=!0,this.originalError=t}static isInstance(e){return ue.hasMarker(e,c$)}};d$=MV;var DV=class extends ue{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}},p$="AI_InvalidMessageRoleError",f$=`vercel.ai.error.${p$}`,UV=Symbol.for(f$),h$,LV=class extends ue{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:p$,message:t}),this[h$]=!0,this.role=e}static isInstance(e){return ue.hasMarker(e,f$)}};h$=UV;var m$="AI_MessageConversionError",g$=`vercel.ai.error.${m$}`,FV=Symbol.for(g$),v$,BV=class extends ue{constructor({originalMessage:e,message:t}){super({name:m$,message:t}),this[v$]=!0,this.originalMessage=e}static isInstance(e){return ue.hasMarker(e,g$)}};v$=FV;var y$="AI_DownloadError",b$=`vercel.ai.error.${y$}`,ZV=Symbol.for(b$),_$,Vu=class extends ue{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:y$,message:r,cause:i}),this[_$]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ue.hasMarker(e,b$)}};_$=ZV;var w$="AI_RetryError",x$=`vercel.ai.error.${w$}`,qV=Symbol.for(x$),S$,vv=class extends ue{constructor({message:e,reason:t,errors:n}){super({name:w$,message:e}),this[S$]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ue.hasMarker(e,x$)}};S$=qV;function I$(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new DV({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return VV().languageModel(e)}function VV(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:wV}var HV=[{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]}],JV=e=>{const t=typeof e=="string"?Yf(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function WV(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?JV(e):e}function GV({data:e,signatures:t}){const n=WV(e),i=typeof n=="string"?Yf(n.substring(0,Math.min(n.length,24))):n;for(const r of t)if(i.length>=r.bytesPrefix.length&&r.bytesPrefix.every((o,a)=>o===null||i[a]===o))return r.mediaType}var KV="5.0.90",YV=async({url:e})=>{var t;const n=e.toString();try{const i=await fetch(n,{headers:Gl({},`ai-sdk/${KV}`,Gf())});if(!i.ok)throw new Vu({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 Vu.isInstance(i)?i:new Vu({url:n,cause:i})}},QV=(e=YV)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function XV(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 k$=ae([k(),vn(Uint8Array),vn(ArrayBuffer),Fo(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function E$(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}=XV(e.toString());if(t==null||n==null)throw new ue({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function e9(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Kc(new Uint8Array(e)):Kc(e)}async function t9({prompt:e,supportedUrls:t,download:n=QV()}){const i=await r9(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(r=>n9({message:r,downloadedAssets:i}))]}function n9({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=>i9(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:a}=E$(i.data);return{type:"file",data:o,filename:i.filename,mediaType:a??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 LV({role:i})}}}async function r9(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 a;const s=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let u=o.type==="image"?o.image:o.data;if(typeof u=="string")try{u=new URL(u)}catch{}return{mediaType:s,data:u}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&LZ({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:n})})),r=await t(i);return Object.fromEntries(r.map((o,a)=>o==null?null:[i[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function i9(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:a}=E$(i);let s=a??e.mediaType,u=o;if(u instanceof URL){const l=t[u.toString()];l&&(u=l.data,s??(s=l.mediaType))}switch(r){case"image":return(u instanceof Uint8Array||typeof u=="string")&&(s=(n=GV({data:u,signatures:HV}))!=null?n:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:u,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:u,providerOptions:e.providerOptions}}}}function o9({maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,seed:a,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new cn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new cn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new cn({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new cn({parameter:"topP",value:n,message:"topP must be a number"});if(i!=null&&typeof i!="number")throw new cn({parameter:"topK",value:i,message:"topK must be a number"});if(r!=null&&typeof r!="number")throw new cn({parameter:"presencePenalty",value:r,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new cn({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new cn({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,stopSequences:s,seed:a}}function a9(e){return e!=null&&Object.keys(e).length>0}function s9({tools:e,toolChoice:t,activeTools:n}){return a9(e)?{tools:(n!=null?Object.entries(e).filter(([r])=>n.includes(r)):Object.entries(e)).map(([r,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:r,description:o.description,inputSchema:Kl(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:r,id:o.id,args:o.args};default:{const s=a;throw new Error(`Unsupported tool type: ${s}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var ho=Uo(()=>ae([jo(),k(),ee(),Ee(),kt(k(),ho),W(ho)])),xn=kt(k(),kt(k(),ho)),T$=O({type:L("text"),text:k(),providerOptions:xn.optional()}),l9=O({type:L("image"),image:ae([k$,vn(URL)]),mediaType:k().optional(),providerOptions:xn.optional()}),$$=O({type:L("file"),data:ae([k$,vn(URL)]),filename:k().optional(),mediaType:k(),providerOptions:xn.optional()}),u9=O({type:L("reasoning"),text:k(),providerOptions:xn.optional()}),c9=O({type:L("tool-call"),toolCallId:k(),toolName:k(),input:ze(),providerOptions:xn.optional(),providerExecuted:Ee().optional()}),d9=kl("type",[O({type:L("text"),value:k()}),O({type:L("json"),value:ho}),O({type:L("error-text"),value:k()}),O({type:L("error-json"),value:ho}),O({type:L("content"),value:W(ae([O({type:L("text"),text:k()}),O({type:L("media"),data:k(),mediaType:k()})]))})]),C$=O({type:L("tool-result"),toolCallId:k(),toolName:k(),output:d9,providerOptions:xn.optional()}),p9=O({role:L("system"),content:k(),providerOptions:xn.optional()}),f9=O({role:L("user"),content:ae([k(),W(ae([T$,l9,$$]))]),providerOptions:xn.optional()}),h9=O({role:L("assistant"),content:ae([k(),W(ae([T$,$$,u9,c9,C$]))]),providerOptions:xn.optional()}),m9=O({role:L("tool"),content:W(C$),providerOptions:xn.optional()}),g9=ae([p9,f9,h9,m9]);async function v9(e){if(e.prompt==null&&e.messages==null)throw new Pr({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Pr({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Pr({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 Pr({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Pr({prompt:e,message:"messages must not be empty"});const n=await er({value:t,schema:W(g9)});if(!n.success)throw new Pr({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 y9(e){return Qf.isInstance(e)||L0.isInstance(e)?new ue({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 Qc({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 b9({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,[a,s])=>(o[`ai.settings.${a}`]=s,o),{}),...Object.entries((r=n?.metadata)!=null?r:{}).reduce((o,[a,s])=>(o[`ai.telemetry.metadata.${a}`]=s,o),{}),...Object.entries(i??{}).reduce((o,[a,s])=>(s!==void 0&&(o[`ai.request.headers.${a}`]=s),o),{})}}var _9={startSpan(){return $a},startActiveSpan(e,t,n,i){if(typeof t=="function")return t($a);if(typeof n=="function")return n($a);if(typeof i=="function")return i($a)}},$a={spanContext(){return w9},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}},w9={traceId:"",spanId:"",traceFlags:0};function x9({isEnabled:e=!1,tracer:t}={}){return e?t||kF.getTracer("ai"):_9}function Xc({name:e,tracer:t,attributes:n,fn:i,endWhenDone:r=!0}){return t.startActiveSpan(e,{attributes:n},async o=>{try{const a=await i(o);return r&&o.end(),a}catch(a){try{A$(o,a)}finally{o.end()}throw a}})}function A$(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ks.ERROR,message:t.message})):e.setStatus({code:ks.ERROR})}function Lr({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 S9(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?e9(n.data):n.data}:n)})))}function I9(e,t){return{inputTokens:Ii(e.inputTokens,t.inputTokens),outputTokens:Ii(e.outputTokens,t.outputTokens),totalTokens:Ii(e.totalTokens,t.totalTokens),reasoningTokens:Ii(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Ii(e.cachedInputTokens,t.cachedInputTokens)}}function Ii(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function yv(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function k9({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let i;const r=n["retry-after-ms"];if(r){const a=parseFloat(r);Number.isNaN(a)||(i=a)}const o=n["retry-after"];if(o&&i===void 0){const a=parseFloat(o);Number.isNaN(a)?i=Date.parse(o)-Date.now():i=a*1e3}return i!=null&&!Number.isNaN(i)&&0<=i&&(i<60*1e3||i<t)?i:t}var E9=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:i}={})=>async r=>P$(r,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:i});async function P$(e,{maxRetries:t,delayInMs:n,backoffFactor:i,abortSignal:r},o=[]){try{return await e()}catch(a){if(br(a)||t===0)throw a;const s=k0(a),u=[...o,a],l=u.length;if(l>t)throw new vv({message:`Failed after ${l} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:u});if(a instanceof Error&&ut.isInstance(a)&&a.isRetryable===!0&&l<=t)return await I0(k9({error:a,exponentialBackoffDelay:n}),{abortSignal:r}),P$(e,{maxRetries:t,delayInMs:i*n,backoffFactor:i,abortSignal:r},u);throw l===1?a:new vv({message:`Failed after ${l} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:u})}}function T9({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new cn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new cn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:E9({maxRetries:n,abortSignal:t})}}var $9=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=Kc(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Yf(this.base64Data)),this.uint8ArrayData}},C9=class extends $9{constructor(e){super(e),this.type="file"}};async function A9({toolCall:e,tools:t,repairToolCall:n,system:i,messages:r}){try{if(t==null)throw new Yc({toolName:e.toolName});try{return await bv({toolCall:e,tools:t})}catch(o){if(n==null||!(Yc.isInstance(o)||X0.isInstance(o)))throw o;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:s})=>{const{inputSchema:u}=t[s];return Kl(u).jsonSchema},system:i,messages:r,error:o})}catch(s){throw new zV({cause:s,originalError:o})}if(a==null)throw o;return await bv({toolCall:a,tools:t})}}catch(o){const a=await _r({text:e.input}),s=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:o}}}async function bv({toolCall:e,tools:t}){const n=e.toolName,i=t[n];if(i==null)throw new Yc({toolName:e.toolName,availableTools:Object.keys(t)});const r=Kl(i.inputSchema),o=e.input.trim()===""?await er({value:{},schema:r}):await _r({text:e.input,schema:r});if(o.success===!1)throw new X0({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 P9=class{constructor({content:e,finishReason:t,usage:n,warnings:i,request:r,response:o,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=i,this.request=r,this.response=o,this.providerMetadata=a}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 R$(e){return({steps:t})=>t.length===e}async function R9({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function Di({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:ci(e)}:n==="json"?{type:"error-json",value:_v(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:_v(e)}}function _v(e){return e===void 0?null:e}function wv({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:Di({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:Di({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:Di({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}ta({prefix:"aitxt",size:24});function Yl(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 O9({status:e,statusText:t,headers:n,textStream:i}){return new Response(i.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Yl(n,{"content-type":"text/plain; charset=utf-8"})})}function O$({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:s,value:u}=await o.read();if(s)break;e.write(u)||await new Promise(c=>{e.once("drain",c)})}}catch(s){throw s}finally{e.end()}})()}function N9({response:e,status:t,statusText:n,headers:i,textStream:r}){O$({response:e,status:t,statusText:n,headers:Object.fromEntries(Yl(i,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:r.pipeThrough(new TextEncoderStream)})}var N$=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
85
127
|
|
|
86
128
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
87
129
|
|
|
88
|
-
`)}})}},y$={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Jz({status:e,statusText:t,headers:r,stream:o,consumeSseStream:n}){let i=o.pipeThrough(new v$);if(n){const[a,s]=i.tee();i=a,n({stream:s})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Ga(r,y$)})}function Wz({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function Hz(e){return e.type.startsWith("data-")}function b$(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)){const n=t[o];if(n===void 0)continue;const i=o in e?e[o]:void 0,a=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),s=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);a&&s?r[o]=b$(i,n):r[o]=n}return r}function Gz(e){const t=["ROOT"];let r=-1,o=null;function n(l,u,c){switch(l){case'"':{r=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,o=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":{r=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{r=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{r=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":n(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=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":{n(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=l,t.pop();break}default:{r=l,n(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"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=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":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(o,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):r=l;break}}}let s=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(o,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function _$(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await xr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await xr({text:Gz(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ms(e){return e.type.startsWith("data-")}function Ds(e){return e.type==="text"}function Us(e){return e.type==="file"}function Nf(e){return e.type==="reasoning"}function Fr(e){return e.type.startsWith("tool-")}function Hc(e){return e.type==="dynamic-tool"}function Pf(e){return Fr(e)||Hc(e)}function Ui(e){return e.type.split("-").slice(1).join("-")}function Kz(e){return Hc(e)?e.toolName:Ui(e)}function Yz({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Qz({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:o,onError:n,onToolCall:i,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,l){await o(async({state:u,write:c})=>{var d,f,p,g;function h(v){const N=u.message.parts.filter(Fr).find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(v){const N=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===v);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function y(v){var k;const N=u.message.parts.find(M=>Fr(M)&&M.toolCallId===v.toolCallId),I=v,O=N;N!=null?(N.state=v.state,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=I.rawInput,O.preliminary=I.preliminary,O.providerExecuted=(k=I.providerExecuted)!=null?k:N.providerExecuted,I.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:v.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function x(v){var k,N;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===v.toolCallId),O=v,M=I;I!=null?(I.state=v.state,M.toolName=v.toolName,M.input=O.input,M.output=O.output,M.errorText=O.errorText,M.rawInput=(k=O.rawInput)!=null?k:M.rawInput,M.preliminary=O.preliminary,M.providerExecuted=(N=O.providerExecuted)!=null?N:I.providerExecuted,O.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=O.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:v.toolName,toolCallId:v.toolCallId,state:v.state,input:O.input,output:O.output,errorText:O.errorText,preliminary:O.preliminary,providerExecuted:O.providerExecuted,...O.providerMetadata!=null?{callProviderMetadata:O.providerMetadata}:{}})}async function $(v){if(v!=null){const k=u.message.metadata!=null?b$(u.message.metadata,v):v;t!=null&&await xu({value:k,schema:t}),u.message.metadata=k}}switch(s.type){case"text-start":{const v={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeTextParts[s.id]=v,u.message.parts.push(v),c();break}case"text-delta":{const v=u.activeTextParts[s.id];v.text+=s.delta,v.providerMetadata=(d=s.providerMetadata)!=null?d:v.providerMetadata,c();break}case"text-end":{const v=u.activeTextParts[s.id];v.state="done",v.providerMetadata=(f=s.providerMetadata)!=null?f:v.providerMetadata,delete u.activeTextParts[s.id],c();break}case"reasoning-start":{const v={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};u.activeReasoningParts[s.id]=v,u.message.parts.push(v),c();break}case"reasoning-delta":{const v=u.activeReasoningParts[s.id];v.text+=s.delta,v.providerMetadata=(p=s.providerMetadata)!=null?p:v.providerMetadata,c();break}case"reasoning-end":{const v=u.activeReasoningParts[s.id];v.providerMetadata=(g=s.providerMetadata)!=null?g:v.providerMetadata,v.state="done",delete u.activeReasoningParts[s.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const v=u.message.parts.filter(Fr);u.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:v.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const v=u.partialToolCalls[s.toolCallId];v.text+=s.inputTextDelta;const{value:k}=await _$(v.text);v.dynamic?x({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}):y({toolCallId:s.toolCallId,toolName:v.toolName,state:"input-streaming",input:k}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),i&&!s.providerExecuted&&await i({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):y({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-available",input:v.input,output:s.output,preliminary:s.preliminary})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ui(v),state:"output-available",input:v.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const v=b(s.toolCallId);x({toolCallId:s.toolCallId,toolName:v.toolName,state:"output-error",input:v.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const v=h(s.toolCallId);y({toolCallId:s.toolCallId,toolName:Ui(v),state:"output-error",input:v.input,rawInput:v.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{s.messageId!=null&&(u.message.id=s.messageId),await $(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await $(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{n?.(new Error(s.errorText));break}default:if(Hz(s)){r?.[s.type]!=null&&await xu({value:s.data,schema:r[s.type]});const v=s;if(v.transient){a?.(v);break}const k=v.id!=null?u.message.parts.find(N=>v.type===N.type&&v.id===N.id):void 0;k!=null?k.data=v.data:u.message.parts.push(v),a?.(v),c()}}l.enqueue(s)})}}))}function Xz({messageId:e,originalMessages:t=[],onFinish:r,onError:o,stream:n}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!1;const s=n.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const g=f;g.messageId==null&&e!=null&&(g.messageId=e)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(r==null)return s;const l=Yz({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async f=>{await f({state:l,write:()=>{}})};let c=!1;const d=async()=>{if(c||!r)return;c=!0;const f=l.message.id===i?.id;await r({isAborted:a,isContinuation:f,responseMessage:l.message,messages:[...f?t.slice(0,-1):t,l.message]})};return Qz({stream:s,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function eM({response:e,status:t,statusText:r,headers:o,stream:n,consumeSseStream:i}){let a=n.pipeThrough(new v$);if(i){const[s,l]=a.tee();a=s,i({stream:l})}g$({response:e,status:t,statusText:r,headers:Object.fromEntries(Ga(o,y$).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Wo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let o=!1;async function n(i){var a;o=!0;try{i&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(o)return{done:!0,value:void 0};const{done:i,value:a}=await r.read();return i?(await n(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(i){throw await n(!0),i}}},t}async function tM({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:o}=await r.read();if(o)break}}catch(o){t?.(o)}finally{r.releaseLock()}}function Cf(){let e,t;return{promise:new Promise((o,n)=>{e=o,t=n}),resolve:e,reject:t}}function rM(){let e=[],t=null,r=!1,o=Cf();const n=()=>{r=!0,o.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},i=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return o=Cf(),await o.promise,i();try{const{value:a,done:s}=await e[0].read();s?(e.shift(),e.length>0?await i():r&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),n()}};return{stream:new ReadableStream({start(a){t=a},pull:i,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),o.resolve()},close:()=>{r=!0,o.resolve(),e.length===0&&t?.close()},terminate:n}}var Ho=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 nM(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function oM({tools:e,generatorStream:t,tracer:r,telemetry:o,system:n,messages:i,abortSignal:a,repairToolCall:s,experimental_context:l}){let u=null;const c=new ReadableStream({start(y){u=y}}),d=new Set,f=new Map;let p=!1,g;function h(){p&&d.size===0&&(g!=null&&u.enqueue(g),u.close())}const b=new TransformStream({async transform(y,x){const $=y.type;switch($){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":{x.enqueue(y);break}case"file":{x.enqueue({type:"file",file:new Lz({data:y.data,mediaType:y.mediaType})});break}case"finish":{g={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const v=await Zz({toolCall:y,tools:e,repairToolCall:s,system:n,messages:i});if(x.enqueue(v),v.invalid){u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:v.toolName,input:v.input,error:ux(v.error),dynamic:!0});break}const k=e[v.toolName];if(f.set(v.toolCallId,v.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:v.input,toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}),k.execute!=null&&v.providerExecuted!==!0){const N=W1();d.add(N),Ou({name:"ai.toolCall",attributes:Lr({telemetry:o,attributes:{...Tu({operationId:"ai.toolCall",telemetry:o}),"ai.toolCall.name":v.toolName,"ai.toolCall.id":v.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(v.input)}}}),tracer:r,fn:async I=>{let O;try{const M=aR({execute:k.execute.bind(k),input:v.input,options:{toolCallId:v.toolCallId,messages:i,abortSignal:a,experimental_context:l}});for await(const F of M)u.enqueue({...v,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(O=F.output)}catch(M){f$(I,M),u.enqueue({...v,type:"tool-error",error:M}),d.delete(N),h();return}d.delete(N),h();try{I.setAttributes(Lr({telemetry:o,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(O)}}}))}catch{}}})}}catch(v){u.enqueue({type:"error",error:v})}break}case"tool-result":{const v=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):x.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:v,input:f.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const v=$;throw new Error(`Unhandled chunk type: ${v}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(b).pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){}})),c.pipeTo(new WritableStream({write(x){y.enqueue(x)},close(){y.close()}}))])}})}var iM=No({prefix:"aitxt",size:24});function aM({model:e,tools:t,toolChoice:r,system:o,prompt:n,messages:i,maxRetries:a,abortSignal:s,headers:l,stopWhen:u=h$(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:g,activeTools:h=g,experimental_repairToolCall:b,experimental_transform:y,experimental_download:x,includeRawChunks:$=!1,onChunk:v,onError:k=({error:V})=>{console.error(V)},onFinish:N,onAbort:I,onStepFinish:O,experimental_context:M,_internal:{now:F=nM,generateId:te=iM,currentDate:oe=()=>new Date}={},...J}){return new uM({model:s$(e),telemetry:d,headers:l,settings:J,maxRetries:a,abortSignal:s,system:o,prompt:n,messages:i,tools:t,toolChoice:r,transforms:kf(y),activeTools:h,repairToolCall:b,stopConditions:kf(u),output:c,providerOptions:p,prepareStep:f,includeRawChunks:$,onChunk:v,onError:k,onFinish:N,onAbort:I,onStepFinish:O,now:F,currentDate:oe,generateId:te,experimental_context:M,download:x})}function sM(e){if(!e)return new TransformStream({transform(a,s){s.enqueue({part:a,partialOutput:void 0})}});let t,r="",o="",n="";function i({controller:a,partialOutput:s=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:o},partialOutput:s}),o=""}return new TransformStream({async transform(a,s){if(a.type==="finish-step"&&o.length>0&&i({controller:s}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){s.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){o.length>0&&i({controller:s}),s.enqueue({part:a,partialOutput:void 0});return}r+=a.text,o+=a.text;const l=await e.parsePartial({text:r});if(l!=null){const u=JSON.stringify(l.partial);u!==n&&(i({controller:s,partialOutput:l.partial}),n=u)}}})}var uM=class{constructor({model:e,telemetry:t,headers:r,settings:o,maxRetries:n,abortSignal:i,system:a,prompt:s,messages:l,tools:u,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:g,output:h,providerOptions:b,prepareStep:y,includeRawChunks:x,now:$,currentDate:v,generateId:k,onChunk:N,onError:I,onFinish:O,onAbort:M,onStepFinish:F,experimental_context:te,download:oe}){this._totalUsage=new Ho,this._finishReason=new Ho,this._steps=new Ho,this.output=h,this.includeRawChunks=x,this.tools=u;let J,V=[];const ye=[];let ie,de,K={},fe=[];const B=[];let Ue,be={},Le={};const U=new TransformStream({async transform(Ee,Te){var Ae,ae,ft,mn;Te.enqueue(Ee);const{part:Z}=Ee;if((Z.type==="text-delta"||Z.type==="reasoning-delta"||Z.type==="source"||Z.type==="tool-call"||Z.type==="tool-result"||Z.type==="tool-input-start"||Z.type==="tool-input-delta"||Z.type==="raw")&&await N?.({chunk:Z}),Z.type==="error"&&await I({error:Oz(Z.error)}),Z.type==="text-start"&&(be[Z.id]={type:"text",text:"",providerMetadata:Z.providerMetadata},V.push(be[Z.id])),Z.type==="text-delta"){const Ie=be[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(Ae=Z.providerMetadata)!=null?Ae:Ie.providerMetadata}if(Z.type==="text-end"){const Ie=be[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(ae=Z.providerMetadata)!=null?ae:Ie.providerMetadata,delete be[Z.id]}if(Z.type==="reasoning-start"&&(Le[Z.id]={type:"reasoning",text:"",providerMetadata:Z.providerMetadata},V.push(Le[Z.id])),Z.type==="reasoning-delta"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.text+=Z.text,Ie.providerMetadata=(ft=Z.providerMetadata)!=null?ft:Ie.providerMetadata}if(Z.type==="reasoning-end"){const Ie=Le[Z.id];if(Ie==null){Te.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}Ie.providerMetadata=(mn=Z.providerMetadata)!=null?mn:Ie.providerMetadata,delete Le[Z.id]}if(Z.type==="file"&&V.push({type:"file",file:Z.file}),Z.type==="source"&&V.push(Z),Z.type==="tool-call"&&V.push(Z),Z.type==="tool-result"&&!Z.preliminary&&V.push(Z),Z.type==="tool-error"&&V.push(Z),Z.type==="start-step"&&(K=Z.request,fe=Z.warnings),Z.type==="finish-step"){const Ie=Of({content:V,tools:u}),hn=new Fz({content:V,finishReason:Z.finishReason,usage:Z.usage,warnings:fe,request:K,response:{...Z.response,messages:[...ye,...Ie]},providerMetadata:Z.providerMetadata});await F?.(hn),LR(fe),B.push(hn),V=[],Le={},be={},ye.push(...Ie),J.resolve()}Z.type==="finish"&&(de=Z.totalUsage,ie=Z.finishReason)},async flush(Ee){try{if(B.length===0){const ft=new BR({message:"No output generated. Check the stream for errors."});je._finishReason.reject(ft),je._totalUsage.reject(ft),je._steps.reject(ft);return}const Te=ie??"unknown",Ae=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};je._finishReason.resolve(Te),je._totalUsage.resolve(Ae),je._steps.resolve(B);const ae=B[B.length-1];await O?.({finishReason:Te,totalUsage:Ae,usage:ae.usage,content:ae.content,text:ae.text,reasoningText:ae.reasoningText,reasoning:ae.reasoning,files:ae.files,sources:ae.sources,toolCalls:ae.toolCalls,staticToolCalls:ae.staticToolCalls,dynamicToolCalls:ae.dynamicToolCalls,toolResults:ae.toolResults,staticToolResults:ae.staticToolResults,dynamicToolResults:ae.dynamicToolResults,request:ae.request,response:ae.response,warnings:ae.warnings,providerMetadata:ae.providerMetadata,steps:B}),Ue.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Te,"ai.response.text":{output:()=>ae.text},"ai.response.toolCalls":{output:()=>{var ft;return(ft=ae.toolCalls)!=null&&ft.length?JSON.stringify(ae.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ae.providerMetadata),"ai.usage.inputTokens":Ae.inputTokens,"ai.usage.outputTokens":Ae.outputTokens,"ai.usage.totalTokens":Ae.totalTokens,"ai.usage.reasoningTokens":Ae.reasoningTokens,"ai.usage.cachedInputTokens":Ae.cachedInputTokens}}))}catch(Te){Ee.error(Te)}finally{Ue.end()}}}),Q=rM();this.addStream=Q.addStream,this.closeStream=Q.close;const me=Q.stream.getReader();let xe=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function Te(){M?.({steps:B}),Ee.enqueue({type:"abort"}),Ee.close()}try{const{done:Ae,value:ae}=await me.read();if(Ae){Ee.close();return}if(i?.aborted){Te();return}Ee.enqueue(ae)}catch(Ae){wr(Ae)&&i?.aborted?Te():Ee.error(Ae)}},cancel(Ee){return Q.stream.cancel(Ee)}});for(const Ee of d)xe=xe.pipeThrough(Ee({tools:u,stopStream(){Q.terminate()}}));this.baseStream=xe.pipeThrough(sM(h)).pipeThrough(U);const{maxRetries:Ro,retry:ls}=Dz({maxRetries:n,abortSignal:i}),fn=jz(t),pt=gz(o),zo=Nz({model:e,telemetry:t,headers:r,settings:{...pt,maxRetries:Ro}}),je=this;Ou({name:"ai.streamText",attributes:Lr({telemetry:t,attributes:{...Tu({operationId:"ai.streamText",telemetry:t}),...zo,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:s,messages:l})}}}),tracer:fn,endWhenDone:!1,fn:async Ee=>{Ue=Ee;async function Te({currentStep:Ae,responseMessages:ae,usage:ft}){var mn,Z,Ie,hn,Id;const kd=je.includeRawChunks;J=new Ho;const Ed=await Tz({system:a,prompt:s,messages:l}),gn=[...Ed.messages,...ae],Et=await y?.({model:e,steps:B,stepNumber:B.length,messages:gn}),Nr=s$((mn=Et?.model)!=null?mn:e),Td=await pz({prompt:{system:(Z=Et?.system)!=null?Z:Ed.system,messages:(Ie=Et?.messages)!=null?Ie:gn},supportedUrls:await Nr.supportedUrls,download:oe}),{toolChoice:cs,tools:ds}=yz({tools:u,toolChoice:(hn=Et?.toolChoice)!=null?hn:c,activeTools:(Id=Et?.activeTools)!=null?Id:f}),{result:{stream:g0,response:Od,request:Nd},doStreamSpan:Pr,startTimestampMs:Pd}=await ls(()=>Ou({name:"ai.streamText.doStream",attributes:Lr({telemetry:t,attributes:{...Tu({operationId:"ai.streamText.doStream",telemetry:t}),...zo,"ai.model.provider":Nr.provider,"ai.model.id":Nr.modelId,"ai.prompt.messages":{input:()=>Az(Td)},"ai.prompt.tools":{input:()=>ds?.map(W=>JSON.stringify(W))},"ai.prompt.toolChoice":{input:()=>cs!=null?JSON.stringify(cs):void 0},"gen_ai.system":Nr.provider,"gen_ai.request.model":Nr.modelId,"gen_ai.request.frequency_penalty":pt.frequencyPenalty,"gen_ai.request.max_tokens":pt.maxOutputTokens,"gen_ai.request.presence_penalty":pt.presencePenalty,"gen_ai.request.stop_sequences":pt.stopSequences,"gen_ai.request.temperature":pt.temperature,"gen_ai.request.top_k":pt.topK,"gen_ai.request.top_p":pt.topP}}),tracer:fn,endWhenDone:!1,fn:async W=>({startTimestampMs:$(),doStreamSpan:W,result:await Nr.doStream({...pt,tools:ds,toolChoice:cs,responseFormat:h?.responseFormat,prompt:Td,providerOptions:b,abortSignal:i,headers:r,includeRawChunks:kd})})})),v0=oM({tools:u,generatorStream:g0,tracer:fn,telemetry:t,system:a,messages:gn,repairToolCall:p,abortSignal:i,experimental_context:te}),y0=Nd??{},Mo=[],ps=[];let fs;const ms={};let Cr="unknown",mt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},hs,Cd=!0,Tt={id:k(),timestamp:v(),modelId:e.modelId},jd="";je.addStream(v0.pipeThrough(new TransformStream({async transform(W,Re){var vn,yn,Do,Ut;if(W.type==="stream-start"){fs=W.warnings;return}if(Cd){const Ze=$()-Pd;Cd=!1,Pr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Ze}),Pr.setAttributes({"ai.response.msToFirstChunk":Ze}),Re.enqueue({type:"start-step",request:y0,warnings:fs??[]})}const Ad=W.type;switch(Ad){case"text-start":case"text-end":{Re.enqueue(W);break}case"text-delta":{W.delta.length>0&&(Re.enqueue({type:"text-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata}),jd+=W.delta);break}case"reasoning-start":case"reasoning-end":{Re.enqueue(W);break}case"reasoning-delta":{Re.enqueue({type:"reasoning-delta",id:W.id,text:W.delta,providerMetadata:W.providerMetadata});break}case"tool-call":{Re.enqueue(W),Mo.push(W);break}case"tool-result":{Re.enqueue(W),W.preliminary||ps.push(W);break}case"tool-error":{Re.enqueue(W),ps.push(W);break}case"response-metadata":{Tt={id:(vn=W.id)!=null?vn:Tt.id,timestamp:(yn=W.timestamp)!=null?yn:Tt.timestamp,modelId:(Do=W.modelId)!=null?Do:Tt.modelId};break}case"finish":{mt=W.usage,Cr=W.finishReason,hs=W.providerMetadata;const Ze=$()-Pd;Pr.addEvent("ai.stream.finish"),Pr.setAttributes({"ai.response.msToFinish":Ze,"ai.response.avgOutputTokensPerSecond":1e3*((Ut=mt.outputTokens)!=null?Ut:0)/Ze});break}case"file":{Re.enqueue(W);break}case"source":{Re.enqueue(W);break}case"tool-input-start":{ms[W.id]=W.toolName;const Ze=u?.[W.toolName];Ze?.onInputStart!=null&&await Ze.onInputStart({toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue({...W,dynamic:Ze?.type==="dynamic"});break}case"tool-input-end":{delete ms[W.id],Re.enqueue(W);break}case"tool-input-delta":{const Ze=ms[W.id],gs=u?.[Ze];gs?.onInputDelta!=null&&await gs.onInputDelta({inputTextDelta:W.delta,toolCallId:W.id,messages:gn,abortSignal:i,experimental_context:te}),Re.enqueue(W);break}case"error":{Re.enqueue(W),Cr="error";break}case"raw":{kd&&Re.enqueue(W);break}default:{const Ze=Ad;throw new Error(`Unknown chunk type: ${Ze}`)}}},async flush(W){const Re=Mo.length>0?JSON.stringify(Mo):void 0;try{Pr.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Cr,"ai.response.text":{output:()=>jd},"ai.response.toolCalls":{output:()=>Re},"ai.response.id":Tt.id,"ai.response.model":Tt.modelId,"ai.response.timestamp":Tt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(hs),"ai.usage.inputTokens":mt.inputTokens,"ai.usage.outputTokens":mt.outputTokens,"ai.usage.totalTokens":mt.totalTokens,"ai.usage.reasoningTokens":mt.reasoningTokens,"ai.usage.cachedInputTokens":mt.cachedInputTokens,"gen_ai.response.finish_reasons":[Cr],"gen_ai.response.id":Tt.id,"gen_ai.response.model":Tt.modelId,"gen_ai.usage.input_tokens":mt.inputTokens,"gen_ai.usage.output_tokens":mt.outputTokens}}))}catch{}finally{Pr.end()}W.enqueue({type:"finish-step",finishReason:Cr,usage:mt,providerMetadata:hs,response:{...Tt,headers:Od?.headers}});const vn=Rz(ft,mt);await J.promise;const yn=Mo.filter(Ut=>Ut.providerExecuted!==!0),Do=ps.filter(Ut=>Ut.providerExecuted!==!0);if(yn.length>0&&Do.length===yn.length&&!await qz({stopConditions:g,steps:B})){ae.push(...Of({content:B[B.length-1].content,tools:u}));try{await Te({currentStep:Ae+1,responseMessages:ae,usage:vn})}catch(Ut){W.enqueue({type:"error",error:Ut}),je.closeStream()}}else W.enqueue({type:"finish",finishReason:Cr,totalUsage:vn}),je.closeStream()}})))}await Te({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(Ee=>{je.addStream(new ReadableStream({start(Te){Te.enqueue({type:"error",error:Ee}),Te.close()}})),je.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 Wo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Wo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await tM({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new MR;return Wo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:o,sendReasoning:n=!0,sendSources:i=!1,sendStart:a=!0,sendFinish:s=!0,onError:l=sn}={}){const u=t!=null?Wz({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var g,h;const b=c[p];return((h=(g=this.tools)==null?void 0:g[b])==null?void 0:h.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,g)=>{const h=o?.({part:p}),b=p.type;switch(b){case"text-start":{g.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{n&&g.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{i&&p.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),i&&p.sourceType==="document"&&g.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);g.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":{g.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?g.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)}):g.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);g.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);g.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":{g.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...h!=null?{messageMetadata:h}:{},...u!=null?{messageId:u}:{}});break}case"finish":{s&&g.enqueue({type:"finish",...h!=null?{messageMetadata:h}:{}});break}case"abort":{g.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=b;throw new Error(`Unknown chunk type: ${y}`)}}h!=null&&b!=="start"&&b!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:h})}}));return Wo(Xz({stream:f,messageId:u??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:o,messageMetadata:n,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u,...c}={}){eM({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:o,messageMetadata:n,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){Bz({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:o,sendReasoning:n,sendSources:i,sendFinish:a,sendStart:s,onError:l,...u}={}){return Jz({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:o,sendReasoning:n,sendSources:i,sendFinish:a,sendStart:s,onError:l}),...u})}toTextStreamResponse(e){return Vz({textStream:this.textStream,...e})}};function lM(e,t){const r=[];t?.ignoreIncompleteToolCalls&&(e=e.map(o=>({...o,parts:o.parts.filter(n=>!Pf(n)||n.state!=="input-streaming"&&n.state!=="input-available")})));for(const o of e)switch(o.role){case"system":{const n=o.parts.filter(a=>a.type==="text"),i=n.reduce((a,s)=>s.providerMetadata!=null?{...a,...s.providerMetadata}:a,{});r.push({role:"system",content:n.map(a=>a.text).join(""),...Object.keys(i).length>0?{providerOptions:i}:{}});break}case"user":{r.push({role:"user",content:o.parts.map(n=>{var i;if(Ds(n))return{type:"text",text:n.text,...n.providerMetadata!=null?{providerOptions:n.providerMetadata}:{}};if(Us(n))return{type:"file",mediaType:n.mediaType,filename:n.filename,data:n.url,...n.providerMetadata!=null?{providerOptions:n.providerMetadata}:{}};if(Ms(n))return(i=t?.convertDataPart)==null?void 0:i.call(t,n)}).filter(n=>n!=null)});break}case"assistant":{if(o.parts!=null){let n=function(){var a,s,l;if(i.length===0)return;const u=[];for(const d of i)if(Ds(d))u.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(Us(d))u.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(Nf(d))u.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(Hc(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(Fr(d)){const f=Ui(d);d.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(a=d.input)!=null?a: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:Nn({output:d.state==="output-error"?d.errorText:d.output,tool:(s=t?.tools)==null?void 0:s[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(Ms(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}`)}r.push({role:"assistant",content:u});const c=i.filter(d=>Fr(d)&&d.providerExecuted!==!0||d.type==="dynamic-tool");c.length>0&&r.push({role:"tool",content:c.map(d=>{var f;switch(d.state){case"output-error":case"output-available":{const p=Kz(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:Nn({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)}),i=[]},i=[];for(const a of o.parts)Ds(a)||Nf(a)||Us(a)||Pf(a)||Ms(a)?i.push(a):a.type==="step-start"&&n();n();break}break}default:{const n=o.role;throw new XR({originalMessage:o,message:`Unsupported role: ${n}`})}}return r}No({prefix:"aiobj",size:24});No({prefix:"aiobj",size:24});var cM={};RR(cM,{object:()=>pM,text:()=>dM});var dM=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),pM=({schema:e})=>{const t=Ha(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const o=await _$(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:o.value};default:{const n=o.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},o){const n=await xr({text:r});if(!n.success)throw new Sf({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=await sr({value:n.value,schema:t});if(!i.success)throw new Sf({message:"No object generated: response did not match schema.",cause:i.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value}}},fM={word:/\S+\s+/m,line:/\n+/m};function mM({delayInMs:e=10,chunking:t="word",_internal:{delay:r=sx}={}}={}){let o;if(typeof t=="function")o=n=>{const i=t(n);if(i==null)return null;if(!i.length)throw new Error("Chunking function must return a non-empty string.");if(!n.startsWith(i))throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: "${i}" expected to start with "${n}"`);return i};else{const n=typeof t=="string"?fM[t]:t;if(n==null)throw new Ji({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});o=i=>{const a=n.exec(i);return a?i.slice(0,a.index)+a?.[0]:null}}return()=>{let n="",i="";return new TransformStream({async transform(a,s){if(a.type!=="text-delta"){n.length>0&&(s.enqueue({type:"text-delta",text:n,id:i}),n=""),s.enqueue(a);return}a.id!==i&&n.length>0&&(s.enqueue({type:"text-delta",text:n,id:i}),n=""),n+=a.text,i=a.id;let l;for(;(l=o(n))!=null;)s.enqueue({type:"text-delta",text:l,id:i}),n=n.slice(l.length),await r(e)}})}}function Go(e){return!!e&&"UNSAFE_apiKey"in e}function hM(e){return e?"sessionFn"in e:!1}const gM=({getSession:e,projectSlug:t,enabled:r})=>{const o=q_(),n=["chatSession",t],i=o.getQueryState(n),a=i?.data!==void 0,s=i?.dataUpdatedAt??0,u=a&&Date.now()-s>1/0,c=!a||u,{data:d}=B_({queryKey:n,queryFn:()=>e({projectSlug:t}),enabled:r&&c&&e!==null,staleTime:1/0,gcTime:1/0});return d??null};async function vM(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const yM=({projectSlug:e,auth:t})=>{const r=z.useMemo(()=>Go(t)?null:!Go(t)&&hM(t)?t.sessionFn:vM,[t]),o=gM({enabled:!Go(t),getSession:r,projectSlug:e});return Go(t)?{headers:{"Gram-Project":e,"Gram-Key":t.UNSAFE_apiKey},isLoading:!1}:o?{headers:{"Gram-Project":e,"Gram-Chat-Session":o},isLoading:!1}:{isLoading:!0}};function bM({children:e}){const[t,r]=z.useState(new Map),[o,n]=z.useState(new Set),i=z.useCallback((d,f,p)=>new Promise(g=>{const h={toolCallId:f,toolName:d,args:p,resolve:g};r(b=>{const y=new Map(b);return y.set(f,h),y})}),[]),a=z.useCallback(d=>{n(f=>{const p=new Set(f);return p.add(d),p})},[]),s=z.useCallback(d=>{r(f=>{const p=f.get(d);if(p){p.resolve(!0);const g=new Map(f);return g.delete(d),g}return f})},[]),l=z.useCallback(d=>{r(f=>{const p=f.get(d);if(p){p.resolve(!1);const g=new Map(f);return g.delete(d),g}return f})},[]),u=z.useCallback(d=>o.has(d),[o]),c=z.useCallback(d=>t.get(d),[t]);return m.jsx(T.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:o,requestApproval:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l,isToolApproved:u,getPendingApproval:c},children:e})}const _M="You are a helpful assistant that can answer questions and help with tasks.";function wM(e,t){return`
|
|
89
|
-
${
|
|
130
|
+
`)}})}},j$={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function j9({status:e,statusText:t,headers:n,stream:i,consumeSseStream:r}){let o=i.pipeThrough(new N$);if(r){const[a,s]=o.tee();o=a,r({stream:s})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Yl(n,j$)})}function M9({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 z9(e){return e.type.startsWith("data-")}function M$(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,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&s?n[i]=M$(o,r):n[i]=r}return n}function D9(e){const t=["ROOT"];let n=-1,i=null;function r(u,l,c){switch(u){case'"':{n=l,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=l,i=l,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=l,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=l,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=l,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=l,t.pop();break}}}function a(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}}}for(let u=0;u<e.length;u++){const l=e[u];switch(t[t.length-1]){case"ROOT":r(l,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(l,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,u);break}case"INSIDE_STRING":{switch(l){case'"':{t.pop(),n=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=u}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{n=u,t.pop();break}default:{n=u,r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}default:{n=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=u;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,u+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u)):n=u;break}}}let s=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function z$(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _r({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _r({text:D9(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Hu(e){return e.type.startsWith("data-")}function Ju(e){return e.type==="text"}function Wu(e){return e.type==="file"}function xv(e){return e.type==="reasoning"}function Vr(e){return e.type.startsWith("tool-")}function Xf(e){return e.type==="dynamic-tool"}function Sv(e){return Vr(e)||Xf(e)}function Ps(e){return e.type.split("-").slice(1).join("-")}function U9(e){return Xf(e)?e.toolName:Ps(e)}function L9({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function F9({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,u){await i(async({state:l,write:c})=>{var d,f,p,g;function m(b){const E=l.message.parts.filter(Vr).find(C=>C.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(b){const E=l.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function v(b){var A;const E=l.message.parts.find(j=>Vr(j)&&j.toolCallId===b.toolCallId),C=b,P=E;E!=null?(E.state=b.state,P.input=C.input,P.output=C.output,P.errorText=C.errorText,P.rawInput=C.rawInput,P.preliminary=C.preliminary,P.providerExecuted=(A=C.providerExecuted)!=null?A:E.providerExecuted,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function x(b){var A,E;const C=l.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===b.toolCallId),P=b,j=C;C!=null?(C.state=b.state,j.toolName=b.toolName,j.input=P.input,j.output=P.output,j.errorText=P.errorText,j.rawInput=(A=P.rawInput)!=null?A:j.rawInput,j.preliminary=P.preliminary,j.providerExecuted=(E=P.providerExecuted)!=null?E:C.providerExecuted,P.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=P.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:P.input,output:P.output,errorText:P.errorText,preliminary:P.preliminary,providerExecuted:P.providerExecuted,...P.providerMetadata!=null?{callProviderMetadata:P.providerMetadata}:{}})}async function S(b){if(b!=null){const A=l.message.metadata!=null?M$(l.message.metadata,b):b;t!=null&&await Hc({value:A,schema:t}),l.message.metadata=A}}switch(s.type){case"text-start":{const b={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeTextParts[s.id]=b,l.message.parts.push(b),c();break}case"text-delta":{const b=l.activeTextParts[s.id];b.text+=s.delta,b.providerMetadata=(d=s.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=l.activeTextParts[s.id];b.state="done",b.providerMetadata=(f=s.providerMetadata)!=null?f:b.providerMetadata,delete l.activeTextParts[s.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeReasoningParts[s.id]=b,l.message.parts.push(b),c();break}case"reasoning-delta":{const b=l.activeReasoningParts[s.id];b.text+=s.delta,b.providerMetadata=(p=s.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=l.activeReasoningParts[s.id];b.providerMetadata=(g=s.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete l.activeReasoningParts[s.id],c();break}case"file":{l.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const b=l.message.parts.filter(Vr);l.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:b.length,dynamic:s.dynamic},s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const b=l.partialToolCalls[s.toolCallId];b.text+=s.inputTextDelta;const{value:A}=await z$(b.text);b.dynamic?x({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:A}):v({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:A}),c();break}case"tool-input-available":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),o&&!s.providerExecuted&&await o({toolCall:s});break}case"tool-input-error":{s.dynamic?x({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const b=y(s.toolCallId);x({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:s.output,preliminary:s.preliminary})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:Ps(b),state:"output-available",input:b.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const b=y(s.toolCallId);x({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:Ps(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{s.messageId!=null&&(l.message.id=s.messageId),await S(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{await S(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await S(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(z9(s)){n?.[s.type]!=null&&await Hc({value:s.data,schema:n[s.type]});const b=s;if(b.transient){a?.(b);break}const A=b.id!=null?l.message.parts.find(E=>b.type===E.type&&b.id===E.id):void 0;A!=null?A.data=b.data:l.message.parts.push(b),a?.(b),c()}}u.enqueue(s)})}}))}function B9({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 a=!1;const s=r.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const g=f;g.messageId==null&&e!=null&&(g.messageId=e)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(n==null)return s;const u=L9({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),l=async f=>{await f({state:u,write:()=>{}})};let c=!1;const d=async()=>{if(c||!n)return;c=!0;const f=u.message.id===o?.id;await n({isAborted:a,isContinuation:f,responseMessage:u.message,messages:[...f?t.slice(0,-1):t,u.message]})};return F9({stream:s,runUpdateMessageJob:l,onError:i}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function Z9({response:e,status:t,statusText:n,headers:i,stream:r,consumeSseStream:o}){let a=r.pipeThrough(new N$);if(o){const[s,u]=a.tee();a=s,o({stream:u})}O$({response:e,status:t,statusText:n,headers:Object.fromEntries(Yl(i,j$).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ca(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let i=!1;async function r(o){var a;i=!0;try{o&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(i)return{done:!0,value:void 0};const{done:o,value:a}=await n.read();return o?(await r(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await r(!0),{done:!0,value:void 0}},async throw(o){throw await r(!0),o}}},t}async function q9({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 Iv(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}function V9(){let e=[],t=null,n=!1,i=Iv();const r=()=>{n=!0,i.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},o=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return i=Iv(),await i.promise,o();try{const{value:a,done:s}=await e[0].read();s?(e.shift(),e.length>0?await o():n&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),r()}};return{stream:new ReadableStream({start(a){t=a},pull:o,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),i.resolve()},close:()=>{n=!0,i.resolve(),e.length===0&&t?.close()},terminate:r}}var Aa=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 H9(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function J9({tools:e,generatorStream:t,tracer:n,telemetry:i,system:r,messages:o,abortSignal:a,repairToolCall:s,experimental_context:u}){let l=null;const c=new ReadableStream({start(v){l=v}}),d=new Set,f=new Map;let p=!1,g;function m(){p&&d.size===0&&(g!=null&&l.enqueue(g),l.close())}const y=new TransformStream({async transform(v,x){const S=v.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":{x.enqueue(v);break}case"file":{x.enqueue({type:"file",file:new C9({data:v.data,mediaType:v.mediaType})});break}case"finish":{g={type:"finish",finishReason:v.finishReason,usage:v.usage,providerMetadata:v.providerMetadata};break}case"tool-call":{try{const b=await A9({toolCall:v,tools:e,repairToolCall:s,system:r,messages:o});if(x.enqueue(b),b.invalid){l.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:k0(b.error),dynamic:!0});break}const A=e[b.toolName];if(f.set(b.toolCallId,b.input),A.onInputAvailable!=null&&await A.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:u}),A.execute!=null&&b.providerExecuted!==!0){const E=MZ();d.add(E),Xc({name:"ai.toolCall",attributes:Lr({telemetry:i,attributes:{...Qc({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 C=>{let P;try{const j=Gq({execute:A.execute.bind(A),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:u}});for await(const F of j)l.enqueue({...b,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(P=F.output)}catch(j){A$(C,j),l.enqueue({...b,type:"tool-error",error:j}),d.delete(E),m();return}d.delete(E),m();try{C.setAttributes(Lr({telemetry:i,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(P)}}}))}catch{}}})}}catch(b){l.enqueue({type:"error",error:b})}break}case"tool-result":{const b=v.toolName;v.isError?l.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:b,input:f.get(v.toolCallId),providerExecuted:v.providerExecuted,error:v.result}):x.enqueue({type:"tool-result",toolCallId:v.toolCallId,toolName:b,input:f.get(v.toolCallId),output:v.result,providerExecuted:v.providerExecuted});break}default:{const b=S;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){p=!0,m()}});return new ReadableStream({async start(v){return Promise.all([t.pipeThrough(y).pipeTo(new WritableStream({write(x){v.enqueue(x)},close(){}})),c.pipeTo(new WritableStream({write(x){v.enqueue(x)},close(){v.close()}}))])}})}var W9=ta({prefix:"aitxt",size:24});function G9({model:e,tools:t,toolChoice:n,system:i,prompt:r,messages:o,maxRetries:a,abortSignal:s,headers:u,stopWhen:l=R$(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:g,activeTools:m=g,experimental_repairToolCall:y,experimental_transform:v,experimental_download:x,includeRawChunks:S=!1,onChunk:b,onError:A=({error:z})=>{console.error(z)},onFinish:E,onAbort:C,onStepFinish:P,experimental_context:j,_internal:{now:F=H9,generateId:D=W9,currentDate:V=()=>new Date}={},...G}){return new Y9({model:I$(e),telemetry:d,headers:u,settings:G,maxRetries:a,abortSignal:s,system:i,prompt:r,messages:o,tools:t,toolChoice:n,transforms:yv(v),activeTools:m,repairToolCall:y,stopConditions:yv(l),output:c,providerOptions:p,prepareStep:f,includeRawChunks:S,onChunk:b,onError:A,onFinish:E,onAbort:C,onStepFinish:P,now:F,currentDate:V,generateId:D,experimental_context:j,download:x})}function K9(e){if(!e)return new TransformStream({transform(a,s){s.enqueue({part:a,partialOutput:void 0})}});let t,n="",i="",r="";function o({controller:a,partialOutput:s=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:i},partialOutput:s}),i=""}return new TransformStream({async transform(a,s){if(a.type==="finish-step"&&i.length>0&&o({controller:s}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){s.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){i.length>0&&o({controller:s}),s.enqueue({part:a,partialOutput:void 0});return}n+=a.text,i+=a.text;const u=await e.parsePartial({text:n});if(u!=null){const l=JSON.stringify(u.partial);l!==r&&(o({controller:s,partialOutput:u.partial}),r=l)}}})}var Y9=class{constructor({model:e,telemetry:t,headers:n,settings:i,maxRetries:r,abortSignal:o,system:a,prompt:s,messages:u,tools:l,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:g,output:m,providerOptions:y,prepareStep:v,includeRawChunks:x,now:S,currentDate:b,generateId:A,onChunk:E,onError:C,onFinish:P,onAbort:j,onStepFinish:F,experimental_context:D,download:V}){this._totalUsage=new Aa,this._finishReason=new Aa,this._steps=new Aa,this.output=m,this.includeRawChunks=x,this.tools=l;let G,z=[];const U=[];let Q,ie,X={},me=[];const I=[];let Te,ve={},T={};const H=new TransformStream({async transform(Le,Ue){var Be,ye,yt,zn;Ue.enqueue(Le);const{part:Y}=Le;if((Y.type==="text-delta"||Y.type==="reasoning-delta"||Y.type==="source"||Y.type==="tool-call"||Y.type==="tool-result"||Y.type==="tool-input-start"||Y.type==="tool-input-delta"||Y.type==="raw")&&await E?.({chunk:Y}),Y.type==="error"&&await C({error:y9(Y.error)}),Y.type==="text-start"&&(ve[Y.id]={type:"text",text:"",providerMetadata:Y.providerMetadata},z.push(ve[Y.id])),Y.type==="text-delta"){const Ne=ve[Y.id];if(Ne==null){Ue.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Ne.text+=Y.text,Ne.providerMetadata=(Be=Y.providerMetadata)!=null?Be:Ne.providerMetadata}if(Y.type==="text-end"){const Ne=ve[Y.id];if(Ne==null){Ue.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Ne.providerMetadata=(ye=Y.providerMetadata)!=null?ye:Ne.providerMetadata,delete ve[Y.id]}if(Y.type==="reasoning-start"&&(T[Y.id]={type:"reasoning",text:"",providerMetadata:Y.providerMetadata},z.push(T[Y.id])),Y.type==="reasoning-delta"){const Ne=T[Y.id];if(Ne==null){Ue.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Ne.text+=Y.text,Ne.providerMetadata=(yt=Y.providerMetadata)!=null?yt:Ne.providerMetadata}if(Y.type==="reasoning-end"){const Ne=T[Y.id];if(Ne==null){Ue.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Ne.providerMetadata=(zn=Y.providerMetadata)!=null?zn:Ne.providerMetadata,delete T[Y.id]}if(Y.type==="file"&&z.push({type:"file",file:Y.file}),Y.type==="source"&&z.push(Y),Y.type==="tool-call"&&z.push(Y),Y.type==="tool-result"&&!Y.preliminary&&z.push(Y),Y.type==="tool-error"&&z.push(Y),Y.type==="start-step"&&(X=Y.request,me=Y.warnings),Y.type==="finish-step"){const Ne=wv({content:z,tools:l}),or=new P9({content:z,finishReason:Y.finishReason,usage:Y.usage,warnings:me,request:X,response:{...Y.response,messages:[...U,...Ne]},providerMetadata:Y.providerMetadata});await F?.(or),CV(me),I.push(or),z=[],T={},ve={},U.push(...Ne),G.resolve()}Y.type==="finish"&&(ie=Y.totalUsage,Q=Y.finishReason)},async flush(Le){try{if(I.length===0){const yt=new NV({message:"No output generated. Check the stream for errors."});He._finishReason.reject(yt),He._totalUsage.reject(yt),He._steps.reject(yt);return}const Ue=Q??"unknown",Be=ie??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};He._finishReason.resolve(Ue),He._totalUsage.resolve(Be),He._steps.resolve(I);const ye=I[I.length-1];await P?.({finishReason:Ue,totalUsage:Be,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:I}),Te.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Ue,"ai.response.text":{output:()=>ye.text},"ai.response.toolCalls":{output:()=>{var yt;return(yt=ye.toolCalls)!=null&&yt.length?JSON.stringify(ye.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ye.providerMetadata),"ai.usage.inputTokens":Be.inputTokens,"ai.usage.outputTokens":Be.outputTokens,"ai.usage.totalTokens":Be.totalTokens,"ai.usage.reasoningTokens":Be.reasoningTokens,"ai.usage.cachedInputTokens":Be.cachedInputTokens}}))}catch(Ue){Le.error(Ue)}finally{Te.end()}}}),te=V9();this.addStream=te.addStream,this.closeStream=te.close;const le=te.stream.getReader();let we=new ReadableStream({async start(Le){Le.enqueue({type:"start"})},async pull(Le){function Ue(){j?.({steps:I}),Le.enqueue({type:"abort"}),Le.close()}try{const{done:Be,value:ye}=await le.read();if(Be){Le.close();return}if(o?.aborted){Ue();return}Le.enqueue(ye)}catch(Be){br(Be)&&o?.aborted?Ue():Le.error(Be)}},cancel(Le){return te.stream.cancel(Le)}});for(const Le of d)we=we.pipeThrough(Le({tools:l,stopStream(){te.terminate()}}));this.baseStream=we.pipeThrough(K9(m)).pipeThrough(H);const{maxRetries:vt,retry:sn}=T9({maxRetries:r,abortSignal:o}),Rt=x9(t),Qe=o9(i),Cr=b9({model:e,telemetry:t,headers:n,settings:{...Qe,maxRetries:vt}}),He=this;Xc({name:"ai.streamText",attributes:Lr({telemetry:t,attributes:{...Qc({operationId:"ai.streamText",telemetry:t}),...Cr,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:s,messages:u})}}}),tracer:Rt,endWhenDone:!1,fn:async Le=>{Te=Le;async function Ue({currentStep:Be,responseMessages:ye,usage:yt}){var zn,Y,Ne,or,oa;const aa=He.includeRawChunks;G=new Aa;const sa=await v9({system:a,prompt:s,messages:u}),N=[...sa.messages,...ye],Z=await v?.({model:e,steps:I,stepNumber:I.length,messages:N}),ne=I$((zn=Z?.model)!=null?zn:e),he=await t9({prompt:{system:(Y=Z?.system)!=null?Y:sa.system,messages:(Ne=Z?.messages)!=null?Ne:N},supportedUrls:await ne.supportedUrls,download:V}),{toolChoice:be,tools:rt}=s9({tools:l,toolChoice:(or=Z?.toolChoice)!=null?or:c,activeTools:(oa=Z?.activeTools)!=null?oa:f}),{result:{stream:Sn,response:Ot,request:Dn},doStreamSpan:Nt,startTimestampMs:Xe}=await sn(()=>Xc({name:"ai.streamText.doStream",attributes:Lr({telemetry:t,attributes:{...Qc({operationId:"ai.streamText.doStream",telemetry:t}),...Cr,"ai.model.provider":ne.provider,"ai.model.id":ne.modelId,"ai.prompt.messages":{input:()=>S9(he)},"ai.prompt.tools":{input:()=>rt?.map(re=>JSON.stringify(re))},"ai.prompt.toolChoice":{input:()=>be!=null?JSON.stringify(be):void 0},"gen_ai.system":ne.provider,"gen_ai.request.model":ne.modelId,"gen_ai.request.frequency_penalty":Qe.frequencyPenalty,"gen_ai.request.max_tokens":Qe.maxOutputTokens,"gen_ai.request.presence_penalty":Qe.presencePenalty,"gen_ai.request.stop_sequences":Qe.stopSequences,"gen_ai.request.temperature":Qe.temperature,"gen_ai.request.top_k":Qe.topK,"gen_ai.request.top_p":Qe.topP}}),tracer:Rt,endWhenDone:!1,fn:async re=>({startTimestampMs:S(),doStreamSpan:re,result:await ne.doStream({...Qe,tools:rt,toolChoice:be,responseFormat:m?.responseFormat,prompt:he,providerOptions:y,abortSignal:o,headers:n,includeRawChunks:aa})})})),Un=J9({tools:l,generatorStream:Sn,tracer:Rt,telemetry:t,system:a,messages:N,repairToolCall:p,abortSignal:o,experimental_context:D}),Zt=Dn??{},la=[],ou=[];let au;const su={};let Ar="unknown",qt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},lu,Ph=!0,ln={id:A(),timestamp:b(),modelId:e.modelId},Rh="";He.addStream(Un.pipeThrough(new TransformStream({async transform(re,Ke){var bi,_i,ua,In;if(re.type==="stream-start"){au=re.warnings;return}if(Ph){const it=S()-Xe;Ph=!1,Nt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":it}),Nt.setAttributes({"ai.response.msToFirstChunk":it}),Ke.enqueue({type:"start-step",request:Zt,warnings:au??[]})}const Oh=re.type;switch(Oh){case"text-start":case"text-end":{Ke.enqueue(re);break}case"text-delta":{re.delta.length>0&&(Ke.enqueue({type:"text-delta",id:re.id,text:re.delta,providerMetadata:re.providerMetadata}),Rh+=re.delta);break}case"reasoning-start":case"reasoning-end":{Ke.enqueue(re);break}case"reasoning-delta":{Ke.enqueue({type:"reasoning-delta",id:re.id,text:re.delta,providerMetadata:re.providerMetadata});break}case"tool-call":{Ke.enqueue(re),la.push(re);break}case"tool-result":{Ke.enqueue(re),re.preliminary||ou.push(re);break}case"tool-error":{Ke.enqueue(re),ou.push(re);break}case"response-metadata":{ln={id:(bi=re.id)!=null?bi:ln.id,timestamp:(_i=re.timestamp)!=null?_i:ln.timestamp,modelId:(ua=re.modelId)!=null?ua:ln.modelId};break}case"finish":{qt=re.usage,Ar=re.finishReason,lu=re.providerMetadata;const it=S()-Xe;Nt.addEvent("ai.stream.finish"),Nt.setAttributes({"ai.response.msToFinish":it,"ai.response.avgOutputTokensPerSecond":1e3*((In=qt.outputTokens)!=null?In:0)/it});break}case"file":{Ke.enqueue(re);break}case"source":{Ke.enqueue(re);break}case"tool-input-start":{su[re.id]=re.toolName;const it=l?.[re.toolName];it?.onInputStart!=null&&await it.onInputStart({toolCallId:re.id,messages:N,abortSignal:o,experimental_context:D}),Ke.enqueue({...re,dynamic:it?.type==="dynamic"});break}case"tool-input-end":{delete su[re.id],Ke.enqueue(re);break}case"tool-input-delta":{const it=su[re.id],uu=l?.[it];uu?.onInputDelta!=null&&await uu.onInputDelta({inputTextDelta:re.delta,toolCallId:re.id,messages:N,abortSignal:o,experimental_context:D}),Ke.enqueue(re);break}case"error":{Ke.enqueue(re),Ar="error";break}case"raw":{aa&&Ke.enqueue(re);break}default:{const it=Oh;throw new Error(`Unknown chunk type: ${it}`)}}},async flush(re){const Ke=la.length>0?JSON.stringify(la):void 0;try{Nt.setAttributes(Lr({telemetry:t,attributes:{"ai.response.finishReason":Ar,"ai.response.text":{output:()=>Rh},"ai.response.toolCalls":{output:()=>Ke},"ai.response.id":ln.id,"ai.response.model":ln.modelId,"ai.response.timestamp":ln.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(lu),"ai.usage.inputTokens":qt.inputTokens,"ai.usage.outputTokens":qt.outputTokens,"ai.usage.totalTokens":qt.totalTokens,"ai.usage.reasoningTokens":qt.reasoningTokens,"ai.usage.cachedInputTokens":qt.cachedInputTokens,"gen_ai.response.finish_reasons":[Ar],"gen_ai.response.id":ln.id,"gen_ai.response.model":ln.modelId,"gen_ai.usage.input_tokens":qt.inputTokens,"gen_ai.usage.output_tokens":qt.outputTokens}}))}catch{}finally{Nt.end()}re.enqueue({type:"finish-step",finishReason:Ar,usage:qt,providerMetadata:lu,response:{...ln,headers:Ot?.headers}});const bi=I9(yt,qt);await G.promise;const _i=la.filter(In=>In.providerExecuted!==!0),ua=ou.filter(In=>In.providerExecuted!==!0);if(_i.length>0&&ua.length===_i.length&&!await R9({stopConditions:g,steps:I})){ye.push(...wv({content:I[I.length-1].content,tools:l}));try{await Ue({currentStep:Be+1,responseMessages:ye,usage:bi})}catch(In){re.enqueue({type:"error",error:In}),He.closeStream()}}else re.enqueue({type:"finish",finishReason:Ar,totalUsage:bi}),He.closeStream()}})))}await Ue({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(Le=>{He.addStream(new ReadableStream({start(Ue){Ue.enqueue({type:"error",error:Le}),Ue.close()}})),He.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 Ca(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ca(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await q9({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 EV;return Ca(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:a=!0,sendFinish:s=!0,onError:u=ci}={}){const l=t!=null?M9({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var g,m;const y=c[p];return((m=(g=this.tools)==null?void 0:g[y])==null?void 0:m.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,g)=>{const m=i?.({part:p}),y=p.type;switch(y){case"text-start":{g.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{r&&g.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{o&&p.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),o&&p.sourceType==="document"&&g.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 v=d(p.id);g.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{c[p.toolCallId]=p.toolName;const v=d(p.toolCallId);p.invalid?g.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}:{},...v!=null?{dynamic:v}:{},errorText:u(p.error)}):g.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}:{},...v!=null?{dynamic:v}:{}});break}case"tool-result":{const v=d(p.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=d(p.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:u(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"error":{g.enqueue({type:"error",errorText:u(p.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...m!=null?{messageMetadata:m}:{},...l!=null?{messageId:l}:{}});break}case"finish":{s&&g.enqueue({type:"finish",...m!=null?{messageMetadata:m}:{}});break}case"abort":{g.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const v=y;throw new Error(`Unknown chunk type: ${v}`)}}m!=null&&y!=="start"&&y!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:m})}}));return Ca(B9({stream:f,messageId:l??t?.(),originalMessages:e,onFinish:n,onError:u}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:u,onError:l,...c}={}){Z9({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:u,onError:l}),...c})}pipeTextStreamToResponse(e,t){N9({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:a,sendStart:s,onError:u,...l}={}){return j9({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:a,sendStart:s,onError:u}),...l})}toTextStreamResponse(e){return O9({textStream:this.textStream,...e})}};function Q9(e,t){const n=[];t?.ignoreIncompleteToolCalls&&(e=e.map(i=>({...i,parts:i.parts.filter(r=>!Sv(r)||r.state!=="input-streaming"&&r.state!=="input-available")})));for(const i of e)switch(i.role){case"system":{const r=i.parts.filter(a=>a.type==="text"),o=r.reduce((a,s)=>s.providerMetadata!=null?{...a,...s.providerMetadata}:a,{});n.push({role:"system",content:r.map(a=>a.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{n.push({role:"user",content:i.parts.map(r=>{var o;if(Ju(r))return{type:"text",text:r.text,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(Wu(r))return{type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(Hu(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 a,s,u;if(o.length===0)return;const l=[];for(const d of o)if(Ju(d))l.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(Wu(d))l.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(xv(d))l.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(Xf(d)){const f=d.toolName;d.state!=="input-streaming"&&l.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.input,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}})}else if(Vr(d)){const f=Ps(d);d.state!=="input-streaming"&&(l.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(a=d.input)!=null?a:d.rawInput:d.input,providerExecuted:d.providerExecuted,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}}),d.providerExecuted===!0&&(d.state==="output-available"||d.state==="output-error")&&l.push({type:"tool-result",toolCallId:d.toolCallId,toolName:f,output:Di({output:d.state==="output-error"?d.errorText:d.output,tool:(s=t?.tools)==null?void 0:s[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(Hu(d)){const f=(u=t?.convertDataPart)==null?void 0:u.call(t,d);f!=null&&l.push(f)}else{const f=d;throw new Error(`Unsupported part: ${f}`)}n.push({role:"assistant",content:l});const c=o.filter(d=>Vr(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=U9(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:Di({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 a of i.parts)Ju(a)||xv(a)||Wu(a)||Sv(a)||Hu(a)?o.push(a):a.type==="step-start"&&r();r();break}break}default:{const r=i.role;throw new BV({originalMessage:i,message:`Unsupported role: ${r}`})}}return n}ta({prefix:"aiobj",size:24});ta({prefix:"aiobj",size:24});var X9={};IV(X9,{object:()=>t3,text:()=>e3});var e3=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),t3=({schema:e})=>{const t=Kl(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await z$(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 _r({text:n});if(!r.success)throw new gv({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 er({value:r.value,schema:t});if(!o.success)throw new gv({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}}},n3={word:/\S+\s+/m,line:/\n+/m};function r3({delayInMs:e=10,chunking:t="word",_internal:{delay:n=I0}={}}={}){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"?n3[t]:t;if(r==null)throw new js({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});i=o=>{const a=r.exec(o);return a?o.slice(0,a.index)+a?.[0]:null}}return()=>{let r="",o="";return new TransformStream({async transform(a,s){if(a.type!=="text-delta"){r.length>0&&(s.enqueue({type:"text-delta",text:r,id:o}),r=""),s.enqueue(a);return}a.id!==o&&r.length>0&&(s.enqueue({type:"text-delta",text:r,id:o}),r=""),r+=a.text,o=a.id;let u;for(;(u=i(r))!=null;)s.enqueue({type:"text-delta",text:u,id:o}),r=r.slice(u.length),await n(e)}})}}function Pa(e){return!!e&&"UNSAFE_apiKey"in e}function i3(e){return e?"sessionFn"in e:!1}const o3=({getSession:e,projectSlug:t,enabled:n})=>{const i=XI(),r=["chatSession",t],o=i.getQueryState(r),a=o?.data!==void 0,s=o?.dataUpdatedAt??0,l=a&&Date.now()-s>1/0,c=!a||l,{data:d}=tk({queryKey:r,queryFn:()=>e({projectSlug:t}),enabled:n&&c&&e!==null,staleTime:1/0,gcTime:1/0});return d??null};async function a3(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const s3=({projectSlug:e,auth:t})=>{const n=$.useMemo(()=>Pa(t)?null:!Pa(t)&&i3(t)?t.sessionFn:a3,[t]),i=o3({enabled:!Pa(t),getSession:n,projectSlug:e});return Pa(t)?{headers:{"Gram-Project":e,"Gram-Key":t.UNSAFE_apiKey},isLoading:!1}:i?{headers:{"Gram-Project":e,"Gram-Chat-Session":i},isLoading:!1}:{isLoading:!0}};function l3({children:e}){const[t,n]=$.useState(new Map),[i,r]=$.useState(new Set),o=$.useCallback((d,f,p)=>new Promise(g=>{const m={toolCallId:f,toolName:d,args:p,resolve:g};n(y=>{const v=new Map(y);return v.set(f,m),v})}),[]),a=$.useCallback(d=>{r(f=>{const p=new Set(f);return p.add(d),p})},[]),s=$.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!0);const g=new Map(f);return g.delete(d),g}return f})},[]),u=$.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!1);const g=new Map(f);return g.delete(d),g}return f})},[]),l=$.useCallback(d=>i.has(d),[i]),c=$.useCallback(d=>t.get(d),[t]);return h.jsx(_.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:i,requestApproval:o,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:u,isToolApproved:l,getPendingApproval:c},children:e})}const u3="You are a helpful assistant that can answer questions and help with tasks.";function c3(e,t){return`
|
|
131
|
+
${u3}
|
|
90
132
|
|
|
91
133
|
User-provided System Prompt:
|
|
92
134
|
${e??"None provided"}
|
|
93
135
|
|
|
94
136
|
Utilities:
|
|
95
|
-
${t.map(
|
|
96
|
-
`)}`}function xM(e){return e.map(t=>{const r=t.parts;if(!Array.isArray(r))return t;const o=r.map(n=>{const{callProviderMetadata:i,...a}=n;return a});return{...t,parts:o}})}const $M=({children:e,config:t})=>{const r=lN(t),o=yM({auth:t.api,projectSlug:t.projectSlug}),n=J_(),[i,a]=z.useState(t.model?.defaultModel??Nc[0]),[s,l]=z.useState(t.modal?.defaultExpanded??!1),[u,c]=z.useState(t.modal?.defaultOpen),d=t.plugins??T.recommended,f=wM(t.systemPrompt,d),{data:p,isLoading:g}=sN({auth:o,mcp:t.mcp,environment:t.environment??{}}),h=z.useRef({requestApproval:n.requestApproval,isToolApproved:n.isToolApproved,whitelistTool:n.whitelistTool});h.current={requestApproval:n.requestApproval,isToolApproved:n.isToolApproved,whitelistTool:n.whitelistTool};const b=z.useCallback(()=>({requestApproval:(...$)=>h.current.requestApproval(...$),isToolApproved:(...$)=>h.current.isToolApproved(...$),whitelistTool:(...$)=>h.current.whitelistTool(...$)}),[]);z.useEffect(()=>(t.tools?.toolsRequiringApproval?.length&&pN(b(),t.tools.toolsRequiringApproval),()=>{fN()}),[t.tools?.toolsRequiringApproval,b]);const y=z.useMemo(()=>({sendMessages:async({messages:$,abortSignal:v})=>{const k=!!t.languageModel;if(o.isLoading)throw new Error("Session is loading");const N=x.thread.getModelContext(),I=cN(dN(N?.tools??{})),O=k?null:ax({baseURL:r,apiKey:"unused, but must be set",headers:o.headers});t.languageModel&&console.log("Using custom language model",t.languageModel);const M={...p,...Pj(I)},F=hN(M,t.tools?.toolsRequiringApproval,b()),te=t.languageModel?t.languageModel:O.chat(i);try{const oe=xM($),J=lM(oe);return aM({system:f,model:te,messages:J,tools:F,stopWhen:h$(10),experimental_transform:mM({delayInMs:15}),abortSignal:v,onError:({error:ye})=>{console.error("Stream error in onError callback:",ye)}}).toUIMessageStream()}catch(oe){throw console.error("Error creating stream:",oe),oe}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t,t.languageModel,i,f,p,g,b,r,o.headers]),x=Nj({transport:y});return m.jsx(L.AssistantRuntimeProvider,{runtime:x,children:m.jsxs(T.ElementsContext.Provider,{value:{config:t,setModel:a,model:i,isExpanded:s,setIsExpanded:l,isOpen:u??!1,setIsOpen:c,plugins:d},children:[e,m.jsx($0,{tools:t.tools?.frontendTools??{}})]})})},SM=e=>{const t=new HO;return m.jsx(GO,{client:t,children:m.jsx(bM,{children:m.jsx($M,{...e})})})};function Oe(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),r===!1||!n.defaultPrevented)return t?.(n)}}function jf(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Gc(...e){return t=>{let r=!1;const o=e.map(n=>{const i=jf(n,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let n=0;n<o.length;n++){const i=o[n];typeof i=="function"?i():jf(e[n],null)}}}}function Ge(...e){return _.useCallback(Gc(...e),e)}function IM(e,t){const r=_.createContext(t),o=i=>{const{children:a,...s}=i,l=_.useMemo(()=>s,Object.values(s));return m.jsx(r.Provider,{value:l,children:a})};o.displayName=e+"Provider";function n(i){const a=_.useContext(r);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[o,n]}function Po(e,t=[]){let r=[];function o(i,a){const s=_.createContext(a),l=r.length;r=[...r,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const n=()=>{const i=r.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return n.scopeName=e,[o,kM(n,...t)]}function kM(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const o=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}function Kc(e){const t=EM(e),r=_.forwardRef((o,n)=>{const{children:i,...a}=o,s=_.Children.toArray(i),l=s.find(OM);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:n,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:n,children:i})});return r.displayName=`${e}.Slot`,r}function EM(e){const t=_.forwardRef((r,o)=>{const{children:n,...i}=r;if(_.isValidElement(n)){const a=PM(n),s=NM(i,n.props);return n.type!==_.Fragment&&(s.ref=o?Gc(o,a):a),_.cloneElement(n,s)}return _.Children.count(n)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var w$=Symbol("radix.slottable");function TM(e){const t=({children:r})=>m.jsx(m.Fragment,{children:r});return t.displayName=`${e}.Slottable`,t.__radixId=w$,t}function OM(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===w$}function NM(e,t){const r={...t};for(const o in t){const n=e[o],i=t[o];/^on[A-Z]/.test(o)?n&&i?r[o]=(...s)=>{const l=i(...s);return n(...s),l}:n&&(r[o]=n):o==="style"?r[o]={...n,...i}:o==="className"&&(r[o]=[n,i].filter(Boolean).join(" "))}return{...e,...r}}function PM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var CM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ce=CM.reduce((e,t)=>{const r=Kc(`Primitive.${t}`),o=_.forwardRef((n,i)=>{const{asChild:a,...s}=n,l=a?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function jM(e,t){e&&um.flushSync(()=>e.dispatchEvent(t))}function Sr(e){const t=_.useRef(e);return _.useEffect(()=>{t.current=e}),_.useMemo(()=>(...r)=>t.current?.(...r),[])}function AM(e,t=globalThis?.document){const r=Sr(e);_.useEffect(()=>{const o=n=>{n.key==="Escape"&&r(n)};return t.addEventListener("keydown",o,{capture:!0}),()=>t.removeEventListener("keydown",o,{capture:!0})},[r,t])}var RM="DismissableLayer",Nu="dismissableLayer.update",zM="dismissableLayer.pointerDownOutside",MM="dismissableLayer.focusOutside",Af,x$=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ka=_.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:n,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...l}=e,u=_.useContext(x$),[c,d]=_.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=_.useState({}),g=Ge(t,I=>d(I)),h=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=h.indexOf(b),x=c?h.indexOf(c):-1,$=u.layersWithOutsidePointerEventsDisabled.size>0,v=x>=y,k=LM(I=>{const O=I.target,M=[...u.branches].some(F=>F.contains(O));!v||M||(n?.(I),a?.(I),I.defaultPrevented||s?.())},f),N=ZM(I=>{const O=I.target;[...u.branches].some(F=>F.contains(O))||(i?.(I),a?.(I),I.defaultPrevented||s?.())},f);return AM(I=>{x===u.layers.size-1&&(o?.(I),!I.defaultPrevented&&s&&(I.preventDefault(),s()))},f),_.useEffect(()=>{if(c)return r&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Af=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),Rf(),()=>{r&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=Af)}},[c,f,r,u]),_.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),Rf())},[c,u]),_.useEffect(()=>{const I=()=>p({});return document.addEventListener(Nu,I),()=>document.removeEventListener(Nu,I)},[]),m.jsx(Ce.div,{...l,ref:g,style:{pointerEvents:$?v?"auto":"none":void 0,...e.style},onFocusCapture:Oe(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Oe(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Oe(e.onPointerDownCapture,k.onPointerDownCapture)})});Ka.displayName=RM;var DM="DismissableLayerBranch",UM=_.forwardRef((e,t)=>{const r=_.useContext(x$),o=_.useRef(null),n=Ge(t,o);return _.useEffect(()=>{const i=o.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),m.jsx(Ce.div,{...e,ref:n})});UM.displayName=DM;function LM(e,t=globalThis?.document){const r=Sr(e),o=_.useRef(!1),n=_.useRef(()=>{});return _.useEffect(()=>{const i=s=>{if(s.target&&!o.current){let l=function(){$$(zM,r,u,{discrete:!0})};const u={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",n.current),n.current=l,t.addEventListener("click",n.current,{once:!0})):l()}else t.removeEventListener("click",n.current);o.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",n.current)}},[t,r]),{onPointerDownCapture:()=>o.current=!0}}function ZM(e,t=globalThis?.document){const r=Sr(e),o=_.useRef(!1);return _.useEffect(()=>{const n=i=>{i.target&&!o.current&&$$(MM,r,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",n),()=>t.removeEventListener("focusin",n)},[t,r]),{onFocusCapture:()=>o.current=!0,onBlurCapture:()=>o.current=!1}}function Rf(){const e=new CustomEvent(Nu);document.dispatchEvent(e)}function $$(e,t,r,{discrete:o}){const n=r.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&n.addEventListener(e,t,{once:!0}),o?jM(n,i):n.dispatchEvent(i)}var lt=globalThis?.document?_.useLayoutEffect:()=>{},FM=_[" useId ".trim().toString()]||(()=>{}),qM=0;function qr(e){const[t,r]=_.useState(FM());return lt(()=>{r(o=>o??String(qM++))},[e]),t?`radix-${t}`:""}const VM=["top","right","bottom","left"],ur=Math.min,Ye=Math.max,Li=Math.round,Ko=Math.floor,At=e=>({x:e,y:e}),BM={left:"right",right:"left",bottom:"top",top:"bottom"},JM={start:"end",end:"start"};function Pu(e,t,r){return Ye(e,ur(t,r))}function Bt(e,t){return typeof e=="function"?e(t):e}function Jt(e){return e.split("-")[0]}function dn(e){return e.split("-")[1]}function Yc(e){return e==="x"?"y":"x"}function Qc(e){return e==="y"?"height":"width"}const WM=new Set(["top","bottom"]);function jt(e){return WM.has(Jt(e))?"y":"x"}function Xc(e){return Yc(jt(e))}function HM(e,t,r){r===void 0&&(r=!1);const o=dn(e),n=Xc(e),i=Qc(n);let a=n==="x"?o===(r?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Zi(a)),[a,Zi(a)]}function GM(e){const t=Zi(e);return[Cu(e),t,Cu(t)]}function Cu(e){return e.replace(/start|end/g,t=>JM[t])}const zf=["left","right"],Mf=["right","left"],KM=["top","bottom"],YM=["bottom","top"];function QM(e,t,r){switch(e){case"top":case"bottom":return r?t?Mf:zf:t?zf:Mf;case"left":case"right":return t?KM:YM;default:return[]}}function XM(e,t,r,o){const n=dn(e);let i=QM(Jt(e),r==="start",o);return n&&(i=i.map(a=>a+"-"+n),t&&(i=i.concat(i.map(Cu)))),i}function Zi(e){return e.replace(/left|right|bottom|top/g,t=>BM[t])}function e4(e){return{top:0,right:0,bottom:0,left:0,...e}}function S$(e){return typeof e!="number"?e4(e):{top:e,right:e,bottom:e,left:e}}function Fi(e){const{x:t,y:r,width:o,height:n}=e;return{width:o,height:n,top:r,left:t,right:t+o,bottom:r+n,x:t,y:r}}function Df(e,t,r){let{reference:o,floating:n}=e;const i=jt(t),a=Xc(t),s=Qc(a),l=Jt(t),u=i==="y",c=o.x+o.width/2-n.width/2,d=o.y+o.height/2-n.height/2,f=o[s]/2-n[s]/2;let p;switch(l){case"top":p={x:c,y:o.y-n.height};break;case"bottom":p={x:c,y:o.y+o.height};break;case"right":p={x:o.x+o.width,y:d};break;case"left":p={x:o.x-n.width,y:d};break;default:p={x:o.x,y:o.y}}switch(dn(t)){case"start":p[a]-=f*(r&&u?-1:1);break;case"end":p[a]+=f*(r&&u?-1:1);break}return p}const t4=async(e,t,r)=>{const{placement:o="bottom",strategy:n="absolute",middleware:i=[],platform:a}=r,s=i.filter(Boolean),l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:n}),{x:c,y:d}=Df(u,o,l),f=o,p={},g=0;for(let h=0;h<s.length;h++){const{name:b,fn:y}=s[h],{x,y:$,data:v,reset:k}=await y({x:c,y:d,initialPlacement:o,placement:f,strategy:n,middlewareData:p,rects:u,platform:a,elements:{reference:e,floating:t}});c=x??c,d=$??d,p={...p,[b]:{...p[b],...v}},k&&g<=50&&(g++,typeof k=="object"&&(k.placement&&(f=k.placement),k.rects&&(u=k.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:n}):k.rects),{x:c,y:d}=Df(u,f,l)),h=-1)}return{x:c,y:d,placement:f,strategy:n,middlewareData:p}};async function Kn(e,t){var r;t===void 0&&(t={});const{x:o,y:n,platform:i,rects:a,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Bt(t,e),g=S$(p),b=s[f?d==="floating"?"reference":"floating":d],y=Fi(await i.getClippingRect({element:(r=await(i.isElement==null?void 0:i.isElement(b)))==null||r?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:c,strategy:l})),x=d==="floating"?{x:o,y:n,width:a.floating.width,height:a.floating.height}:a.reference,$=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),v=await(i.isElement==null?void 0:i.isElement($))?await(i.getScale==null?void 0:i.getScale($))||{x:1,y:1}:{x:1,y:1},k=Fi(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:x,offsetParent:$,strategy:l}):x);return{top:(y.top-k.top+g.top)/v.y,bottom:(k.bottom-y.bottom+g.bottom)/v.y,left:(y.left-k.left+g.left)/v.x,right:(k.right-y.right+g.right)/v.x}}const r4=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:o,placement:n,rects:i,platform:a,elements:s,middlewareData:l}=t,{element:u,padding:c=0}=Bt(e,t)||{};if(u==null)return{};const d=S$(c),f={x:r,y:o},p=Xc(n),g=Qc(p),h=await a.getDimensions(u),b=p==="y",y=b?"top":"left",x=b?"bottom":"right",$=b?"clientHeight":"clientWidth",v=i.reference[g]+i.reference[p]-f[p]-i.floating[g],k=f[p]-i.reference[p],N=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let I=N?N[$]:0;(!I||!await(a.isElement==null?void 0:a.isElement(N)))&&(I=s.floating[$]||i.floating[g]);const O=v/2-k/2,M=I/2-h[g]/2-1,F=ur(d[y],M),te=ur(d[x],M),oe=F,J=I-h[g]-te,V=I/2-h[g]/2+O,ye=Pu(oe,V,J),ie=!l.arrow&&dn(n)!=null&&V!==ye&&i.reference[g]/2-(V<oe?F:te)-h[g]/2<0,de=ie?V<oe?V-oe:V-J:0;return{[p]:f[p]+de,data:{[p]:ye,centerOffset:V-ye-de,...ie&&{alignmentOffset:de}},reset:ie}}}),n4=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,o;const{placement:n,middlewareData:i,rects:a,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...b}=Bt(e,t);if((r=i.arrow)!=null&&r.alignmentOffset)return{};const y=Jt(n),x=jt(s),$=Jt(s)===s,v=await(l.isRTL==null?void 0:l.isRTL(u.floating)),k=f||($||!h?[Zi(s)]:GM(s)),N=g!=="none";!f&&N&&k.push(...XM(s,h,g,v));const I=[s,...k],O=await Kn(t,b),M=[];let F=((o=i.flip)==null?void 0:o.overflows)||[];if(c&&M.push(O[y]),d){const V=HM(n,a,v);M.push(O[V[0]],O[V[1]])}if(F=[...F,{placement:n,overflows:M}],!M.every(V=>V<=0)){var te,oe;const V=(((te=i.flip)==null?void 0:te.index)||0)+1,ye=I[V];if(ye&&(!(d==="alignment"?x!==jt(ye):!1)||F.every(K=>jt(K.placement)===x?K.overflows[0]>0:!0)))return{data:{index:V,overflows:F},reset:{placement:ye}};let ie=(oe=F.filter(de=>de.overflows[0]<=0).sort((de,K)=>de.overflows[1]-K.overflows[1])[0])==null?void 0:oe.placement;if(!ie)switch(p){case"bestFit":{var J;const de=(J=F.filter(K=>{if(N){const fe=jt(K.placement);return fe===x||fe==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(fe=>fe>0).reduce((fe,B)=>fe+B,0)]).sort((K,fe)=>K[1]-fe[1])[0])==null?void 0:J[0];de&&(ie=de);break}case"initialPlacement":ie=s;break}if(n!==ie)return{reset:{placement:ie}}}return{}}}};function Uf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Lf(e){return VM.some(t=>e[t]>=0)}const o4=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:o="referenceHidden",...n}=Bt(e,t);switch(o){case"referenceHidden":{const i=await Kn(t,{...n,elementContext:"reference"}),a=Uf(i,r.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:Lf(a)}}}case"escaped":{const i=await Kn(t,{...n,altBoundary:!0}),a=Uf(i,r.floating);return{data:{escapedOffsets:a,escaped:Lf(a)}}}default:return{}}}}},I$=new Set(["left","top"]);async function i4(e,t){const{placement:r,platform:o,elements:n}=e,i=await(o.isRTL==null?void 0:o.isRTL(n.floating)),a=Jt(r),s=dn(r),l=jt(r)==="y",u=I$.has(a)?-1:1,c=i&&l?-1:1,d=Bt(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof g=="number"&&(p=s==="end"?g*-1:g),l?{x:p*c,y:f*u}:{x:f*u,y:p*c}}const a4=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,o;const{x:n,y:i,placement:a,middlewareData:s}=t,l=await i4(t,e);return a===((r=s.offset)==null?void 0:r.placement)&&(o=s.arrow)!=null&&o.alignmentOffset?{}:{x:n+l.x,y:i+l.y,data:{...l,placement:a}}}}},s4=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:o,placement:n}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:s={fn:b=>{let{x:y,y:x}=b;return{x:y,y:x}}},...l}=Bt(e,t),u={x:r,y:o},c=await Kn(t,l),d=jt(Jt(n)),f=Yc(d);let p=u[f],g=u[d];if(i){const b=f==="y"?"top":"left",y=f==="y"?"bottom":"right",x=p+c[b],$=p-c[y];p=Pu(x,p,$)}if(a){const b=d==="y"?"top":"left",y=d==="y"?"bottom":"right",x=g+c[b],$=g-c[y];g=Pu(x,g,$)}const h=s.fn({...t,[f]:p,[d]:g});return{...h,data:{x:h.x-r,y:h.y-o,enabled:{[f]:i,[d]:a}}}}}},u4=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:o,placement:n,rects:i,middlewareData:a}=t,{offset:s=0,mainAxis:l=!0,crossAxis:u=!0}=Bt(e,t),c={x:r,y:o},d=jt(n),f=Yc(d);let p=c[f],g=c[d];const h=Bt(s,t),b=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const $=f==="y"?"height":"width",v=i.reference[f]-i.floating[$]+b.mainAxis,k=i.reference[f]+i.reference[$]-b.mainAxis;p<v?p=v:p>k&&(p=k)}if(u){var y,x;const $=f==="y"?"width":"height",v=I$.has(Jt(n)),k=i.reference[d]-i.floating[$]+(v&&((y=a.offset)==null?void 0:y[d])||0)+(v?0:b.crossAxis),N=i.reference[d]+i.reference[$]+(v?0:((x=a.offset)==null?void 0:x[d])||0)-(v?b.crossAxis:0);g<k?g=k:g>N&&(g=N)}return{[f]:p,[d]:g}}}},l4=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,o;const{placement:n,rects:i,platform:a,elements:s}=t,{apply:l=()=>{},...u}=Bt(e,t),c=await Kn(t,u),d=Jt(n),f=dn(n),p=jt(n)==="y",{width:g,height:h}=i.floating;let b,y;d==="top"||d==="bottom"?(b=d,y=f===(await(a.isRTL==null?void 0:a.isRTL(s.floating))?"start":"end")?"left":"right"):(y=d,b=f==="end"?"top":"bottom");const x=h-c.top-c.bottom,$=g-c.left-c.right,v=ur(h-c[b],x),k=ur(g-c[y],$),N=!t.middlewareData.shift;let I=v,O=k;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(O=$),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(I=x),N&&!f){const F=Ye(c.left,0),te=Ye(c.right,0),oe=Ye(c.top,0),J=Ye(c.bottom,0);p?O=g-2*(F!==0||te!==0?F+te:Ye(c.left,c.right)):I=h-2*(oe!==0||J!==0?oe+J:Ye(c.top,c.bottom))}await l({...t,availableWidth:O,availableHeight:I});const M=await a.getDimensions(s.floating);return g!==M.width||h!==M.height?{reset:{rects:!0}}:{}}}};function Ya(){return typeof window<"u"}function pn(e){return k$(e)?(e.nodeName||"").toLowerCase():"#document"}function Qe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dt(e){var t;return(t=(k$(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function k$(e){return Ya()?e instanceof Node||e instanceof Qe(e).Node:!1}function St(e){return Ya()?e instanceof Element||e instanceof Qe(e).Element:!1}function zt(e){return Ya()?e instanceof HTMLElement||e instanceof Qe(e).HTMLElement:!1}function Zf(e){return!Ya()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Qe(e).ShadowRoot}const c4=new Set(["inline","contents"]);function Co(e){const{overflow:t,overflowX:r,overflowY:o,display:n}=It(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+r)&&!c4.has(n)}const d4=new Set(["table","td","th"]);function p4(e){return d4.has(pn(e))}const f4=[":popover-open",":modal"];function Qa(e){return f4.some(t=>{try{return e.matches(t)}catch{return!1}})}const m4=["transform","translate","scale","rotate","perspective"],h4=["transform","translate","scale","rotate","perspective","filter"],g4=["paint","layout","strict","content"];function ed(e){const t=td(),r=St(e)?It(e):e;return m4.some(o=>r[o]?r[o]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||h4.some(o=>(r.willChange||"").includes(o))||g4.some(o=>(r.contain||"").includes(o))}function v4(e){let t=lr(e);for(;zt(t)&&!nn(t);){if(ed(t))return t;if(Qa(t))return null;t=lr(t)}return null}function td(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const y4=new Set(["html","body","#document"]);function nn(e){return y4.has(pn(e))}function It(e){return Qe(e).getComputedStyle(e)}function Xa(e){return St(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(pn(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Zf(e)&&e.host||Dt(e);return Zf(t)?t.host:t}function E$(e){const t=lr(e);return nn(t)?e.ownerDocument?e.ownerDocument.body:e.body:zt(t)&&Co(t)?t:E$(t)}function Yn(e,t,r){var o;t===void 0&&(t=[]),r===void 0&&(r=!0);const n=E$(e),i=n===((o=e.ownerDocument)==null?void 0:o.body),a=Qe(n);if(i){const s=ju(a);return t.concat(a,a.visualViewport||[],Co(n)?n:[],s&&r?Yn(s):[])}return t.concat(n,Yn(n,[],r))}function ju(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function T$(e){const t=It(e);let r=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const n=zt(e),i=n?e.offsetWidth:r,a=n?e.offsetHeight:o,s=Li(r)!==i||Li(o)!==a;return s&&(r=i,o=a),{width:r,height:o,$:s}}function rd(e){return St(e)?e:e.contextElement}function Vr(e){const t=rd(e);if(!zt(t))return At(1);const r=t.getBoundingClientRect(),{width:o,height:n,$:i}=T$(t);let a=(i?Li(r.width):r.width)/o,s=(i?Li(r.height):r.height)/n;return(!a||!Number.isFinite(a))&&(a=1),(!s||!Number.isFinite(s))&&(s=1),{x:a,y:s}}const b4=At(0);function O$(e){const t=Qe(e);return!td()||!t.visualViewport?b4:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function _4(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==Qe(e)?!1:t}function Ir(e,t,r,o){t===void 0&&(t=!1),r===void 0&&(r=!1);const n=e.getBoundingClientRect(),i=rd(e);let a=At(1);t&&(o?St(o)&&(a=Vr(o)):a=Vr(e));const s=_4(i,r,o)?O$(i):At(0);let l=(n.left+s.x)/a.x,u=(n.top+s.y)/a.y,c=n.width/a.x,d=n.height/a.y;if(i){const f=Qe(i),p=o&&St(o)?Qe(o):o;let g=f,h=ju(g);for(;h&&o&&p!==g;){const b=Vr(h),y=h.getBoundingClientRect(),x=It(h),$=y.left+(h.clientLeft+parseFloat(x.paddingLeft))*b.x,v=y.top+(h.clientTop+parseFloat(x.paddingTop))*b.y;l*=b.x,u*=b.y,c*=b.x,d*=b.y,l+=$,u+=v,g=Qe(h),h=ju(g)}}return Fi({width:c,height:d,x:l,y:u})}function nd(e,t){const r=Xa(e).scrollLeft;return t?t.left+r:Ir(Dt(e)).left+r}function N$(e,t,r){r===void 0&&(r=!1);const o=e.getBoundingClientRect(),n=o.left+t.scrollLeft-(r?0:nd(e,o)),i=o.top+t.scrollTop;return{x:n,y:i}}function w4(e){let{elements:t,rect:r,offsetParent:o,strategy:n}=e;const i=n==="fixed",a=Dt(o),s=t?Qa(t.floating):!1;if(o===a||s&&i)return r;let l={scrollLeft:0,scrollTop:0},u=At(1);const c=At(0),d=zt(o);if((d||!d&&!i)&&((pn(o)!=="body"||Co(a))&&(l=Xa(o)),zt(o))){const p=Ir(o);u=Vr(o),c.x=p.x+o.clientLeft,c.y=p.y+o.clientTop}const f=a&&!d&&!i?N$(a,l,!0):At(0);return{width:r.width*u.x,height:r.height*u.y,x:r.x*u.x-l.scrollLeft*u.x+c.x+f.x,y:r.y*u.y-l.scrollTop*u.y+c.y+f.y}}function x4(e){return Array.from(e.getClientRects())}function $4(e){const t=Dt(e),r=Xa(e),o=e.ownerDocument.body,n=Ye(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),i=Ye(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let a=-r.scrollLeft+nd(e);const s=-r.scrollTop;return It(o).direction==="rtl"&&(a+=Ye(t.clientWidth,o.clientWidth)-n),{width:n,height:i,x:a,y:s}}function S4(e,t){const r=Qe(e),o=Dt(e),n=r.visualViewport;let i=o.clientWidth,a=o.clientHeight,s=0,l=0;if(n){i=n.width,a=n.height;const u=td();(!u||u&&t==="fixed")&&(s=n.offsetLeft,l=n.offsetTop)}return{width:i,height:a,x:s,y:l}}const I4=new Set(["absolute","fixed"]);function k4(e,t){const r=Ir(e,!0,t==="fixed"),o=r.top+e.clientTop,n=r.left+e.clientLeft,i=zt(e)?Vr(e):At(1),a=e.clientWidth*i.x,s=e.clientHeight*i.y,l=n*i.x,u=o*i.y;return{width:a,height:s,x:l,y:u}}function Ff(e,t,r){let o;if(t==="viewport")o=S4(e,r);else if(t==="document")o=$4(Dt(e));else if(St(t))o=k4(t,r);else{const n=O$(e);o={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Fi(o)}function P$(e,t){const r=lr(e);return r===t||!St(r)||nn(r)?!1:It(r).position==="fixed"||P$(r,t)}function E4(e,t){const r=t.get(e);if(r)return r;let o=Yn(e,[],!1).filter(s=>St(s)&&pn(s)!=="body"),n=null;const i=It(e).position==="fixed";let a=i?lr(e):e;for(;St(a)&&!nn(a);){const s=It(a),l=ed(a);!l&&s.position==="fixed"&&(n=null),(i?!l&&!n:!l&&s.position==="static"&&!!n&&I4.has(n.position)||Co(a)&&!l&&P$(e,a))?o=o.filter(c=>c!==a):n=s,a=lr(a)}return t.set(e,o),o}function T4(e){let{element:t,boundary:r,rootBoundary:o,strategy:n}=e;const a=[...r==="clippingAncestors"?Qa(t)?[]:E4(t,this._c):[].concat(r),o],s=a[0],l=a.reduce((u,c)=>{const d=Ff(t,c,n);return u.top=Ye(d.top,u.top),u.right=ur(d.right,u.right),u.bottom=ur(d.bottom,u.bottom),u.left=Ye(d.left,u.left),u},Ff(t,s,n));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function O4(e){const{width:t,height:r}=T$(e);return{width:t,height:r}}function N4(e,t,r){const o=zt(t),n=Dt(t),i=r==="fixed",a=Ir(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=At(0);function u(){l.x=nd(n)}if(o||!o&&!i)if((pn(t)!=="body"||Co(n))&&(s=Xa(t)),o){const p=Ir(t,!0,i,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else n&&u();i&&!o&&n&&u();const c=n&&!o&&!i?N$(n,s):At(0),d=a.left+s.scrollLeft-l.x-c.x,f=a.top+s.scrollTop-l.y-c.y;return{x:d,y:f,width:a.width,height:a.height}}function Ls(e){return It(e).position==="static"}function qf(e,t){if(!zt(e)||It(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Dt(e)===r&&(r=r.ownerDocument.body),r}function C$(e,t){const r=Qe(e);if(Qa(e))return r;if(!zt(e)){let n=lr(e);for(;n&&!nn(n);){if(St(n)&&!Ls(n))return n;n=lr(n)}return r}let o=qf(e,t);for(;o&&p4(o)&&Ls(o);)o=qf(o,t);return o&&nn(o)&&Ls(o)&&!ed(o)?r:o||v4(e)||r}const P4=async function(e){const t=this.getOffsetParent||C$,r=this.getDimensions,o=await r(e.floating);return{reference:N4(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function C4(e){return It(e).direction==="rtl"}const j4={convertOffsetParentRelativeRectToViewportRelativeRect:w4,getDocumentElement:Dt,getClippingRect:T4,getOffsetParent:C$,getElementRects:P4,getClientRects:x4,getDimensions:O4,getScale:Vr,isElement:St,isRTL:C4};function j$(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function A4(e,t){let r=null,o;const n=Dt(e);function i(){var s;clearTimeout(o),(s=r)==null||s.disconnect(),r=null}function a(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=u;if(s||t(),!f||!p)return;const g=Ko(d),h=Ko(n.clientWidth-(c+f)),b=Ko(n.clientHeight-(d+p)),y=Ko(c),$={rootMargin:-g+"px "+-h+"px "+-b+"px "+-y+"px",threshold:Ye(0,ur(1,l))||1};let v=!0;function k(N){const I=N[0].intersectionRatio;if(I!==l){if(!v)return a();I?a(!1,I):o=setTimeout(()=>{a(!1,1e-7)},1e3)}I===1&&!j$(u,e.getBoundingClientRect())&&a(),v=!1}try{r=new IntersectionObserver(k,{...$,root:n.ownerDocument})}catch{r=new IntersectionObserver(k,$)}r.observe(e)}return a(!0),i}function R4(e,t,r,o){o===void 0&&(o={});const{ancestorScroll:n=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=o,u=rd(e),c=n||i?[...u?Yn(u):[],...Yn(t)]:[];c.forEach(y=>{n&&y.addEventListener("scroll",r,{passive:!0}),i&&y.addEventListener("resize",r)});const d=u&&s?A4(u,r):null;let f=-1,p=null;a&&(p=new ResizeObserver(y=>{let[x]=y;x&&x.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var $;($=p)==null||$.observe(t)})),r()}),u&&!l&&p.observe(u),p.observe(t));let g,h=l?Ir(e):null;l&&b();function b(){const y=Ir(e);h&&!j$(h,y)&&r(),h=y,g=requestAnimationFrame(b)}return r(),()=>{var y;c.forEach(x=>{n&&x.removeEventListener("scroll",r),i&&x.removeEventListener("resize",r)}),d?.(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(g)}}const z4=a4,M4=s4,D4=n4,U4=l4,L4=o4,Vf=r4,Z4=u4,F4=(e,t,r)=>{const o=new Map,n={platform:j4,...r},i={...n.platform,_c:o};return t4(e,t,{...n,platform:i})};var q4=typeof document<"u",V4=function(){},si=q4?z.useLayoutEffect:V4;function qi(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 r,o,n;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(o=r;o--!==0;)if(!qi(e[o],t[o]))return!1;return!0}if(n=Object.keys(e),r=n.length,r!==Object.keys(t).length)return!1;for(o=r;o--!==0;)if(!{}.hasOwnProperty.call(t,n[o]))return!1;for(o=r;o--!==0;){const i=n[o];if(!(i==="_owner"&&e.$$typeof)&&!qi(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function A$(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Bf(e,t){const r=A$(e);return Math.round(t*r)/r}function Zs(e){const t=_.useRef(e);return si(()=>{t.current=e}),t}function B4(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:o=[],platform:n,elements:{reference:i,floating:a}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[c,d]=_.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=_.useState(o);qi(f,o)||p(o);const[g,h]=_.useState(null),[b,y]=_.useState(null),x=_.useCallback(K=>{K!==N.current&&(N.current=K,h(K))},[]),$=_.useCallback(K=>{K!==I.current&&(I.current=K,y(K))},[]),v=i||g,k=a||b,N=_.useRef(null),I=_.useRef(null),O=_.useRef(c),M=l!=null,F=Zs(l),te=Zs(n),oe=Zs(u),J=_.useCallback(()=>{if(!N.current||!I.current)return;const K={placement:t,strategy:r,middleware:f};te.current&&(K.platform=te.current),F4(N.current,I.current,K).then(fe=>{const B={...fe,isPositioned:oe.current!==!1};V.current&&!qi(O.current,B)&&(O.current=B,um.flushSync(()=>{d(B)}))})},[f,t,r,te,oe]);si(()=>{u===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,d(K=>({...K,isPositioned:!1})))},[u]);const V=_.useRef(!1);si(()=>(V.current=!0,()=>{V.current=!1}),[]),si(()=>{if(v&&(N.current=v),k&&(I.current=k),v&&k){if(F.current)return F.current(v,k,J);J()}},[v,k,J,F,M]);const ye=_.useMemo(()=>({reference:N,floating:I,setReference:x,setFloating:$}),[x,$]),ie=_.useMemo(()=>({reference:v,floating:k}),[v,k]),de=_.useMemo(()=>{const K={position:r,left:0,top:0};if(!ie.floating)return K;const fe=Bf(ie.floating,c.x),B=Bf(ie.floating,c.y);return s?{...K,transform:"translate("+fe+"px, "+B+"px)",...A$(ie.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:fe,top:B}},[r,s,ie.floating,c.x,c.y]);return _.useMemo(()=>({...c,update:J,refs:ye,elements:ie,floatingStyles:de}),[c,J,ye,ie,de])}const J4=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:o,padding:n}=typeof e=="function"?e(r):e;return o&&t(o)?o.current!=null?Vf({element:o.current,padding:n}).fn(r):{}:o?Vf({element:o,padding:n}).fn(r):{}}}},W4=(e,t)=>({...z4(e),options:[e,t]}),H4=(e,t)=>({...M4(e),options:[e,t]}),G4=(e,t)=>({...Z4(e),options:[e,t]}),K4=(e,t)=>({...D4(e),options:[e,t]}),Y4=(e,t)=>({...U4(e),options:[e,t]}),Q4=(e,t)=>({...L4(e),options:[e,t]}),X4=(e,t)=>({...J4(e),options:[e,t]});var eD="Arrow",R$=_.forwardRef((e,t)=>{const{children:r,width:o=10,height:n=5,...i}=e;return m.jsx(Ce.svg,{...i,ref:t,width:o,height:n,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:m.jsx("polygon",{points:"0,0 30,0 15,10"})})});R$.displayName=eD;var tD=R$;function rD(e){const[t,r]=_.useState(void 0);return lt(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const o=new ResizeObserver(n=>{if(!Array.isArray(n)||!n.length)return;const i=n[0];let a,s;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;a=u.inlineSize,s=u.blockSize}else a=e.offsetWidth,s=e.offsetHeight;r({width:a,height:s})});return o.observe(e,{box:"border-box"}),()=>o.unobserve(e)}else r(void 0)},[e]),t}var od="Popper",[z$,es]=Po(od),[nD,M$]=z$(od),D$=e=>{const{__scopePopper:t,children:r}=e,[o,n]=_.useState(null);return m.jsx(nD,{scope:t,anchor:o,onAnchorChange:n,children:r})};D$.displayName=od;var U$="PopperAnchor",L$=_.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:o,...n}=e,i=M$(U$,r),a=_.useRef(null),s=Ge(t,a),l=_.useRef(null);return _.useEffect(()=>{const u=l.current;l.current=o?.current||a.current,u!==l.current&&i.onAnchorChange(l.current)}),o?null:m.jsx(Ce.div,{...n,ref:s})});L$.displayName=U$;var id="PopperContent",[oD,iD]=z$(id),Z$=_.forwardRef((e,t)=>{const{__scopePopper:r,side:o="bottom",sideOffset:n=0,align:i="center",alignOffset:a=0,arrowPadding:s=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:g,...h}=e,b=M$(id,r),[y,x]=_.useState(null),$=Ge(t,xe=>x(xe)),[v,k]=_.useState(null),N=rD(v),I=N?.width??0,O=N?.height??0,M=o+(i!=="center"?"-"+i:""),F=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},te=Array.isArray(u)?u:[u],oe=te.length>0,J={padding:F,boundary:te.filter(sD),altBoundary:oe},{refs:V,floatingStyles:ye,placement:ie,isPositioned:de,middlewareData:K}=B4({strategy:"fixed",placement:M,whileElementsMounted:(...xe)=>R4(...xe,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[W4({mainAxis:n+O,alignmentAxis:a}),l&&H4({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?G4():void 0,...J}),l&&K4({...J}),Y4({...J,apply:({elements:xe,rects:Ro,availableWidth:ls,availableHeight:fn})=>{const{width:pt,height:zo}=Ro.reference,je=xe.floating.style;je.setProperty("--radix-popper-available-width",`${ls}px`),je.setProperty("--radix-popper-available-height",`${fn}px`),je.setProperty("--radix-popper-anchor-width",`${pt}px`),je.setProperty("--radix-popper-anchor-height",`${zo}px`)}}),v&&X4({element:v,padding:s}),uD({arrowWidth:I,arrowHeight:O}),f&&Q4({strategy:"referenceHidden",...J})]}),[fe,B]=V$(ie),Ue=Sr(g);lt(()=>{de&&Ue?.()},[de,Ue]);const be=K.arrow?.x,Le=K.arrow?.y,U=K.arrow?.centerOffset!==0,[Q,me]=_.useState();return lt(()=>{y&&me(window.getComputedStyle(y).zIndex)},[y]),m.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...ye,transform:de?ye.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[K.transformOrigin?.x,K.transformOrigin?.y].join(" "),...K.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:m.jsx(oD,{scope:r,placedSide:fe,onArrowChange:k,arrowX:be,arrowY:Le,shouldHideArrow:U,children:m.jsx(Ce.div,{"data-side":fe,"data-align":B,...h,ref:$,style:{...h.style,animation:de?void 0:"none"}})})})});Z$.displayName=id;var F$="PopperArrow",aD={top:"bottom",right:"left",bottom:"top",left:"right"},q$=_.forwardRef(function(t,r){const{__scopePopper:o,...n}=t,i=iD(F$,o),a=aD[i.placedSide];return m.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:m.jsx(tD,{...n,ref:r,style:{...n.style,display:"block"}})})});q$.displayName=F$;function sD(e){return e!==null}var uD=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:o,middlewareData:n}=t,a=n.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,l=a?0:e.arrowHeight,[u,c]=V$(r),d={start:"0%",center:"50%",end:"100%"}[c],f=(n.arrow?.x??0)+s/2,p=(n.arrow?.y??0)+l/2;let g="",h="";return u==="bottom"?(g=a?d:`${f}px`,h=`${-l}px`):u==="top"?(g=a?d:`${f}px`,h=`${o.floating.height+l}px`):u==="right"?(g=`${-l}px`,h=a?d:`${p}px`):u==="left"&&(g=`${o.floating.width+l}px`,h=a?d:`${p}px`),{data:{x:g,y:h}}}});function V$(e){const[t,r="center"]=e.split("-");return[t,r]}var B$=D$,ad=L$,J$=Z$,W$=q$,lD="Portal",ts=_.forwardRef((e,t)=>{const{container:r,...o}=e,[n,i]=_.useState(!1);lt(()=>i(!0),[]);const a=r||n&&globalThis?.document?.body;return a?sm.createPortal(m.jsx(Ce.div,{...o,ref:t}),a):null});ts.displayName=lD;function cD(e,t){return _.useReducer((r,o)=>t[r][o]??r,e)}var Gt=e=>{const{present:t,children:r}=e,o=dD(t),n=typeof r=="function"?r({present:o.isPresent}):_.Children.only(r),i=Ge(o.ref,pD(n));return typeof r=="function"||o.isPresent?_.cloneElement(n,{ref:i}):null};Gt.displayName="Presence";function dD(e){const[t,r]=_.useState(),o=_.useRef(null),n=_.useRef(e),i=_.useRef("none"),a=e?"mounted":"unmounted",[s,l]=cD(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const u=Yo(o.current);i.current=s==="mounted"?u:"none"},[s]),lt(()=>{const u=o.current,c=n.current;if(c!==e){const f=i.current,p=Yo(u);e?l("MOUNT"):p==="none"||u?.display==="none"?l("UNMOUNT"):l(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),n.current=e}},[e,l]),lt(()=>{if(t){let u;const c=t.ownerDocument.defaultView??window,d=p=>{const h=Yo(o.current).includes(CSS.escape(p.animationName));if(p.target===t&&h&&(l("ANIMATION_END"),!n.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",u=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=p=>{p.target===t&&(i.current=Yo(o.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(s),ref:_.useCallback(u=>{o.current=u?getComputedStyle(u):null,r(u)},[])}}function Yo(e){return e?.animationName||"none"}function pD(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var fD=_[" useInsertionEffect ".trim().toString()]||lt;function rs({prop:e,defaultProp:t,onChange:r=()=>{},caller:o}){const[n,i,a]=mD({defaultProp:t,onChange:r}),s=e!==void 0,l=s?e:n;{const c=_.useRef(e!==void 0);_.useEffect(()=>{const d=c.current;d!==s&&console.warn(`${o} is changing from ${d?"controlled":"uncontrolled"} to ${s?"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=s},[s,o])}const u=_.useCallback(c=>{if(s){const d=hD(c)?c(e):c;d!==e&&a.current?.(d)}else i(c)},[s,e,i,a]);return[l,u]}function mD({defaultProp:e,onChange:t}){const[r,o]=_.useState(e),n=_.useRef(r),i=_.useRef(t);return fD(()=>{i.current=t},[t]),_.useEffect(()=>{n.current!==r&&(i.current?.(r),n.current=r)},[r,n]),[r,o,i]}function hD(e){return typeof e=="function"}var gD=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"}),vD="VisuallyHidden",H$=_.forwardRef((e,t)=>m.jsx(Ce.span,{...e,ref:t,style:{...gD,...e.style}}));H$.displayName=vD;var yD=H$,[ns]=Po("Tooltip",[es]),os=es(),G$="TooltipProvider",bD=700,Au="tooltip.open",[_D,sd]=ns(G$),K$=e=>{const{__scopeTooltip:t,delayDuration:r=bD,skipDelayDuration:o=300,disableHoverableContent:n=!1,children:i}=e,a=_.useRef(!0),s=_.useRef(!1),l=_.useRef(0);return _.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),m.jsx(_D,{scope:t,isOpenDelayedRef:a,delayDuration:r,onOpen:_.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,o)},[o]),isPointerInTransitRef:s,onPointerInTransitChange:_.useCallback(u=>{s.current=u},[]),disableHoverableContent:n,children:i})};K$.displayName=G$;var Qn="Tooltip",[wD,jo]=ns(Qn),Y$=e=>{const{__scopeTooltip:t,children:r,open:o,defaultOpen:n,onOpenChange:i,disableHoverableContent:a,delayDuration:s}=e,l=sd(Qn,e.__scopeTooltip),u=os(t),[c,d]=_.useState(null),f=qr(),p=_.useRef(0),g=a??l.disableHoverableContent,h=s??l.delayDuration,b=_.useRef(!1),[y,x]=rs({prop:o,defaultProp:n??!1,onChange:I=>{I?(l.onOpen(),document.dispatchEvent(new CustomEvent(Au))):l.onClose(),i?.(I)},caller:Qn}),$=_.useMemo(()=>y?b.current?"delayed-open":"instant-open":"closed",[y]),v=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b.current=!1,x(!0)},[x]),k=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x(!1)},[x]),N=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b.current=!0,x(!0),p.current=0},h)},[h,x]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),m.jsx(B$,{...u,children:m.jsx(wD,{scope:t,contentId:f,open:y,stateAttribute:$,trigger:c,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{l.isOpenDelayedRef.current?N():v()},[l.isOpenDelayedRef,N,v]),onTriggerLeave:_.useCallback(()=>{g?k():(window.clearTimeout(p.current),p.current=0)},[k,g]),onOpen:v,onClose:k,disableHoverableContent:g,children:r})})};Y$.displayName=Qn;var Ru="TooltipTrigger",Q$=_.forwardRef((e,t)=>{const{__scopeTooltip:r,...o}=e,n=jo(Ru,r),i=sd(Ru,r),a=os(r),s=_.useRef(null),l=Ge(t,s,n.onTriggerChange),u=_.useRef(!1),c=_.useRef(!1),d=_.useCallback(()=>u.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),m.jsx(ad,{asChild:!0,...a,children:m.jsx(Ce.button,{"aria-describedby":n.open?n.contentId:void 0,"data-state":n.stateAttribute,...o,ref:l,onPointerMove:Oe(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!i.isPointerInTransitRef.current&&(n.onTriggerEnter(),c.current=!0)}),onPointerLeave:Oe(e.onPointerLeave,()=>{n.onTriggerLeave(),c.current=!1}),onPointerDown:Oe(e.onPointerDown,()=>{n.open&&n.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Oe(e.onFocus,()=>{u.current||n.onOpen()}),onBlur:Oe(e.onBlur,n.onClose),onClick:Oe(e.onClick,n.onClose)})})});Q$.displayName=Ru;var ud="TooltipPortal",[xD,$D]=ns(ud,{forceMount:void 0}),X$=e=>{const{__scopeTooltip:t,forceMount:r,children:o,container:n}=e,i=jo(ud,t);return m.jsx(xD,{scope:t,forceMount:r,children:m.jsx(Gt,{present:r||i.open,children:m.jsx(ts,{asChild:!0,container:n,children:o})})})};X$.displayName=ud;var on="TooltipContent",eS=_.forwardRef((e,t)=>{const r=$D(on,e.__scopeTooltip),{forceMount:o=r.forceMount,side:n="top",...i}=e,a=jo(on,e.__scopeTooltip);return m.jsx(Gt,{present:o||a.open,children:a.disableHoverableContent?m.jsx(tS,{side:n,...i,ref:t}):m.jsx(SD,{side:n,...i,ref:t})})}),SD=_.forwardRef((e,t)=>{const r=jo(on,e.__scopeTooltip),o=sd(on,e.__scopeTooltip),n=_.useRef(null),i=Ge(t,n),[a,s]=_.useState(null),{trigger:l,onClose:u}=r,c=n.current,{onPointerInTransitChange:d}=o,f=_.useCallback(()=>{s(null),d(!1)},[d]),p=_.useCallback((g,h)=>{const b=g.currentTarget,y={x:g.clientX,y:g.clientY},x=TD(y,b.getBoundingClientRect()),$=OD(y,x),v=ND(h.getBoundingClientRect()),k=CD([...$,...v]);s(k),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(l&&c){const g=b=>p(b,c),h=b=>p(b,l);return l.addEventListener("pointerleave",g),c.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),c.removeEventListener("pointerleave",h)}}},[l,c,p,f]),_.useEffect(()=>{if(a){const g=h=>{const b=h.target,y={x:h.clientX,y:h.clientY},x=l?.contains(b)||c?.contains(b),$=!PD(y,a);x?f():$&&(f(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,c,a,u,f]),m.jsx(tS,{...e,ref:i})}),[ID,kD]=ns(Qn,{isInside:!1}),ED=TM("TooltipContent"),tS=_.forwardRef((e,t)=>{const{__scopeTooltip:r,children:o,"aria-label":n,onEscapeKeyDown:i,onPointerDownOutside:a,...s}=e,l=jo(on,r),u=os(r),{onClose:c}=l;return _.useEffect(()=>(document.addEventListener(Au,c),()=>document.removeEventListener(Au,c)),[c]),_.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]),m.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:m.jsxs(J$,{"data-state":l.stateAttribute,...u,...s,ref:t,style:{...s.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:[m.jsx(ED,{children:o}),m.jsx(ID,{scope:r,isInside:!0,children:m.jsx(yD,{id:l.contentId,role:"tooltip",children:n||o})})]})})});eS.displayName=on;var rS="TooltipArrow",nS=_.forwardRef((e,t)=>{const{__scopeTooltip:r,...o}=e,n=os(r);return kD(rS,r).isInside?null:m.jsx(W$,{...n,...o,ref:t})});nS.displayName=rS;function TD(e,t){const r=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),n=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(r,o,n,i)){case i:return"left";case n:return"right";case r:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function OD(e,t,r=5){const o=[];switch(t){case"top":o.push({x:e.x-r,y:e.y+r},{x:e.x+r,y:e.y+r});break;case"bottom":o.push({x:e.x-r,y:e.y-r},{x:e.x+r,y:e.y-r});break;case"left":o.push({x:e.x+r,y:e.y-r},{x:e.x+r,y:e.y+r});break;case"right":o.push({x:e.x-r,y:e.y-r},{x:e.x-r,y:e.y+r});break}return o}function ND(e){const{top:t,right:r,bottom:o,left:n}=e;return[{x:n,y:t},{x:r,y:t},{x:r,y:o},{x:n,y:o}]}function PD(e,t){const{x:r,y:o}=e;let n=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const s=t[i],l=t[a],u=s.x,c=s.y,d=l.x,f=l.y;c>o!=f>o&&r<(d-u)*(o-c)/(f-c)+u&&(n=!n)}return n}function CD(e){const t=e.slice();return t.sort((r,o)=>r.x<o.x?-1:r.x>o.x?1:r.y<o.y?-1:r.y>o.y?1:0),jD(t)}function jD(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o<e.length;o++){const n=e[o];for(;t.length>=2;){const i=t[t.length-1],a=t[t.length-2];if((i.x-a.x)*(n.y-a.y)>=(i.y-a.y)*(n.x-a.x))t.pop();else break}t.push(n)}t.pop();const r=[];for(let o=e.length-1;o>=0;o--){const n=e[o];for(;r.length>=2;){const i=r[r.length-1],a=r[r.length-2];if((i.x-a.x)*(n.y-a.y)>=(i.y-a.y)*(n.x-a.x))r.pop();else break}r.push(n)}return r.pop(),t.length===1&&r.length===1&&t[0].x===r[0].x&&t[0].y===r[0].y?t:t.concat(r)}var AD=K$,RD=Y$,zD=Q$,MD=X$,DD=eS,UD=nS;function oS({delayDuration:e=0,...t}){return m.jsx(AD,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ld({...e}){return m.jsx(oS,{children:m.jsx(RD,{"data-slot":"tooltip",...e})})}function cd({...e}){return m.jsx(zD,{"data-slot":"tooltip-trigger",...e})}function dd({className:e,sideOffset:t=0,children:r,...o}){return m.jsx(MD,{children:m.jsxs(DD,{"data-slot":"tooltip-content",sideOffset:t,className:T.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),...o,children:[r,m.jsx(UD,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}var Fs="focusScope.autoFocusOnMount",qs="focusScope.autoFocusOnUnmount",Jf={bubbles:!1,cancelable:!0},LD="FocusScope",pd=_.forwardRef((e,t)=>{const{loop:r=!1,trapped:o=!1,onMountAutoFocus:n,onUnmountAutoFocus:i,...a}=e,[s,l]=_.useState(null),u=Sr(n),c=Sr(i),d=_.useRef(null),f=Ge(t,h=>l(h)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(o){let h=function($){if(p.paused||!s)return;const v=$.target;s.contains(v)?d.current=v:Qt(d.current,{select:!0})},b=function($){if(p.paused||!s)return;const v=$.relatedTarget;v!==null&&(s.contains(v)||Qt(d.current,{select:!0}))},y=function($){if(document.activeElement===document.body)for(const k of $)k.removedNodes.length>0&&Qt(s)};document.addEventListener("focusin",h),document.addEventListener("focusout",b);const x=new MutationObserver(y);return s&&x.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),x.disconnect()}}},[o,s,p.paused]),_.useEffect(()=>{if(s){Hf.add(p);const h=document.activeElement;if(!s.contains(h)){const y=new CustomEvent(Fs,Jf);s.addEventListener(Fs,u),s.dispatchEvent(y),y.defaultPrevented||(ZD(JD(iS(s)),{select:!0}),document.activeElement===h&&Qt(s))}return()=>{s.removeEventListener(Fs,u),setTimeout(()=>{const y=new CustomEvent(qs,Jf);s.addEventListener(qs,c),s.dispatchEvent(y),y.defaultPrevented||Qt(h??document.body,{select:!0}),s.removeEventListener(qs,c),Hf.remove(p)},0)}}},[s,u,c,p]);const g=_.useCallback(h=>{if(!r&&!o||p.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,y=document.activeElement;if(b&&y){const x=h.currentTarget,[$,v]=FD(x);$&&v?!h.shiftKey&&y===v?(h.preventDefault(),r&&Qt($,{select:!0})):h.shiftKey&&y===$&&(h.preventDefault(),r&&Qt(v,{select:!0})):y===x&&h.preventDefault()}},[r,o,p.paused]);return m.jsx(Ce.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});pd.displayName=LD;function ZD(e,{select:t=!1}={}){const r=document.activeElement;for(const o of e)if(Qt(o,{select:t}),document.activeElement!==r)return}function FD(e){const t=iS(e),r=Wf(t,e),o=Wf(t.reverse(),e);return[r,o]}function iS(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const n=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||n?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Wf(e,t){for(const r of e)if(!qD(r,{upTo:t}))return r}function qD(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 VD(e){return e instanceof HTMLInputElement&&"select"in e}function Qt(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&VD(e)&&t&&e.select()}}var Hf=BD();function BD(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=Gf(e,t),e.unshift(t)},remove(t){e=Gf(e,t),e[0]?.resume()}}}function Gf(e,t){const r=[...e],o=r.indexOf(t);return o!==-1&&r.splice(o,1),r}function JD(e){return e.filter(t=>t.tagName!=="A")}var Vs=0;function aS(){_.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Kf()),document.body.insertAdjacentElement("beforeend",e[1]??Kf()),Vs++,()=>{Vs===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Vs--}},[])}function Kf(){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 Pt=function(){return Pt=Object.assign||function(t){for(var r,o=1,n=arguments.length;o<n;o++){r=arguments[o];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},Pt.apply(this,arguments)};function sS(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(r[o[n]]=e[o[n]]);return r}function WD(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++)(i||!(o in t))&&(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}var ui="right-scroll-bar-position",li="width-before-scroll-bar",HD="with-scroll-bars-hidden",GD="--removed-body-scroll-bar-size";function Bs(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function KD(e,t){var r=z.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(o){var n=r.value;n!==o&&(r.value=o,r.callback(o,n))}}}})[0];return r.callback=t,r.facade}var YD=typeof window<"u"?_.useLayoutEffect:_.useEffect,Yf=new WeakMap;function QD(e,t){var r=KD(null,function(o){return e.forEach(function(n){return Bs(n,o)})});return YD(function(){var o=Yf.get(r);if(o){var n=new Set(o),i=new Set(e),a=r.current;n.forEach(function(s){i.has(s)||Bs(s,null)}),i.forEach(function(s){n.has(s)||Bs(s,a)})}Yf.set(r,e)},[e]),r}function XD(e){return e}function eU(e,t){t===void 0&&(t=XD);var r=[],o=!1,n={read:function(){if(o)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(i){var a=t(i,o);return r.push(a),function(){r=r.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(o=!0;r.length;){var a=r;r=[],a.forEach(i)}r={push:function(s){return i(s)},filter:function(){return r}}},assignMedium:function(i){o=!0;var a=[];if(r.length){var s=r;r=[],s.forEach(i),a=r}var l=function(){var c=a;a=[],c.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),r={push:function(c){a.push(c),u()},filter:function(c){return a=a.filter(c),r}}}};return n}function tU(e){e===void 0&&(e={});var t=eU(null);return t.options=Pt({async:!0,ssr:!1},e),t}var uS=function(e){var t=e.sideCar,r=sS(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var o=t.read();if(!o)throw new Error("Sidecar medium not found");return _.createElement(o,Pt({},r))};uS.isSideCarExport=!0;function rU(e,t){return e.useMedium(t),uS}var lS=tU(),Js=function(){},is=_.forwardRef(function(e,t){var r=_.useRef(null),o=_.useState({onScrollCapture:Js,onWheelCapture:Js,onTouchMoveCapture:Js}),n=o[0],i=o[1],a=e.forwardProps,s=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,g=e.noIsolation,h=e.inert,b=e.allowPinchZoom,y=e.as,x=y===void 0?"div":y,$=e.gapMode,v=sS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=f,N=QD([r,t]),I=Pt(Pt({},v),n);return _.createElement(_.Fragment,null,c&&_.createElement(k,{sideCar:lS,removeScrollBar:u,shards:d,noRelative:p,noIsolation:g,inert:h,setCallbacks:i,allowPinchZoom:!!b,lockRef:r,gapMode:$}),a?_.cloneElement(_.Children.only(s),Pt(Pt({},I),{ref:N})):_.createElement(x,Pt({},I,{className:l,ref:N}),s))});is.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};is.classNames={fullWidth:li,zeroRight:ui};var nU=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function oU(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=nU();return t&&e.setAttribute("nonce",t),e}function iU(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function aU(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var sU=function(){var e=0,t=null;return{add:function(r){e==0&&(t=oU())&&(iU(t,r),aU(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},uU=function(){var e=sU();return function(t,r){_.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},cS=function(){var e=uU(),t=function(r){var o=r.styles,n=r.dynamic;return e(o,n),null};return t},lU={left:0,top:0,right:0,gap:0},Ws=function(e){return parseInt(e||"",10)||0},cU=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],o=t[e==="padding"?"paddingTop":"marginTop"],n=t[e==="padding"?"paddingRight":"marginRight"];return[Ws(r),Ws(o),Ws(n)]},dU=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return lU;var t=cU(e),r=document.documentElement.clientWidth,o=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,o-r+t[2]-t[0])}},pU=cS(),Br="data-scroll-locked",fU=function(e,t,r,o){var n=e.left,i=e.top,a=e.right,s=e.gap;return r===void 0&&(r="margin"),`
|
|
97
|
-
.`.concat(HD,` {
|
|
98
|
-
overflow: hidden `).concat(o,`;
|
|
99
|
-
padding-right: `).concat(s,"px ").concat(o,`;
|
|
100
|
-
}
|
|
101
|
-
body[`).concat(Br,`] {
|
|
102
|
-
overflow: hidden `).concat(o,`;
|
|
103
|
-
overscroll-behavior: contain;
|
|
104
|
-
`).concat([t&&"position: relative ".concat(o,";"),r==="margin"&&`
|
|
105
|
-
padding-left: `.concat(n,`px;
|
|
106
|
-
padding-top: `).concat(i,`px;
|
|
107
|
-
padding-right: `).concat(a,`px;
|
|
108
|
-
margin-left:0;
|
|
109
|
-
margin-top:0;
|
|
110
|
-
margin-right: `).concat(s,"px ").concat(o,`;
|
|
111
|
-
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(o,";")].filter(Boolean).join(""),`
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
.`).concat(ui,` {
|
|
115
|
-
right: `).concat(s,"px ").concat(o,`;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
.`).concat(li,` {
|
|
119
|
-
margin-right: `).concat(s,"px ").concat(o,`;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
.`).concat(ui," .").concat(ui,` {
|
|
123
|
-
right: 0 `).concat(o,`;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
.`).concat(li," .").concat(li,` {
|
|
127
|
-
margin-right: 0 `).concat(o,`;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
body[`).concat(Br,`] {
|
|
131
|
-
`).concat(GD,": ").concat(s,`px;
|
|
132
|
-
}
|
|
133
|
-
`)},Qf=function(){var e=parseInt(document.body.getAttribute(Br)||"0",10);return isFinite(e)?e:0},mU=function(){_.useEffect(function(){return document.body.setAttribute(Br,(Qf()+1).toString()),function(){var e=Qf()-1;e<=0?document.body.removeAttribute(Br):document.body.setAttribute(Br,e.toString())}},[])},hU=function(e){var t=e.noRelative,r=e.noImportant,o=e.gapMode,n=o===void 0?"margin":o;mU();var i=_.useMemo(function(){return dU(n)},[n]);return _.createElement(pU,{styles:fU(i,!t,n,r?"":"!important")})},zu=!1;if(typeof window<"u")try{var Qo=Object.defineProperty({},"passive",{get:function(){return zu=!0,!0}});window.addEventListener("test",Qo,Qo),window.removeEventListener("test",Qo,Qo)}catch{zu=!1}var Rr=zu?{passive:!1}:!1,gU=function(e){return e.tagName==="TEXTAREA"},dS=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!gU(e)&&r[t]==="visible")},vU=function(e){return dS(e,"overflowY")},yU=function(e){return dS(e,"overflowX")},Xf=function(e,t){var r=t.ownerDocument,o=t;do{typeof ShadowRoot<"u"&&o instanceof ShadowRoot&&(o=o.host);var n=pS(e,o);if(n){var i=fS(e,o),a=i[1],s=i[2];if(a>s)return!0}o=o.parentNode}while(o&&o!==r.body);return!1},bU=function(e){var t=e.scrollTop,r=e.scrollHeight,o=e.clientHeight;return[t,r,o]},_U=function(e){var t=e.scrollLeft,r=e.scrollWidth,o=e.clientWidth;return[t,r,o]},pS=function(e,t){return e==="v"?vU(t):yU(t)},fS=function(e,t){return e==="v"?bU(t):_U(t)},wU=function(e,t){return e==="h"&&t==="rtl"?-1:1},xU=function(e,t,r,o,n){var i=wU(e,window.getComputedStyle(t).direction),a=i*o,s=r.target,l=t.contains(s),u=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=fS(e,s),g=p[0],h=p[1],b=p[2],y=h-b-i*g;(g||y)&&pS(e,s)&&(d+=y,f+=g);var x=s.parentNode;s=x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE?x.host:x}while(!l&&s!==document.body||l&&(t.contains(s)||t===s));return(c&&Math.abs(d)<1||!c&&Math.abs(f)<1)&&(u=!0),u},Xo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},em=function(e){return[e.deltaX,e.deltaY]},tm=function(e){return e&&"current"in e?e.current:e},$U=function(e,t){return e[0]===t[0]&&e[1]===t[1]},SU=function(e){return`
|
|
134
|
-
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
135
|
-
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
136
|
-
`)},IU=0,zr=[];function kU(e){var t=_.useRef([]),r=_.useRef([0,0]),o=_.useRef(),n=_.useState(IU++)[0],i=_.useState(cS)[0],a=_.useRef(e);_.useEffect(function(){a.current=e},[e]),_.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(n));var h=WD([e.lockRef.current],(e.shards||[]).map(tm),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(n))}),function(){document.body.classList.remove("block-interactivity-".concat(n)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(n))})}}},[e.inert,e.lockRef.current,e.shards]);var s=_.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=Xo(h),x=r.current,$="deltaX"in h?h.deltaX:x[0]-y[0],v="deltaY"in h?h.deltaY:x[1]-y[1],k,N=h.target,I=Math.abs($)>Math.abs(v)?"h":"v";if("touches"in h&&I==="h"&&N.type==="range")return!1;var O=Xf(I,N);if(!O)return!0;if(O?k=I:(k=I==="v"?"h":"v",O=Xf(I,N)),!O)return!1;if(!o.current&&"changedTouches"in h&&($||v)&&(o.current=k),!k)return!0;var M=o.current||k;return xU(M,b,h,M==="h"?$:v)},[]),l=_.useCallback(function(h){var b=h;if(!(!zr.length||zr[zr.length-1]!==i)){var y="deltaY"in b?em(b):Xo(b),x=t.current.filter(function(k){return k.name===b.type&&(k.target===b.target||b.target===k.shadowParent)&&$U(k.delta,y)})[0];if(x&&x.should){b.cancelable&&b.preventDefault();return}if(!x){var $=(a.current.shards||[]).map(tm).filter(Boolean).filter(function(k){return k.contains(b.target)}),v=$.length>0?s(b,$[0]):!a.current.noIsolation;v&&b.cancelable&&b.preventDefault()}}},[]),u=_.useCallback(function(h,b,y,x){var $={name:h,delta:b,target:y,should:x,shadowParent:EU(y)};t.current.push($),setTimeout(function(){t.current=t.current.filter(function(v){return v!==$})},1)},[]),c=_.useCallback(function(h){r.current=Xo(h),o.current=void 0},[]),d=_.useCallback(function(h){u(h.type,em(h),h.target,s(h,e.lockRef.current))},[]),f=_.useCallback(function(h){u(h.type,Xo(h),h.target,s(h,e.lockRef.current))},[]);_.useEffect(function(){return zr.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Rr),document.addEventListener("touchmove",l,Rr),document.addEventListener("touchstart",c,Rr),function(){zr=zr.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,Rr),document.removeEventListener("touchmove",l,Rr),document.removeEventListener("touchstart",c,Rr)}},[]);var p=e.removeScrollBar,g=e.inert;return _.createElement(_.Fragment,null,g?_.createElement(i,{styles:SU(n)}):null,p?_.createElement(hU,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function EU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const TU=rU(lS,kU);var fd=_.forwardRef(function(e,t){return _.createElement(is,Pt({},e,{ref:t,sideCar:TU}))});fd.classNames=is.classNames;var OU=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Mr=new WeakMap,ei=new WeakMap,ti={},Hs=0,mS=function(e){return e&&(e.host||mS(e.parentNode))},NU=function(e,t){return t.map(function(r){if(e.contains(r))return r;var o=mS(r);return o&&e.contains(o)?o:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return!!r})},PU=function(e,t,r,o){var n=NU(t,Array.isArray(e)?e:[e]);ti[r]||(ti[r]=new WeakMap);var i=ti[r],a=[],s=new Set,l=new Set(n),u=function(d){!d||s.has(d)||(s.add(d),u(d.parentNode))};n.forEach(u);var c=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(s.has(f))c(f);else try{var p=f.getAttribute(o),g=p!==null&&p!=="false",h=(Mr.get(f)||0)+1,b=(i.get(f)||0)+1;Mr.set(f,h),i.set(f,b),a.push(f),h===1&&g&&ei.set(f,!0),b===1&&f.setAttribute(r,"true"),g||f.setAttribute(o,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return c(t),s.clear(),Hs++,function(){a.forEach(function(d){var f=Mr.get(d)-1,p=i.get(d)-1;Mr.set(d,f),i.set(d,p),f||(ei.has(d)||d.removeAttribute(o),ei.delete(d)),p||d.removeAttribute(r)}),Hs--,Hs||(Mr=new WeakMap,Mr=new WeakMap,ei=new WeakMap,ti={})}},hS=function(e,t,r){r===void 0&&(r="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),n=OU(e);return n?(o.push.apply(o,Array.from(n.querySelectorAll("[aria-live], script"))),PU(o,n,r,"aria-hidden")):function(){return null}},as="Dialog",[gS]=Po(as),[CU,kt]=gS(as),vS=e=>{const{__scopeDialog:t,children:r,open:o,defaultOpen:n,onOpenChange:i,modal:a=!0}=e,s=_.useRef(null),l=_.useRef(null),[u,c]=rs({prop:o,defaultProp:n??!1,onChange:i,caller:as});return m.jsx(CU,{scope:t,triggerRef:s,contentRef:l,contentId:qr(),titleId:qr(),descriptionId:qr(),open:u,onOpenChange:c,onOpenToggle:_.useCallback(()=>c(d=>!d),[c]),modal:a,children:r})};vS.displayName=as;var yS="DialogTrigger",bS=_.forwardRef((e,t)=>{const{__scopeDialog:r,...o}=e,n=kt(yS,r),i=Ge(t,n.triggerRef);return m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":gd(n.open),...o,ref:i,onClick:Oe(e.onClick,n.onOpenToggle)})});bS.displayName=yS;var md="DialogPortal",[jU,_S]=gS(md,{forceMount:void 0}),wS=e=>{const{__scopeDialog:t,forceMount:r,children:o,container:n}=e,i=kt(md,t);return m.jsx(jU,{scope:t,forceMount:r,children:_.Children.map(o,a=>m.jsx(Gt,{present:r||i.open,children:m.jsx(ts,{asChild:!0,container:n,children:a})}))})};wS.displayName=md;var Vi="DialogOverlay",xS=_.forwardRef((e,t)=>{const r=_S(Vi,e.__scopeDialog),{forceMount:o=r.forceMount,...n}=e,i=kt(Vi,e.__scopeDialog);return i.modal?m.jsx(Gt,{present:o||i.open,children:m.jsx(RU,{...n,ref:t})}):null});xS.displayName=Vi;var AU=Kc("DialogOverlay.RemoveScroll"),RU=_.forwardRef((e,t)=>{const{__scopeDialog:r,...o}=e,n=kt(Vi,r);return m.jsx(fd,{as:AU,allowPinchZoom:!0,shards:[n.contentRef],children:m.jsx(Ce.div,{"data-state":gd(n.open),...o,ref:t,style:{pointerEvents:"auto",...o.style}})})}),kr="DialogContent",$S=_.forwardRef((e,t)=>{const r=_S(kr,e.__scopeDialog),{forceMount:o=r.forceMount,...n}=e,i=kt(kr,e.__scopeDialog);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(zU,{...n,ref:t}):m.jsx(MU,{...n,ref:t})})});$S.displayName=kr;var zU=_.forwardRef((e,t)=>{const r=kt(kr,e.__scopeDialog),o=_.useRef(null),n=Ge(t,r.contentRef,o);return _.useEffect(()=>{const i=o.current;if(i)return hS(i)},[]),m.jsx(SS,{...e,ref:n,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,i=>{i.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,s=a.button===0&&a.ctrlKey===!0;(a.button===2||s)&&i.preventDefault()}),onFocusOutside:Oe(e.onFocusOutside,i=>i.preventDefault())})}),MU=_.forwardRef((e,t)=>{const r=kt(kr,e.__scopeDialog),o=_.useRef(!1),n=_.useRef(!1);return m.jsx(SS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||r.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,n.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(n.current=!0));const a=i.target;r.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&n.current&&i.preventDefault()}})}),SS=_.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:o,onOpenAutoFocus:n,onCloseAutoFocus:i,...a}=e,s=kt(kr,r),l=_.useRef(null),u=Ge(t,l);return aS(),m.jsxs(m.Fragment,{children:[m.jsx(pd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:n,onUnmountAutoFocus:i,children:m.jsx(Ka,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":gd(s.open),...a,ref:u,onDismiss:()=>s.onOpenChange(!1)})}),m.jsxs(m.Fragment,{children:[m.jsx(UU,{titleId:s.titleId}),m.jsx(ZU,{contentRef:l,descriptionId:s.descriptionId})]})]})}),hd="DialogTitle",IS=_.forwardRef((e,t)=>{const{__scopeDialog:r,...o}=e,n=kt(hd,r);return m.jsx(Ce.h2,{id:n.titleId,...o,ref:t})});IS.displayName=hd;var kS="DialogDescription",DU=_.forwardRef((e,t)=>{const{__scopeDialog:r,...o}=e,n=kt(kS,r);return m.jsx(Ce.p,{id:n.descriptionId,...o,ref:t})});DU.displayName=kS;var ES="DialogClose",TS=_.forwardRef((e,t)=>{const{__scopeDialog:r,...o}=e,n=kt(ES,r);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>n.onOpenChange(!1))})});TS.displayName=ES;function gd(e){return e?"open":"closed"}var OS="DialogTitleWarning",[K2,NS]=IM(OS,{contentName:kr,titleName:hd,docsSlug:"dialog"}),UU=({titleId:e})=>{const t=NS(OS),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
137
|
+
${t.map(n=>`- ${n.language}: ${n.prompt}`).join(`
|
|
138
|
+
`)}`}function d3(e){return e.map(t=>{const n=t.parts;if(!Array.isArray(n))return t;const i=n.map(r=>{const{callProviderMetadata:o,...a}=r;return a});return{...t,parts:i}})}const p3=({children:e,config:t})=>{const n=uj(t),i=s3({auth:t.api,projectSlug:t.projectSlug}),r=nk(),[o,a]=$.useState(t.model?.defaultModel??af[0]),[s,u]=$.useState(t.modal?.defaultExpanded??!1),[l,c]=$.useState(t.modal?.defaultOpen),d=t.plugins??_.recommended,f=c3(t.systemPrompt,d),{data:p,isLoading:g}=sj({auth:i,mcp:t.mcp,environment:t.environment??{}}),m=$.useRef({requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool});m.current={requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool};const y=$.useCallback(()=>({requestApproval:(...S)=>m.current.requestApproval(...S),isToolApproved:(...S)=>m.current.isToolApproved(...S),whitelistTool:(...S)=>m.current.whitelistTool(...S)}),[]);$.useEffect(()=>(t.tools?.toolsRequiringApproval?.length&&n2(y(),t.tools.toolsRequiringApproval),()=>{r2()}),[t.tools?.toolsRequiringApproval,y]);const v=$.useMemo(()=>({sendMessages:async({messages:S,abortSignal:b})=>{const A=!!t.languageModel;if(i.isLoading)throw new Error("Session is loading");const E=x.thread.getModelContext(),C=e2(t2(E?.tools??{})),P=A?null:S0({baseURL:n,apiKey:"unused, but must be set",headers:i.headers});t.languageModel&&console.log("Using custom language model",t.languageModel);const j={...p,..._B(C)},F=o2(j,t.tools?.toolsRequiringApproval,y()),D=t.languageModel?t.languageModel:P.chat(o);try{const V=d3(S),G=Q9(V);return G9({system:f,model:D,messages:G,tools:F,stopWhen:R$(10),experimental_transform:r3({delayInMs:15}),abortSignal:b,onError:({error:U})=>{console.error("Stream error in onError callback:",U)}}).toUIMessageStream()}catch(V){throw console.error("Error creating stream:",V),V}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t,t.languageModel,o,f,p,g,y,n,i.headers]),x=bB({transport:v});return h.jsx(tz,{runtime:x,children:h.jsxs(_.ElementsContext.Provider,{value:{config:t,setModel:a,model:o,isExpanded:s,setIsExpanded:u,isOpen:l??!1,setIsOpen:c,plugins:d},children:[e,h.jsx(SA,{tools:t.tools?.frontendTools??{}})]})})},f3=e=>{const t=new WN;return h.jsx(GN,{client:t,children:h.jsx(l3,{children:h.jsx(p3,{...e})})})};var h3=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"}),m3="VisuallyHidden",D$=w.forwardRef((e,t)=>h.jsx(We.span,{...e,ref:t,style:{...h3,...e.style}}));D$.displayName=m3;var g3=D$,[Ql]=Wo("Tooltip",[Fl]),Xl=Fl(),U$="TooltipProvider",v3=700,ed="tooltip.open",[y3,eh]=Ql(U$),L$=e=>{const{__scopeTooltip:t,delayDuration:n=v3,skipDelayDuration:i=300,disableHoverableContent:r=!1,children:o}=e,a=w.useRef(!0),s=w.useRef(!1),u=w.useRef(0);return w.useEffect(()=>{const l=u.current;return()=>window.clearTimeout(l)},[]),h.jsx(y3,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:w.useCallback(()=>{window.clearTimeout(u.current),a.current=!1},[]),onClose:w.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>a.current=!0,i)},[i]),isPointerInTransitRef:s,onPointerInTransitChange:w.useCallback(l=>{s.current=l},[]),disableHoverableContent:r,children:o})};L$.displayName=U$;var mo="Tooltip",[b3,na]=Ql(mo),F$=e=>{const{__scopeTooltip:t,children:n,open:i,defaultOpen:r,onOpenChange:o,disableHoverableContent:a,delayDuration:s}=e,u=eh(mo,e.__scopeTooltip),l=Xl(t),[c,d]=w.useState(null),f=Fr(),p=w.useRef(0),g=a??u.disableHoverableContent,m=s??u.delayDuration,y=w.useRef(!1),[v,x]=Zl({prop:i,defaultProp:r??!1,onChange:C=>{C?(u.onOpen(),document.dispatchEvent(new CustomEvent(ed))):u.onClose(),o?.(C)},caller:mo}),S=w.useMemo(()=>v?y.current?"delayed-open":"instant-open":"closed",[v]),b=w.useCallback(()=>{window.clearTimeout(p.current),p.current=0,y.current=!1,x(!0)},[x]),A=w.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x(!1)},[x]),E=w.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{y.current=!0,x(!0),p.current=0},m)},[m,x]);return w.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),h.jsx(hE,{...l,children:h.jsx(b3,{scope:t,contentId:f,open:v,stateAttribute:S,trigger:c,onTriggerChange:d,onTriggerEnter:w.useCallback(()=>{u.isOpenDelayedRef.current?E():b()},[u.isOpenDelayedRef,E,b]),onTriggerLeave:w.useCallback(()=>{g?A():(window.clearTimeout(p.current),p.current=0)},[A,g]),onOpen:b,onClose:A,disableHoverableContent:g,children:n})})};F$.displayName=mo;var td="TooltipTrigger",B$=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=na(td,n),o=eh(td,n),a=Xl(n),s=w.useRef(null),u=Ge(t,s,r.onTriggerChange),l=w.useRef(!1),c=w.useRef(!1),d=w.useCallback(()=>l.current=!1,[]);return w.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),h.jsx($f,{asChild:!0,...a,children:h.jsx(We.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...i,ref:u,onPointerMove:Re(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!o.isPointerInTransitRef.current&&(r.onTriggerEnter(),c.current=!0)}),onPointerLeave:Re(e.onPointerLeave,()=>{r.onTriggerLeave(),c.current=!1}),onPointerDown:Re(e.onPointerDown,()=>{r.open&&r.onClose(),l.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Re(e.onFocus,()=>{l.current||r.onOpen()}),onBlur:Re(e.onBlur,r.onClose),onClick:Re(e.onClick,r.onClose)})})});B$.displayName=td;var th="TooltipPortal",[_3,w3]=Ql(th,{forceMount:void 0}),Z$=e=>{const{__scopeTooltip:t,forceMount:n,children:i,container:r}=e,o=na(th,t);return h.jsx(_3,{scope:t,forceMount:n,children:h.jsx(Mn,{present:n||o.open,children:h.jsx(Bl,{asChild:!0,container:r,children:i})})})};Z$.displayName=th;var ui="TooltipContent",q$=w.forwardRef((e,t)=>{const n=w3(ui,e.__scopeTooltip),{forceMount:i=n.forceMount,side:r="top",...o}=e,a=na(ui,e.__scopeTooltip);return h.jsx(Mn,{present:i||a.open,children:a.disableHoverableContent?h.jsx(V$,{side:r,...o,ref:t}):h.jsx(x3,{side:r,...o,ref:t})})}),x3=w.forwardRef((e,t)=>{const n=na(ui,e.__scopeTooltip),i=eh(ui,e.__scopeTooltip),r=w.useRef(null),o=Ge(t,r),[a,s]=w.useState(null),{trigger:u,onClose:l}=n,c=r.current,{onPointerInTransitChange:d}=i,f=w.useCallback(()=>{s(null),d(!1)},[d]),p=w.useCallback((g,m)=>{const y=g.currentTarget,v={x:g.clientX,y:g.clientY},x=E3(v,y.getBoundingClientRect()),S=T3(v,x),b=$3(m.getBoundingClientRect()),A=A3([...S,...b]);s(A),d(!0)},[d]);return w.useEffect(()=>()=>f(),[f]),w.useEffect(()=>{if(u&&c){const g=y=>p(y,c),m=y=>p(y,u);return u.addEventListener("pointerleave",g),c.addEventListener("pointerleave",m),()=>{u.removeEventListener("pointerleave",g),c.removeEventListener("pointerleave",m)}}},[u,c,p,f]),w.useEffect(()=>{if(a){const g=m=>{const y=m.target,v={x:m.clientX,y:m.clientY},x=u?.contains(y)||c?.contains(y),S=!C3(v,a);x?f():S&&(f(),l())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[u,c,a,l,f]),h.jsx(V$,{...e,ref:o})}),[S3,I3]=Ql(mo,{isInside:!1}),k3=iD("TooltipContent"),V$=w.forwardRef((e,t)=>{const{__scopeTooltip:n,children:i,"aria-label":r,onEscapeKeyDown:o,onPointerDownOutside:a,...s}=e,u=na(ui,n),l=Xl(n),{onClose:c}=u;return w.useEffect(()=>(document.addEventListener(ed,c),()=>document.removeEventListener(ed,c)),[c]),w.useEffect(()=>{if(u.trigger){const d=f=>{f.target?.contains(u.trigger)&&c()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[u.trigger,c]),h.jsx(zl,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:h.jsxs(mE,{"data-state":u.stateAttribute,...l,...s,ref:t,style:{...s.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:[h.jsx(k3,{children:i}),h.jsx(S3,{scope:n,isInside:!0,children:h.jsx(g3,{id:u.contentId,role:"tooltip",children:r||i})})]})})});q$.displayName=ui;var H$="TooltipArrow",J$=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=Xl(n);return I3(H$,n).isInside?null:h.jsx(gE,{...r,...i,ref:t})});J$.displayName=H$;function E3(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 T3(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 $3(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 C3(e,t){const{x:n,y:i}=e;let r=!1;for(let o=0,a=t.length-1;o<t.length;a=o++){const s=t[o],u=t[a],l=s.x,c=s.y,d=u.x,f=u.y;c>i!=f>i&&n<(d-l)*(i-c)/(f-c)+l&&(r=!r)}return r}function A3(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),P3(t)}function P3(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],a=t[t.length-2];if((o.x-a.x)*(r.y-a.y)>=(o.y-a.y)*(r.x-a.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],a=n[n.length-2];if((o.x-a.x)*(r.y-a.y)>=(o.y-a.y)*(r.x-a.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 R3=L$,O3=F$,N3=B$,j3=Z$,M3=q$,z3=J$;function W$({delayDuration:e=0,...t}){return h.jsx(R3,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function nh({...e}){return h.jsx(W$,{children:h.jsx(O3,{"data-slot":"tooltip",...e})})}function rh({...e}){return h.jsx(N3,{"data-slot":"tooltip-trigger",...e})}function ih({className:e,sideOffset:t=0,children:n,...i}){return h.jsx(j3,{children:h.jsxs(M3,{"data-slot":"tooltip-content",sideOffset:t,className:_.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),...i,children:[n,h.jsx(z3,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}var eu="Dialog",[G$]=Wo(eu),[D3,an]=G$(eu),K$=e=>{const{__scopeDialog:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:a=!0}=e,s=w.useRef(null),u=w.useRef(null),[l,c]=Zl({prop:i,defaultProp:r??!1,onChange:o,caller:eu});return h.jsx(D3,{scope:t,triggerRef:s,contentRef:u,contentId:Fr(),titleId:Fr(),descriptionId:Fr(),open:l,onOpenChange:c,onOpenToggle:w.useCallback(()=>c(d=>!d),[c]),modal:a,children:n})};K$.displayName=eu;var Y$="DialogTrigger",Q$=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=an(Y$,n),o=Ge(t,r.triggerRef);return h.jsx(We.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":sh(r.open),...i,ref:o,onClick:Re(e.onClick,r.onOpenToggle)})});Q$.displayName=Y$;var oh="DialogPortal",[U3,X$]=G$(oh,{forceMount:void 0}),eC=e=>{const{__scopeDialog:t,forceMount:n,children:i,container:r}=e,o=an(oh,t);return h.jsx(U3,{scope:t,forceMount:n,children:w.Children.map(i,a=>h.jsx(Mn,{present:n||o.open,children:h.jsx(Bl,{asChild:!0,container:r,children:a})}))})};eC.displayName=oh;var Rs="DialogOverlay",tC=w.forwardRef((e,t)=>{const n=X$(Rs,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=an(Rs,e.__scopeDialog);return o.modal?h.jsx(Mn,{present:i||o.open,children:h.jsx(F3,{...r,ref:t})}):null});tC.displayName=Rs;var L3=vf("DialogOverlay.RemoveScroll"),F3=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=an(Rs,n);return h.jsx(Cf,{as:L3,allowPinchZoom:!0,shards:[r.contentRef],children:h.jsx(We.div,{"data-state":sh(r.open),...i,ref:t,style:{pointerEvents:"auto",...i.style}})})}),xr="DialogContent",nC=w.forwardRef((e,t)=>{const n=X$(xr,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=an(xr,e.__scopeDialog);return h.jsx(Mn,{present:i||o.open,children:o.modal?h.jsx(B3,{...r,ref:t}):h.jsx(Z3,{...r,ref:t})})});nC.displayName=xr;var B3=w.forwardRef((e,t)=>{const n=an(xr,e.__scopeDialog),i=w.useRef(null),r=Ge(t,n.contentRef,i);return w.useEffect(()=>{const o=i.current;if(o)return yE(o)},[]),h.jsx(rC,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Re(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Re(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,s=a.button===0&&a.ctrlKey===!0;(a.button===2||s)&&o.preventDefault()}),onFocusOutside:Re(e.onFocusOutside,o=>o.preventDefault())})}),Z3=w.forwardRef((e,t)=>{const n=an(xr,e.__scopeDialog),i=w.useRef(!1),r=w.useRef(!1);return h.jsx(rC,{...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 a=o.target;n.triggerRef.current?.contains(a)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),rC=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,...a}=e,s=an(xr,n),u=w.useRef(null),l=Ge(t,u);return Vk(),h.jsxs(h.Fragment,{children:[h.jsx(yf,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:h.jsx(zl,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":sh(s.open),...a,ref:l,onDismiss:()=>s.onOpenChange(!1)})}),h.jsxs(h.Fragment,{children:[h.jsx(V3,{titleId:s.titleId}),h.jsx(J3,{contentRef:u,descriptionId:s.descriptionId})]})]})}),ah="DialogTitle",iC=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=an(ah,n);return h.jsx(We.h2,{id:r.titleId,...i,ref:t})});iC.displayName=ah;var oC="DialogDescription",q3=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=an(oC,n);return h.jsx(We.p,{id:r.descriptionId,...i,ref:t})});q3.displayName=oC;var aC="DialogClose",sC=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=an(aC,n);return h.jsx(We.button,{type:"button",...i,ref:t,onClick:Re(e.onClick,()=>r.onOpenChange(!1))})});sC.displayName=aC;function sh(e){return e?"open":"closed"}var lC="DialogTitleWarning",[bK,uC]=tD(lC,{contentName:xr,titleName:ah,docsSlug:"dialog"}),V3=({titleId:e})=>{const t=uC(lC),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
137
139
|
|
|
138
140
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
139
141
|
|
|
140
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return _.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},LU="DialogDescriptionWarning",ZU=({contentRef:e,descriptionId:t})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${NS(LU).contentName}}.`;return _.useEffect(()=>{const n=e.current?.getAttribute("aria-describedby");t&&n&&(document.getElementById(t)||console.warn(o))},[o,e,t]),null},FU=vS,qU=bS,VU=wS,BU=xS,JU=$S,WU=IS,HU=TS;function GU({...e}){return m.jsx(FU,{"data-slot":"dialog",...e})}function KU({...e}){return m.jsx(qU,{"data-slot":"dialog-trigger",...e})}function YU({...e}){return m.jsx(VU,{"data-slot":"dialog-portal",...e})}function QU({className:e,...t}){return m.jsx(BU,{"data-slot":"dialog-overlay",className:T.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 XU({className:e,children:t,showCloseButton:r=!0,...o}){return m.jsxs(YU,{"data-slot":"dialog-portal",children:[m.jsx(QU,{}),m.jsxs(JU,{"data-slot":"dialog-content",className:T.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),...o,children:[t,r&&m.jsxs(HU,{"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:[m.jsx(Eo,{}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function e6({className:e,...t}){return m.jsx(WU,{"data-slot":"dialog-title",className:T.cn("text-lg leading-none font-semibold",e),...t})}function t6(e,t=[]){let r=[];function o(i,a){const s=_.createContext(a);s.displayName=i+"Context";const l=r.length;r=[...r,a];const u=d=>{const{scope:f,children:p,...g}=d,h=f?.[e]?.[l]||s,b=_.useMemo(()=>g,Object.values(g));return m.jsx(h.Provider,{value:b,children:p})};u.displayName=i+"Provider";function c(d,f){const p=f?.[e]?.[l]||s,g=_.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,c]}const n=()=>{const i=r.map(a=>_.createContext(a));return function(s){const l=s?.[e]||i;return _.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return n.scopeName=e,[o,r6(n,...t)]}function r6(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const o=e.map(n=>({useScope:n(),scopeName:n.scopeName}));return function(i){const a=o.reduce((s,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...s,...d}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}var n6=Symbol.for("react.lazy"),Bi=_[" use ".trim().toString()];function o6(e){return typeof e=="object"&&e!==null&&"then"in e}function PS(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===n6&&"_payload"in e&&o6(e._payload)}function CS(e){const t=a6(e),r=_.forwardRef((o,n)=>{let{children:i,...a}=o;PS(i)&&typeof Bi=="function"&&(i=Bi(i._payload));const s=_.Children.toArray(i),l=s.find(l6);if(l){const u=l.props.children,c=s.map(d=>d===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:d);return m.jsx(t,{...a,ref:n,children:_.isValidElement(u)?_.cloneElement(u,void 0,c):null})}return m.jsx(t,{...a,ref:n,children:i})});return r.displayName=`${e}.Slot`,r}var i6=CS("Slot");function a6(e){const t=_.forwardRef((r,o)=>{let{children:n,...i}=r;if(PS(n)&&typeof Bi=="function"&&(n=Bi(n._payload)),_.isValidElement(n)){const a=d6(n),s=c6(i,n.props);return n.type!==_.Fragment&&(s.ref=o?Gc(o,a):a),_.cloneElement(n,s)}return _.Children.count(n)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var jS=Symbol("radix.slottable");function s6(e){const t=({children:r})=>m.jsx(m.Fragment,{children:r});return t.displayName=`${e}.Slottable`,t.__radixId=jS,t}var u6=s6("Slottable");function l6(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===jS}function c6(e,t){const r={...t};for(const o in t){const n=e[o],i=t[o];/^on[A-Z]/.test(o)?n&&i?r[o]=(...s)=>{const l=i(...s);return n(...s),l}:n&&(r[o]=n):o==="style"?r[o]={...n,...i}:o==="className"&&(r[o]=[n,i].filter(Boolean).join(" "))}return{...e,...r}}function d6(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var p6=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],vd=p6.reduce((e,t)=>{const r=CS(`Primitive.${t}`),o=_.forwardRef((n,i)=>{const{asChild:a,...s}=n,l=a?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m.jsx(l,{...s,ref:i})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function f6(){return xj.useSyncExternalStore(m6,()=>!0,()=>!1)}function m6(){return()=>{}}var yd="Avatar",[h6]=t6(yd),[g6,AS]=h6(yd),RS=_.forwardRef((e,t)=>{const{__scopeAvatar:r,...o}=e,[n,i]=_.useState("idle");return m.jsx(g6,{scope:r,imageLoadingStatus:n,onImageLoadingStatusChange:i,children:m.jsx(vd.span,{...o,ref:t})})});RS.displayName=yd;var zS="AvatarImage",MS=_.forwardRef((e,t)=>{const{__scopeAvatar:r,src:o,onLoadingStatusChange:n=()=>{},...i}=e,a=AS(zS,r),s=v6(o,i),l=Sr(u=>{n(u),a.onImageLoadingStatusChange(u)});return lt(()=>{s!=="idle"&&l(s)},[s,l]),s==="loaded"?m.jsx(vd.img,{...i,ref:t,src:o}):null});MS.displayName=zS;var DS="AvatarFallback",US=_.forwardRef((e,t)=>{const{__scopeAvatar:r,delayMs:o,...n}=e,i=AS(DS,r),[a,s]=_.useState(o===void 0);return _.useEffect(()=>{if(o!==void 0){const l=window.setTimeout(()=>s(!0),o);return()=>window.clearTimeout(l)}},[o]),a&&i.imageLoadingStatus!=="loaded"?m.jsx(vd.span,{...n,ref:t}):null});US.displayName=DS;function rm(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function v6(e,{referrerPolicy:t,crossOrigin:r}){const o=f6(),n=_.useRef(null),i=o?(n.current||(n.current=new window.Image),n.current):null,[a,s]=_.useState(()=>rm(i,e));return lt(()=>{s(rm(i,e))},[i,e]),lt(()=>{const l=d=>()=>{s(d)};if(!i)return;const u=l("loaded"),c=l("error");return i.addEventListener("load",u),i.addEventListener("error",c),t&&(i.referrerPolicy=t),typeof r=="string"&&(i.crossOrigin=r),()=>{i.removeEventListener("load",u),i.removeEventListener("error",c)}},[i,r,t]),a}var y6=RS,b6=MS,_6=US;function w6({className:e,...t}){return m.jsx(y6,{"data-slot":"avatar",className:T.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function x6({className:e,...t}){return m.jsx(b6,{"data-slot":"avatar-image",className:T.cn("aspect-square size-full",e),...t})}function $6({className:e,...t}){return m.jsx(_6,{"data-slot":"avatar-fallback",className:T.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const nm=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,om=T.clsx,LS=(e,t)=>r=>{var o;if(t?.variants==null)return om(e,r?.class,r?.className);const{variants:n,defaultVariants:i}=t,a=Object.keys(n).map(u=>{const c=r?.[u],d=i?.[u];if(c===null)return null;const f=nm(c)||nm(d);return n[u][f]}),s=r&&Object.entries(r).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((u,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(g=>{let[h,b]=g;return Array.isArray(b)?b.includes({...i,...s}[h]):{...i,...s}[h]===b})?[...u,d,f]:u},[]);return om(e,a,l,r?.class,r?.className)},S6=LS("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"}}),$t=_.forwardRef(({className:e,variant:t,size:r,asChild:o=!1,...n},i)=>{const a=o?i6:"button";return m.jsx(a,{"data-slot":"button",className:T.cn(S6({variant:t,size:r,className:e})),ref:i,...n})});$t.displayName="Button";const ct=z.forwardRef(({children:e,tooltip:t,side:r="bottom",align:o="center",className:n,...i},a)=>m.jsxs(ld,{children:[m.jsx(cd,{asChild:!0,children:m.jsxs($t,{variant:"ghost",size:"icon",...i,className:T.cn("aui-button-icon size-6 p-1",n),ref:a,children:[m.jsx(u6,{children:e}),m.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),m.jsx(dd,{side:r,align:o,children:t})]}));ct.displayName="TooltipIconButton";const I6=e=>{const[t,r]=z.useState(void 0);return z.useEffect(()=>{if(!e){r(void 0);return}const o=URL.createObjectURL(e);return r(o),()=>{URL.revokeObjectURL(o)}},[e]),t},ZS=()=>{const{file:e,src:t}=L.useAssistantState(_0.useShallow(({attachment:r})=>{if(r.type!=="image")return{};if(r.file)return{file:r.file};const o=r.content?.filter(n=>n.type==="image")[0]?.image;return o?{src:o}:{}}));return I6(e)??t},k6=({src:e})=>{const[t,r]=z.useState(!1);return m.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:()=>r(!0)})},E6=({children:e})=>{const t=ZS();return t?m.jsxs(GU,{children:[m.jsx(KU,{className:"aui-attachment-preview-trigger hover:bg-accent/50 cursor-pointer transition-colors",asChild:!0,children:e}),m.jsxs(XU,{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:[m.jsx(e6,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),m.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:m.jsx(k6,{src:t})})]})]}):e},T6=()=>{const e=L.useAssistantState(({attachment:r})=>r.type==="image"),t=ZS();return m.jsxs(w6,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[m.jsx(x6,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),m.jsx($6,{delayMs:e?200:0,children:m.jsx(ON,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},FS=()=>{const t=L.useAssistantApi().attachment.source==="composer",r=L.useAssistantState(({attachment:n})=>n.type==="image"),o=L.useAssistantState(({attachment:n})=>{const i=n.type;switch(i){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const a=i;throw new Error(`Unknown attachment type: ${a}`)}}});return m.jsxs(ld,{children:[m.jsxs(L.AttachmentPrimitive.Root,{className:T.cn("aui-attachment-root relative",r&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[m.jsx(E6,{children:m.jsx(cd,{asChild:!0,children:m.jsx("div",{className:T.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":`${o} attachment`,children:m.jsx(T6,{})})})}),t&&m.jsx(O6,{})]}),m.jsx(dd,{side:"top",children:m.jsx(L.AttachmentPrimitive.Name,{})})]})},O6=()=>m.jsx(L.AttachmentPrimitive.Remove,{asChild:!0,children:m.jsx(ct,{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:m.jsx(Eo,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),N6=()=>m.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:m.jsx(L.MessagePrimitive.Attachments,{components:{Attachment:FS}})}),P6=()=>m.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:m.jsx(L.ComposerPrimitive.Attachments,{components:{Attachment:FS}})}),C6=()=>m.jsx(L.ComposerPrimitive.AddAttachment,{asChild:!0,children:m.jsx(ct,{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:m.jsx(VN,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})});function j6(e){return z.useMemo(()=>e.reduce((t,r)=>(t?.[r.language]&&!r.overrideExisting||(t={...t,[r.language]:{CodeHeader:r.Header??(()=>null),SyntaxHighlighter:r.Component??void 0}}),t),{}),[e])}const A6=()=>{const{plugins:e}=T.useElements(),t=j6(e);return m.jsx(Gs.MarkdownTextPrimitive,{remarkPlugins:[w0],className:"aui-md",components:M6,componentsByLanguage:t})},qS=z.memo(A6),R6=({language:e,code:t})=>{const o=L.useAssistantState(({message:s})=>s).status?.type==="complete",{isCopied:n,copyToClipboard:i}=z6(),a=()=>{!t||n||i(t)};return o?m.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:[m.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),m.jsxs(ct,{tooltip:"Copy",onClick:a,children:[!n&&m.jsx(Pc,{}),n&&m.jsx(nr,{})]})]}):null},z6=({copiedDuration:e=3e3}={})=>{const[t,r]=z.useState(!1);return{isCopied:t,copyToClipboard:n=>{n&&navigator.clipboard.writeText(n).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},M6=Gs.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>m.jsx("h1",{className:T.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>m.jsx("h2",{className:T.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})=>m.jsx("h3",{className:T.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})=>m.jsx("h4",{className:T.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})=>m.jsx("h5",{className:T.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>m.jsx("h6",{className:T.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>m.jsx("p",{className:T.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>m.jsx("a",{className:T.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>m.jsx("blockquote",{className:T.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>m.jsx("ul",{className:T.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>m.jsx("ol",{className:T.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>m.jsx("hr",{className:T.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>m.jsx("table",{className:T.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>m.jsx("th",{className:T.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})=>m.jsx("td",{className:T.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})=>m.jsx("tr",{className:T.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})=>m.jsx("sup",{className:T.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>m.jsx("pre",{className:T.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,...r}){const o=Gs.useIsMarkdownCodeBlock();return m.jsx("code",{className:T.cn(!o&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...r})},CodeHeader:R6});var ss="Collapsible",[D6]=Po(ss),[U6,bd]=D6(ss),VS=_.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:o,defaultOpen:n,disabled:i,onOpenChange:a,...s}=e,[l,u]=rs({prop:o,defaultProp:n??!1,onChange:a,caller:ss});return m.jsx(U6,{scope:r,disabled:i,contentId:qr(),open:l,onOpenToggle:_.useCallback(()=>u(c=>!c),[u]),children:m.jsx(Ce.div,{"data-state":wd(l),"data-disabled":i?"":void 0,...s,ref:t})})});VS.displayName=ss;var BS="CollapsibleTrigger",JS=_.forwardRef((e,t)=>{const{__scopeCollapsible:r,...o}=e,n=bd(BS,r);return m.jsx(Ce.button,{type:"button","aria-controls":n.contentId,"aria-expanded":n.open||!1,"data-state":wd(n.open),"data-disabled":n.disabled?"":void 0,disabled:n.disabled,...o,ref:t,onClick:Oe(e.onClick,n.onOpenToggle)})});JS.displayName=BS;var _d="CollapsibleContent",WS=_.forwardRef((e,t)=>{const{forceMount:r,...o}=e,n=bd(_d,e.__scopeCollapsible);return m.jsx(Gt,{present:r||n.open,children:({present:i})=>m.jsx(L6,{...o,ref:t,present:i})})});WS.displayName=_d;var L6=_.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:o,children:n,...i}=e,a=bd(_d,r),[s,l]=_.useState(o),u=_.useRef(null),c=Ge(t,u),d=_.useRef(0),f=d.current,p=_.useRef(0),g=p.current,h=a.open||s,b=_.useRef(h),y=_.useRef(void 0);return _.useEffect(()=>{const x=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(x)},[]),lt(()=>{const x=u.current;if(x){y.current=y.current||{transitionDuration:x.style.transitionDuration,animationName:x.style.animationName},x.style.transitionDuration="0s",x.style.animationName="none";const $=x.getBoundingClientRect();d.current=$.height,p.current=$.width,b.current||(x.style.transitionDuration=y.current.transitionDuration,x.style.animationName=y.current.animationName),l(o)}},[a.open,o]),m.jsx(Ce.div,{"data-state":wd(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!h,...i,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&n})});function wd(e){return e?"open":"closed"}var Z6=VS;function F6({...e}){return m.jsx(Z6,{"data-slot":"collapsible",...e})}function q6({...e}){return m.jsx(JS,{"data-slot":"collapsible-trigger",...e})}function V6({...e}){return m.jsx(WS,{"data-slot":"collapsible-content",...e})}const im=200,HS=({className:e,children:t})=>{const r=z.useRef(null),[o,n]=z.useState(!1),i=L.useScrollLock(r,im),a=z.useCallback(s=>{s||i(),n(s)},[i]);return m.jsx(F6,{ref:r,open:o,onOpenChange:a,className:T.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${im}ms`},children:t})};HS.displayName="ReasoningRoot";const B6=({className:e})=>m.jsx("div",{className:T.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)}),J6=({active:e,className:t})=>m.jsxs(q6,{className:T.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:[m.jsx(wN,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),m.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[m.jsx("span",{children:"Reasoning"}),e?m.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),m.jsx(Ti,{className:T.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")})]}),GS=({className:e,children:t,"aria-busy":r})=>m.jsxs(V6,{className:T.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":r,children:[t,m.jsx(B6,{})]});GS.displayName="ReasoningContent";const KS=({className:e,children:t})=>m.jsx("div",{className:T.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});KS.displayName="ReasoningText";const W6=()=>m.jsx(qS,{}),H6=({children:e,startIndex:t,endIndex:r})=>{const o=L.useAssistantState(({message:n})=>{if(n.status?.type!=="running")return!1;const i=n.parts.length-1;return i<0||n.parts[i]?.type!=="reasoning"?!1:i>=t&&i<=r});return m.jsxs(HS,{children:[m.jsx(J6,{active:o}),m.jsx(GS,{"aria-busy":o,children:m.jsx(KS,{children:e})})]})},YS=z.memo(W6);YS.displayName="Reasoning";const QS=z.memo(H6);QS.displayName="ReasoningGroup";var us="Popover",[XS]=Po(us,[es]),Ao=es(),[G6,pr]=XS(us),e0=e=>{const{__scopePopover:t,children:r,open:o,defaultOpen:n,onOpenChange:i,modal:a=!1}=e,s=Ao(t),l=_.useRef(null),[u,c]=_.useState(!1),[d,f]=rs({prop:o,defaultProp:n??!1,onChange:i,caller:us});return m.jsx(B$,{...s,children:m.jsx(G6,{scope:t,contentId:qr(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:_.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:u,onCustomAnchorAdd:_.useCallback(()=>c(!0),[]),onCustomAnchorRemove:_.useCallback(()=>c(!1),[]),modal:a,children:r})})};e0.displayName=us;var t0="PopoverAnchor",K6=_.forwardRef((e,t)=>{const{__scopePopover:r,...o}=e,n=pr(t0,r),i=Ao(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=n;return _.useEffect(()=>(a(),()=>s()),[a,s]),m.jsx(ad,{...i,...o,ref:t})});K6.displayName=t0;var r0="PopoverTrigger",n0=_.forwardRef((e,t)=>{const{__scopePopover:r,...o}=e,n=pr(r0,r),i=Ao(r),a=Ge(t,n.triggerRef),s=m.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":u0(n.open),...o,ref:a,onClick:Oe(e.onClick,n.onOpenToggle)});return n.hasCustomAnchor?s:m.jsx(ad,{asChild:!0,...i,children:s})});n0.displayName=r0;var xd="PopoverPortal",[Y6,Q6]=XS(xd,{forceMount:void 0}),o0=e=>{const{__scopePopover:t,forceMount:r,children:o,container:n}=e,i=pr(xd,t);return m.jsx(Y6,{scope:t,forceMount:r,children:m.jsx(Gt,{present:r||i.open,children:m.jsx(ts,{asChild:!0,container:n,children:o})})})};o0.displayName=xd;var an="PopoverContent",i0=_.forwardRef((e,t)=>{const r=Q6(an,e.__scopePopover),{forceMount:o=r.forceMount,...n}=e,i=pr(an,e.__scopePopover);return m.jsx(Gt,{present:o||i.open,children:i.modal?m.jsx(e2,{...n,ref:t}):m.jsx(t2,{...n,ref:t})})});i0.displayName=an;var X6=Kc("PopoverContent.RemoveScroll"),e2=_.forwardRef((e,t)=>{const r=pr(an,e.__scopePopover),o=_.useRef(null),n=Ge(t,o),i=_.useRef(!1);return _.useEffect(()=>{const a=o.current;if(a)return hS(a)},[]),m.jsx(fd,{as:X6,allowPinchZoom:!0,children:m.jsx(a0,{...e,ref:n,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oe(e.onCloseAutoFocus,a=>{a.preventDefault(),i.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Oe(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0,u=s.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Oe(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),t2=_.forwardRef((e,t)=>{const r=pr(an,e.__scopePopover),o=_.useRef(!1),n=_.useRef(!1);return m.jsx(a0,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(o.current||r.triggerRef.current?.focus(),i.preventDefault()),o.current=!1,n.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(o.current=!0,i.detail.originalEvent.type==="pointerdown"&&(n.current=!0));const a=i.target;r.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&n.current&&i.preventDefault()}})}),a0=_.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:o,onOpenAutoFocus:n,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:c,...d}=e,f=pr(an,r),p=Ao(r);return aS(),m.jsx(pd,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:n,onUnmountAutoFocus:i,children:m.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:c,onEscapeKeyDown:s,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:m.jsx(J$,{"data-state":u0(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)"}})})})}),s0="PopoverClose",r2=_.forwardRef((e,t)=>{const{__scopePopover:r,...o}=e,n=pr(s0,r);return m.jsx(Ce.button,{type:"button",...o,ref:t,onClick:Oe(e.onClick,()=>n.onOpenChange(!1))})});r2.displayName=s0;var n2="PopoverArrow",o2=_.forwardRef((e,t)=>{const{__scopePopover:r,...o}=e,n=Ao(r);return m.jsx(W$,{...n,...o,ref:t})});o2.displayName=n2;function u0(e){return e?"open":"closed"}var i2=e0,a2=n0,s2=o0,u2=i0;function l0({...e}){return m.jsx(i2,{"data-slot":"popover",...e})}function c0({...e}){return m.jsx(a2,{"data-slot":"popover-trigger",...e})}function d0({className:e,align:t="center",sideOffset:r=4,...o}){return m.jsx(s2,{children:m.jsx(u2,{"data-slot":"popover-content",align:t,sideOffset:r,className:T.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),...o})})}const l2=LS("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 c2(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 d2(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function p2(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function p0({status:e}){return m.jsxs("div",{className:T.cn(l2({status:e})),children:[e==="pending"&&null,e==="running"&&m.jsx(Oi,{className:"size-4 animate-spin"}),e==="complete"&&m.jsx(nr,{className:"size-4"}),e==="error"&&m.jsx(Eo,{className:"size-4"}),e==="approval"&&m.jsx(Oi,{className:"text-muted-foreground size-4 animate-spin"})]})}function f2({content:e}){const[t,r]=z.useState(!1),o=async n=>{n.stopPropagation(),await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)};return m.jsx("button",{onClick:o,className:"text-muted-foreground hover:bg-accent hover:text-foreground rounded p-1 transition-colors","aria-label":"Copy to clipboard",children:t?m.jsx(nr,{className:"size-4"}):m.jsx(Pc,{className:"size-4"})})}function f0({text:e,language:t,className:r}){const[o,n]=z.useState(null);return z.useEffect(()=>{t&&x0.codeToHtml(e,{lang:t,theme:"github-dark-default",rootStyle:"background-color: transparent;",transformers:[{pre(i){i.properties.class="w-full py-3 px-4 max-h-[300px] overflow-y-auto whitespace-pre-wrap text-left text-sm"}}]}).then(n)},[e,t]),o?m.jsx("div",{className:T.cn("w-full bg-slate-800/90",r),dangerouslySetInnerHTML:{__html:o}}):m.jsx("pre",{className:T.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",r),children:e})}function m2({data:e}){const t=`data:image/png;base64,${e}`;return m.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
142
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return w.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},H3="DialogDescriptionWarning",J3=({contentRef:e,descriptionId:t})=>{const i=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${uC(H3).contentName}}.`;return w.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(i))},[i,e,t]),null},W3=K$,G3=Q$,K3=eC,Y3=tC,Q3=nC,X3=iC,eH=sC;function tH({...e}){return h.jsx(W3,{"data-slot":"dialog",...e})}function nH({...e}){return h.jsx(G3,{"data-slot":"dialog-trigger",...e})}function rH({...e}){return h.jsx(K3,{"data-slot":"dialog-portal",...e})}function iH({className:e,...t}){return h.jsx(Y3,{"data-slot":"dialog-overlay",className:_.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 oH({className:e,children:t,showCloseButton:n=!0,...i}){return h.jsxs(rH,{"data-slot":"dialog-portal",children:[h.jsx(iH,{}),h.jsxs(Q3,{"data-slot":"dialog-content",className:_.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&&h.jsxs(eH,{"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:[h.jsx(Qo,{}),h.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function aH({className:e,...t}){return h.jsx(X3,{"data-slot":"dialog-title",className:_.cn("text-lg leading-none font-semibold",e),...t})}function sH(e,t=[]){let n=[];function i(o,a){const s=w.createContext(a);s.displayName=o+"Context";const u=n.length;n=[...n,a];const l=d=>{const{scope:f,children:p,...g}=d,m=f?.[e]?.[u]||s,y=w.useMemo(()=>g,Object.values(g));return h.jsx(m.Provider,{value:y,children:p})};l.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[u]||s,g=w.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[l,c]}const r=()=>{const o=n.map(a=>w.createContext(a));return function(s){const u=s?.[e]||o;return w.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return r.scopeName=e,[i,lH(r,...t)]}function lH(...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 a=i.reduce((s,{useScope:u,scopeName:l})=>{const d=u(o)[`__scope${l}`];return{...s,...d}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function uH(){return dB.useSyncExternalStore(cH,()=>!0,()=>!1)}function cH(){return()=>{}}var lh="Avatar",[dH]=sH(lh),[pH,cC]=dH(lh),dC=w.forwardRef((e,t)=>{const{__scopeAvatar:n,...i}=e,[r,o]=w.useState("idle");return h.jsx(pH,{scope:n,imageLoadingStatus:r,onImageLoadingStatusChange:o,children:h.jsx(ct.span,{...i,ref:t})})});dC.displayName=lh;var pC="AvatarImage",fC=w.forwardRef((e,t)=>{const{__scopeAvatar:n,src:i,onLoadingStatusChange:r=()=>{},...o}=e,a=cC(pC,n),s=fH(i,o),u=Et(l=>{r(l),a.onImageLoadingStatusChange(l)});return Lt(()=>{s!=="idle"&&u(s)},[s,u]),s==="loaded"?h.jsx(ct.img,{...o,ref:t,src:i}):null});fC.displayName=pC;var hC="AvatarFallback",mC=w.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:i,...r}=e,o=cC(hC,n),[a,s]=w.useState(i===void 0);return w.useEffect(()=>{if(i!==void 0){const u=window.setTimeout(()=>s(!0),i);return()=>window.clearTimeout(u)}},[i]),a&&o.imageLoadingStatus!=="loaded"?h.jsx(ct.span,{...r,ref:t}):null});mC.displayName=hC;function kv(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function fH(e,{referrerPolicy:t,crossOrigin:n}){const i=uH(),r=w.useRef(null),o=i?(r.current||(r.current=new window.Image),r.current):null,[a,s]=w.useState(()=>kv(o,e));return Lt(()=>{s(kv(o,e))},[o,e]),Lt(()=>{const u=d=>()=>{s(d)};if(!o)return;const l=u("loaded"),c=u("error");return o.addEventListener("load",l),o.addEventListener("error",c),t&&(o.referrerPolicy=t),typeof n=="string"&&(o.crossOrigin=n),()=>{o.removeEventListener("load",l),o.removeEventListener("error",c)}},[o,n,t]),a}var hH=dC,mH=fC,gH=mC;function vH({className:e,...t}){return h.jsx(hH,{"data-slot":"avatar",className:_.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function yH({className:e,...t}){return h.jsx(mH,{"data-slot":"avatar-image",className:_.cn("aspect-square size-full",e),...t})}function bH({className:e,...t}){return h.jsx(gH,{"data-slot":"avatar-fallback",className:_.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const Ev=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Tv=_.clsx,gC=(e,t)=>n=>{var i;if(t?.variants==null)return Tv(e,n?.class,n?.className);const{variants:r,defaultVariants:o}=t,a=Object.keys(r).map(l=>{const c=n?.[l],d=o?.[l];if(c===null)return null;const f=Ev(c)||Ev(d);return r[l][f]}),s=n&&Object.entries(n).reduce((l,c)=>{let[d,f]=c;return f===void 0||(l[d]=f),l},{}),u=t==null||(i=t.compoundVariants)===null||i===void 0?void 0:i.reduce((l,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(g=>{let[m,y]=g;return Array.isArray(y)?y.includes({...o,...s}[m]):{...o,...s}[m]===y})?[...l,d,f]:l},[]);return Tv(e,a,u,n?.class,n?.className)},_H=gC("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=w.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...r},o)=>{const a=i?mf:"button";return h.jsx(a,{"data-slot":"button",className:_.cn(_H({variant:t,size:n,className:e})),ref:o,...r})});tn.displayName="Button";const Ft=$.forwardRef(({children:e,tooltip:t,side:n="bottom",align:i="center",className:r,...o},a)=>h.jsxs(nh,{children:[h.jsx(rh,{asChild:!0,children:h.jsxs(tn,{variant:"ghost",size:"icon",...o,className:_.cn("aui-button-icon size-6 p-1",r),ref:a,children:[h.jsx(qz,{children:e}),h.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),h.jsx(ih,{side:n,align:i,children:t})]}));Ft.displayName="TooltipIconButton";const wH=e=>{const[t,n]=$.useState(void 0);return $.useEffect(()=>{if(!e){n(void 0);return}const i=URL.createObjectURL(e);return n(i),()=>{URL.revokeObjectURL(i)}},[e]),t},vC=()=>{const{file:e,src:t}=_.useAssistantState(gy.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 wH(e)??t},xH=({src:e})=>{const[t,n]=$.useState(!1);return h.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)})},SH=({children:e})=>{const t=vC();return t?h.jsxs(tH,{children:[h.jsx(nH,{className:"aui-attachment-preview-trigger hover:bg-accent/50 cursor-pointer transition-colors",asChild:!0,children:e}),h.jsxs(oH,{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:[h.jsx(aH,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),h.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:h.jsx(xH,{src:t})})]})]}):e},IH=()=>{const e=_.useAssistantState(({attachment:n})=>n.type==="image"),t=vC();return h.jsxs(vH,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[h.jsx(yH,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),h.jsx(bH,{delayMs:e?200:0,children:h.jsx(b2,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},yC=()=>{const t=_.useAssistantApi().attachment.source==="composer",n=_.useAssistantState(({attachment:r})=>r.type==="image"),i=_.useAssistantState(({attachment:r})=>{const o=r.type;switch(o){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const a=o;throw new Error(`Unknown attachment type: ${a}`)}}});return h.jsxs(nh,{children:[h.jsxs(ME,{className:_.cn("aui-attachment-root relative",n&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[h.jsx(SH,{children:h.jsx(rh,{asChild:!0,children:h.jsx("div",{className:_.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:h.jsx(IH,{})})})}),t&&h.jsx(kH,{})]}),h.jsx(ih,{side:"top",children:h.jsx(zE,{})})]})},kH=()=>h.jsx(QU,{asChild:!0,children:h.jsx(Ft,{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:h.jsx(Qo,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),EH=()=>h.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:h.jsx(JE,{components:{Attachment:yC}})}),TH=()=>h.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:h.jsx(tT,{components:{Attachment:yC}})}),$H=()=>h.jsx(DL,{asChild:!0,children:h.jsx(Ft,{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:h.jsx(N2,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})});function CH(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const AH=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,PH=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,RH={};function $v(e,t){return(RH.jsx?PH:AH).test(e)}const OH=/[ \t\n\f\r]/g;function NH(e){return typeof e=="object"?e.type==="text"?Cv(e.value):!1:Cv(e)}function Cv(e){return e.replace(OH,"")===""}class ra{constructor(t,n,i){this.normal=n,this.property=t,i&&(this.space=i)}}ra.prototype.normal={};ra.prototype.property={};ra.prototype.space=void 0;function bC(e,t){const n={},i={};for(const r of e)Object.assign(n,r.property),Object.assign(i,r.normal);return new ra(n,i,t)}function nd(e){return e.toLowerCase()}class gt{constructor(t,n){this.attribute=n,this.property=t}}gt.prototype.attribute="";gt.prototype.booleanish=!1;gt.prototype.boolean=!1;gt.prototype.commaOrSpaceSeparated=!1;gt.prototype.commaSeparated=!1;gt.prototype.defined=!1;gt.prototype.mustUseProperty=!1;gt.prototype.number=!1;gt.prototype.overloadedBoolean=!1;gt.prototype.property="";gt.prototype.spaceSeparated=!1;gt.prototype.space=void 0;let jH=0;const pe=$r(),qe=$r(),rd=$r(),B=$r(),Pe=$r(),Hr=$r(),bt=$r();function $r(){return 2**++jH}const id=Object.freeze(Object.defineProperty({__proto__:null,boolean:pe,booleanish:qe,commaOrSpaceSeparated:bt,commaSeparated:Hr,number:B,overloadedBoolean:rd,spaceSeparated:Pe},Symbol.toStringTag,{value:"Module"})),Gu=Object.keys(id);class uh extends gt{constructor(t,n,i,r){let o=-1;if(super(t,n),Av(this,"space",r),typeof i=="number")for(;++o<Gu.length;){const a=Gu[o];Av(this,Gu[o],(i&id[a])===id[a])}}}uh.prototype.defined=!0;function Av(e,t,n){n&&(e[t]=n)}function vi(e){const t={},n={};for(const[i,r]of Object.entries(e.properties)){const o=new uh(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),t[i]=o,n[nd(i)]=i,n[nd(o.attribute)]=i}return new ra(t,n,e.space)}const _C=vi({properties:{ariaActiveDescendant:null,ariaAtomic:qe,ariaAutoComplete:null,ariaBusy:qe,ariaChecked:qe,ariaColCount:B,ariaColIndex:B,ariaColSpan:B,ariaControls:Pe,ariaCurrent:null,ariaDescribedBy:Pe,ariaDetails:null,ariaDisabled:qe,ariaDropEffect:Pe,ariaErrorMessage:null,ariaExpanded:qe,ariaFlowTo:Pe,ariaGrabbed:qe,ariaHasPopup:null,ariaHidden:qe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Pe,ariaLevel:B,ariaLive:null,ariaModal:qe,ariaMultiLine:qe,ariaMultiSelectable:qe,ariaOrientation:null,ariaOwns:Pe,ariaPlaceholder:null,ariaPosInSet:B,ariaPressed:qe,ariaReadOnly:qe,ariaRelevant:null,ariaRequired:qe,ariaRoleDescription:Pe,ariaRowCount:B,ariaRowIndex:B,ariaRowSpan:B,ariaSelected:qe,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 wC(e,t){return t in e?e[t]:t}function xC(e,t){return wC(e,t.toLowerCase())}const MH=vi({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Hr,acceptCharset:Pe,accessKey:Pe,action:null,allow:null,allowFullScreen:pe,allowPaymentRequest:pe,allowUserMedia:pe,alt:null,as:null,async:pe,autoCapitalize:null,autoComplete:Pe,autoFocus:pe,autoPlay:pe,blocking:Pe,capture:null,charSet:null,checked:pe,cite:null,className:Pe,cols:B,colSpan:null,content:null,contentEditable:qe,controls:pe,controlsList:Pe,coords:B|Hr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:pe,defer:pe,dir:null,dirName:null,disabled:pe,download:rd,draggable:qe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:pe,formTarget:null,headers:Pe,height:B,hidden:rd,high:B,href:null,hrefLang:null,htmlFor:Pe,httpEquiv:Pe,id:null,imageSizes:null,imageSrcSet:null,inert:pe,inputMode:null,integrity:null,is:null,isMap:pe,itemId:null,itemProp:Pe,itemRef:Pe,itemScope:pe,itemType:Pe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:pe,low:B,manifest:null,max:null,maxLength:B,media:null,method:null,min:null,minLength:B,multiple:pe,muted:pe,name:null,nonce:null,noModule:pe,noValidate:pe,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:pe,optimum:B,pattern:null,ping:Pe,placeholder:null,playsInline:pe,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:pe,referrerPolicy:null,rel:Pe,required:pe,reversed:pe,rows:B,rowSpan:B,sandbox:Pe,scope:null,scoped:pe,seamless:pe,selected:pe,shadowRootClonable:pe,shadowRootDelegatesFocus:pe,shadowRootMode:null,shape:null,size:B,sizes:null,slot:null,span:B,spellCheck:qe,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:pe,useMap:null,value:qe,width:B,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Pe,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:pe,declare:pe,event:null,face:null,frame:null,frameBorder:null,hSpace:B,leftMargin:B,link:null,longDesc:null,lowSrc:null,marginHeight:B,marginWidth:B,noResize:pe,noHref:pe,noShade:pe,noWrap:pe,object:null,profile:null,prompt:null,rev:null,rightMargin:B,rules:null,scheme:null,scrolling:qe,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:pe,disableRemotePlayback:pe,prefix:null,property:null,results:B,security:null,unselectable:null},space:"html",transform:xC}),zH=vi({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:bt,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:Pe,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:pe,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:Hr,g2:Hr,glyphName:Hr,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:bt,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:Pe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:B,pointsAtY:B,pointsAtZ:B,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:bt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:bt,rev:bt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:bt,requiredFeatures:bt,requiredFonts:bt,requiredFormats:bt,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:bt,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:bt,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:bt,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:wC}),SC=vi({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()}}),IC=vi({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:xC}),kC=vi({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),DH={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"},UH=/[A-Z]/g,Pv=/-[a-z]/g,LH=/^data[-\w.:]+$/i;function FH(e,t){const n=nd(t);let i=t,r=gt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&LH.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(Pv,ZH);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!Pv.test(o)){let a=o.replace(UH,BH);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}r=uh}return new r(i,t)}function BH(e){return"-"+e.toLowerCase()}function ZH(e){return e.charAt(1).toUpperCase()}const qH=bC([_C,MH,SC,IC,kC],"html"),ch=bC([_C,zH,SC,IC,kC],"svg");function VH(e){return e.join(" ").trim()}var Mr={},Ku,Rv;function HH(){if(Rv)return Ku;Rv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,s=/^\s+|\s+$/g,u=`
|
|
143
|
+
`,l="/",c="*",d="",f="comment",p="declaration";function g(y,v){if(typeof y!="string")throw new TypeError("First argument must be a string");if(!y)return[];v=v||{};var x=1,S=1;function b(z){var U=z.match(t);U&&(x+=U.length);var Q=z.lastIndexOf(u);S=~Q?z.length-Q:S+z.length}function A(){var z={line:x,column:S};return function(U){return U.position=new E(z),j(),U}}function E(z){this.start=z,this.end={line:x,column:S},this.source=v.source}E.prototype.content=y;function C(z){var U=new Error(v.source+":"+x+":"+S+": "+z);if(U.reason=z,U.filename=v.source,U.line=x,U.column=S,U.source=y,!v.silent)throw U}function P(z){var U=z.exec(y);if(U){var Q=U[0];return b(Q),y=y.slice(Q.length),U}}function j(){P(n)}function F(z){var U;for(z=z||[];U=D();)U!==!1&&z.push(U);return z}function D(){var z=A();if(!(l!=y.charAt(0)||c!=y.charAt(1))){for(var U=2;d!=y.charAt(U)&&(c!=y.charAt(U)||l!=y.charAt(U+1));)++U;if(U+=2,d===y.charAt(U-1))return C("End of comment missing");var Q=y.slice(2,U-2);return S+=2,b(Q),y=y.slice(U),S+=2,z({type:f,comment:Q})}}function V(){var z=A(),U=P(i);if(U){if(D(),!P(r))return C("property missing ':'");var Q=P(o),ie=z({type:p,property:m(U[0].replace(e,d)),value:Q?m(Q[0].replace(e,d)):d});return P(a),ie}}function G(){var z=[];F(z);for(var U;U=V();)U!==!1&&(z.push(U),F(z));return z}return j(),G()}function m(y){return y?y.replace(s,d):d}return Ku=g,Ku}var Ov;function JH(){if(Ov)return Mr;Ov=1;var e=Mr&&Mr.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.default=n;const t=e(HH());function n(i,r){let o=null;if(!i||typeof i!="string")return o;const a=(0,t.default)(i),s=typeof r=="function";return a.forEach(u=>{if(u.type!=="declaration")return;const{property:l,value:c}=u;s?r(l,c,u):c&&(o=o||{},o[l]=c)}),o}return Mr}var ki={},Nv;function WH(){if(Nv)return ki;Nv=1,Object.defineProperty(ki,"__esModule",{value:!0}),ki.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(l){return!l||n.test(l)||e.test(l)},a=function(l,c){return c.toUpperCase()},s=function(l,c){return"".concat(c,"-")},u=function(l,c){return c===void 0&&(c={}),o(l)?l:(l=l.toLowerCase(),c.reactCompat?l=l.replace(r,s):l=l.replace(i,s),l.replace(t,a))};return ki.camelCase=u,ki}var Ei,jv;function GH(){if(jv)return Ei;jv=1;var e=Ei&&Ei.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(JH()),n=WH();function i(r,o){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(s,u){s&&u&&(a[(0,n.camelCase)(s,o)]=u)}),a}return i.default=i,Ei=i,Ei}var KH=GH();const YH=Ho(KH),EC=TC("end"),dh=TC("start");function TC(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 QH(e){const t=dh(e),n=EC(e);if(t&&n)return{start:t,end:n}}function Ui(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Mv(e.position):"start"in e||"end"in e?Mv(e):"line"in e||"column"in e?od(e):""}function od(e){return zv(e&&e.line)+":"+zv(e&&e.column)}function Mv(e){return od(e&&e.start)+"-"+od(e&&e.end)}function zv(e){return e&&typeof e=="number"?e:1}class nt extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",o={},a=!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&&(a=!0,r=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const s=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=s?s.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=s?s.line:void 0,this.name=Ui(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=a&&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}}nt.prototype.file="";nt.prototype.name="";nt.prototype.reason="";nt.prototype.message="";nt.prototype.stack="";nt.prototype.column=void 0;nt.prototype.line=void 0;nt.prototype.ancestors=void 0;nt.prototype.cause=void 0;nt.prototype.fatal=void 0;nt.prototype.place=void 0;nt.prototype.ruleId=void 0;nt.prototype.source=void 0;const ph={}.hasOwnProperty,XH=new Map,e5=/[A-Z]/g,t5=new Set(["table","tbody","thead","tfoot","tr"]),n5=new Set(["td","th"]),$C="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function r5(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=d5(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=c5(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"?ch:qH,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=CC(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function CC(e,t,n){if(t.type==="element")return i5(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return o5(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return s5(e,t,n);if(t.type==="mdxjsEsm")return a5(e,t);if(t.type==="root")return l5(e,t,n);if(t.type==="text")return u5(e,t)}function i5(e,t,n){const i=e.schema;let r=i;t.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=ch,e.schema=r),e.ancestors.push(t);const o=PC(e,t.tagName,!1),a=p5(e,t);let s=hh(e,t);return t5.has(t.tagName)&&(s=s.filter(function(u){return typeof u=="string"?!NH(u):!0})),AC(e,a,o,t),fh(a,s),e.ancestors.pop(),e.schema=i,e.create(t,o,a,n)}function o5(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)}go(e,t.position)}function a5(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);go(e,t.position)}function s5(e,t,n){const i=e.schema;let r=i;t.name==="svg"&&i.space==="html"&&(r=ch,e.schema=r),e.ancestors.push(t);const o=t.name===null?e.Fragment:PC(e,t.name,!0),a=f5(e,t),s=hh(e,t);return AC(e,a,o,t),fh(a,s),e.ancestors.pop(),e.schema=i,e.create(t,o,a,n)}function l5(e,t,n){const i={};return fh(i,hh(e,t)),e.create(t,e.Fragment,i,n)}function u5(e,t){return t.value}function AC(e,t,n,i){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=i)}function fh(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function c5(e,t,n){return i;function i(r,o,a,s){const l=Array.isArray(a.children)?n:t;return s?l(o,a,s):l(o,a)}}function d5(e,t){return n;function n(i,r,o,a){const s=Array.isArray(o.children),u=dh(i);return t(r,o,a,s,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function p5(e,t){const n={};let i,r;for(r in t.properties)if(r!=="children"&&ph.call(t.properties,r)){const o=h5(e,r,t.properties[r]);if(o){const[a,s]=o;e.tableCellAlignToStyle&&a==="align"&&typeof s=="string"&&n5.has(t.tagName)?i=s:n[a]=s}}if(i){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return n}function f5(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 a=o.expression;a.type;const s=a.properties[0];s.type,Object.assign(n,e.evaluater.evaluateExpression(s.argument))}else go(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 s=i.value.data.estree.body[0];s.type,o=e.evaluater.evaluateExpression(s.expression)}else go(e,t.position);else o=i.value===null?!0:i.value;n[r]=o}return n}function hh(e,t){const n=[];let i=-1;const r=e.passKeys?new Map:XH;for(;++i<t.children.length;){const o=t.children[i];let a;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const l=r.get(u)||0;a=u+"-"+l,r.set(u,l+1)}}const s=CC(e,o,a);s!==void 0&&n.push(s)}return n}function h5(e,t,n){const i=FH(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=i.commaSeparated?CH(n):VH(n)),i.property==="style"){let r=typeof n=="object"?n:m5(e,String(n));return e.stylePropertyNameCase==="css"&&(r=g5(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?DH[i.property]||i.property:i.attribute,n]}}function m5(e,t){try{return YH(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const i=n,r=new nt("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=$C+"#cannot-parse-style-attribute",r}}function PC(e,t,n){let i;if(!n)i={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let o=-1,a;for(;++o<r.length;){const s=$v(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};a=a?{type:"MemberExpression",object:a,property:s,computed:!!(o&&s.type==="Literal"),optional:!1}:s}i=a}else i=$v(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(i.type==="Literal"){const r=i.value;return ph.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);go(e)}function go(e,t){const n=new nt("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=$C+"#cannot-handle-mdx-estrees-without-createevaluater",n}function g5(e){const t={};let n;for(n in e)ph.call(e,n)&&(t[v5(n)]=e[n]);return t}function v5(e){let t=e.replace(e5,y5);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function y5(e){return"-"+e.toLowerCase()}const Yu={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"]},b5={};function _5(e,t){const n=b5,i=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return RC(e,i,r)}function RC(e,t,n){if(w5(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 Dv(e.children,t,n)}return Array.isArray(e)?Dv(e,t,n):""}function Dv(e,t,n){const i=[];let r=-1;for(;++r<e.length;)i[r]=RC(e[r],t,n);return i.join("")}function w5(e){return!!(e&&typeof e=="object")}const Uv=document.createElement("i");function mh(e){const t="&"+e+";";Uv.innerHTML=t;const n=Uv.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function bn(e,t,n,i){const r=e.length;let o=0,a;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,i.length<1e4)a=Array.from(i),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);o<i.length;)a=i.slice(o,o+1e4),a.unshift(t,0),e.splice(...a),o+=1e4,t+=1e4}function zt(e,t){return e.length>0?(bn(e,e.length,0,t),e):t}const Lv={}.hasOwnProperty;function x5(e){const t={};let n=-1;for(;++n<e.length;)S5(t,e[n]);return t}function S5(e,t){let n;for(n in t){const r=(Lv.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let a;if(o)for(a in o){Lv.call(r,a)||(r[a]=[]);const s=o[a];I5(r[a],Array.isArray(s)?s:s?[s]:[])}}}function I5(e,t){let n=-1;const i=[];for(;++n<t.length;)(t[n].add==="after"?e:i).push(t[n]);bn(e,0,0,i)}function OC(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 Jr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const fn=ir(/[A-Za-z]/),xt=ir(/[\dA-Za-z]/),k5=ir(/[#-'*+\--9=?A-Z^-~]/);function ad(e){return e!==null&&(e<32||e===127)}const sd=ir(/\d/),E5=ir(/[\dA-Fa-f]/),T5=ir(/[!-/:-@[-`{-~]/);function se(e){return e!==null&&e<-2}function mt(e){return e!==null&&(e<0||e===32)}function _e(e){return e===-2||e===-1||e===32}const $5=ir(new RegExp("\\p{P}|\\p{S}","u")),C5=ir(/\s/);function ir(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function yi(e){const t=[];let n=-1,i=0,r=0;for(;++n<e.length;){const o=e.charCodeAt(n);let a="";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))||(a=String.fromCharCode(o));else if(o>55295&&o<57344){const s=e.charCodeAt(n+1);o<56320&&s>56319&&s<57344?(a=String.fromCharCode(o,s),r=1):a="�"}else a=String.fromCharCode(o);a&&(t.push(e.slice(i,n),encodeURIComponent(a)),i=n+r+1,a=""),r&&(n+=r,r=0)}return t.join("")+e.slice(i)}function Oe(e,t,n,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(u){return _e(u)?(e.enter(n),s(u)):t(u)}function s(u){return _e(u)&&o++<r?(e.consume(u),s):(e.exit(n),t(u))}}const A5={tokenize:P5};function P5(e){const t=e.attempt(this.parser.constructs.contentInitial,i,r);let n;return t;function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Oe(e,t,"linePrefix")}function r(s){return e.enter("paragraph"),o(s)}function o(s){const u=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=u),n=u,a(s)}function a(s){if(s===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(s);return}return se(s)?(e.consume(s),e.exit("chunkText"),o):(e.consume(s),a)}}const R5={tokenize:O5},Fv={tokenize:N5};function O5(e){const t=this,n=[];let i=0,r,o,a;return s;function s(S){if(i<n.length){const b=n[i];return t.containerState=b[1],e.attempt(b[0].continuation,u,l)(S)}return l(S)}function u(S){if(i++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&x();const b=t.events.length;let A=b,E;for(;A--;)if(t.events[A][0]==="exit"&&t.events[A][1].type==="chunkFlow"){E=t.events[A][1].end;break}v(i);let C=b;for(;C<t.events.length;)t.events[C][1].end={...E},C++;return bn(t.events,A+1,0,t.events.slice(b)),t.events.length=C,l(S)}return s(S)}function l(S){if(i===n.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Fv,c,d)(S)}function c(S){return r&&x(),v(i),f(S)}function d(S){return t.parser.lazy[t.now().line]=i!==n.length,a=t.now().offset,g(S)}function f(S){return t.containerState={},e.attempt(Fv,p,g)(S)}function p(S){return i++,n.push([t.currentConstruct,t.containerState]),f(S)}function g(S){if(S===null){r&&x(),v(0),e.consume(S);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),m(S)}function m(S){if(S===null){y(e.exit("chunkFlow"),!0),v(0),e.consume(S);return}return se(S)?(e.consume(S),y(e.exit("chunkFlow")),i=0,t.interrupt=void 0,s):(e.consume(S),m)}function y(S,b){const A=t.sliceStream(S);if(b&&A.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(A),t.parser.lazy[S.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<a&&(!r.events[E][1].end||r.events[E][1].end.offset>a))return;const C=t.events.length;let P=C,j,F;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){if(j){F=t.events[P][1].end;break}j=!0}for(v(i),E=C;E<t.events.length;)t.events[E][1].end={...F},E++;bn(t.events,P+1,0,t.events.slice(C)),t.events.length=E}}function v(S){let b=n.length;for(;b-- >S;){const A=n[b];t.containerState=A[1],A[0].exit.call(t,e)}n.length=S}function x(){r.write([null]),o=void 0,r=void 0,t.containerState._closeFlow=void 0}}function N5(e,t,n){return Oe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Bv(e){if(e===null||mt(e)||C5(e))return 1;if($5(e))return 2}function gh(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 ld={name:"attention",resolveAll:j5,tokenize:M5};function j5(e,t){let n=-1,i,r,o,a,s,u,l,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;u=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};Zv(d,-u),Zv(f,u),a={type:u>1?"strongSequence":"emphasisSequence",start:d,end:{...e[i][1].end}},s={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},r={type:u>1?"strong":"emphasis",start:{...a.start},end:{...s.end}},e[i][1].end={...a.start},e[n][1].start={...s.end},l=[],e[i][1].end.offset-e[i][1].start.offset&&(l=zt(l,[["enter",e[i][1],t],["exit",e[i][1],t]])),l=zt(l,[["enter",r,t],["enter",a,t],["exit",a,t],["enter",o,t]]),l=zt(l,gh(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),l=zt(l,[["exit",o,t],["enter",s,t],["exit",s,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,l=zt(l,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,bn(e,i-1,n-i+3,l),n=i+l.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function M5(e,t){const n=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Bv(i);let o;return a;function a(u){return o=u,e.enter("attentionSequence"),s(u)}function s(u){if(u===o)return e.consume(u),s;const l=e.exit("attentionSequence"),c=Bv(u),d=!c||c===2&&r||n.includes(u),f=!r||r===2&&c||n.includes(i);return l._open=!!(o===42?d:d&&(r||!f)),l._close=!!(o===42?f:f&&(c||!d)),t(u)}}function Zv(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const z5={name:"autolink",tokenize:D5};function D5(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 fn(p)?(e.consume(p),a):p===64?n(p):l(p)}function a(p){return p===43||p===45||p===46||xt(p)?(i=1,s(p)):l(p)}function s(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||xt(p))&&i++<32?(e.consume(p),s):(i=0,l(p))}function u(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||ad(p)?n(p):(e.consume(p),u)}function l(p){return p===64?(e.consume(p),c):k5(p)?(e.consume(p),l):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 g=p===45?f:d;return e.consume(p),g}return n(p)}}const tu={partial:!0,tokenize:U5};function U5(e,t,n){return i;function i(o){return _e(o)?Oe(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||se(o)?t(o):n(o)}}const NC={continuation:{tokenize:F5},exit:B5,name:"blockQuote",tokenize:L5};function L5(e,t,n){const i=this;return r;function r(a){if(a===62){const s=i.containerState;return s.open||(e.enter("blockQuote",{_container:!0}),s.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),o}return n(a)}function o(a){return _e(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function F5(e,t,n){const i=this;return r;function r(a){return _e(a)?Oe(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):o(a)}function o(a){return e.attempt(NC,t,n)(a)}}function B5(e){e.exit("blockQuote")}const jC={name:"characterEscape",tokenize:Z5};function Z5(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 T5(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const MC={name:"characterReference",tokenize:q5};function q5(e,t,n){const i=this;let r=0,o,a;return s;function s(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),u}function u(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),l):(e.enter("characterReferenceValue"),o=31,a=xt,c(d))}function l(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,a=E5,c):(e.enter("characterReferenceValue"),o=7,a=sd,c(d))}function c(d){if(d===59&&r){const f=e.exit("characterReferenceValue");return a===xt&&!mh(i.sliceSerialize(f))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(d)&&r++<o?(e.consume(d),c):n(d)}}const qv={partial:!0,tokenize:H5},Vv={concrete:!0,name:"codeFenced",tokenize:V5};function V5(e,t,n){const i=this,r={partial:!0,tokenize:A};let o=0,a=0,s;return u;function u(E){return l(E)}function l(E){const C=i.events[i.events.length-1];return o=C&&C[1].type==="linePrefix"?C[2].sliceSerialize(C[1],!0).length:0,s=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(E)}function c(E){return E===s?(a++,e.consume(E),c):a<3?n(E):(e.exit("codeFencedFenceSequence"),_e(E)?Oe(e,d,"whitespace")(E):d(E))}function d(E){return E===null||se(E)?(e.exit("codeFencedFence"),i.interrupt?t(E):e.check(qv,m,b)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(E))}function f(E){return E===null||se(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(E)):_e(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Oe(e,p,"whitespace")(E)):E===96&&E===s?n(E):(e.consume(E),f)}function p(E){return E===null||se(E)?d(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||se(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(E)):E===96&&E===s?n(E):(e.consume(E),g)}function m(E){return e.attempt(r,b,y)(E)}function y(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),v}function v(E){return o>0&&_e(E)?Oe(e,x,"linePrefix",o+1)(E):x(E)}function x(E){return E===null||se(E)?e.check(qv,m,b)(E):(e.enter("codeFlowValue"),S(E))}function S(E){return E===null||se(E)?(e.exit("codeFlowValue"),x(E)):(e.consume(E),S)}function b(E){return e.exit("codeFenced"),t(E)}function A(E,C,P){let j=0;return F;function F(U){return E.enter("lineEnding"),E.consume(U),E.exit("lineEnding"),D}function D(U){return E.enter("codeFencedFence"),_e(U)?Oe(E,V,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):V(U)}function V(U){return U===s?(E.enter("codeFencedFenceSequence"),G(U)):P(U)}function G(U){return U===s?(j++,E.consume(U),G):j>=a?(E.exit("codeFencedFenceSequence"),_e(U)?Oe(E,z,"whitespace")(U):z(U)):P(U)}function z(U){return U===null||se(U)?(E.exit("codeFencedFence"),C(U)):P(U)}}}function H5(e,t,n){const i=this;return r;function r(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o)}function o(a){return i.parser.lazy[i.now().line]?n(a):t(a)}}const Qu={name:"codeIndented",tokenize:W5},J5={partial:!0,tokenize:G5};function W5(e,t,n){const i=this;return r;function r(l){return e.enter("codeIndented"),Oe(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(l):n(l)}function a(l){return l===null?u(l):se(l)?e.attempt(J5,a,u)(l):(e.enter("codeFlowValue"),s(l))}function s(l){return l===null||se(l)?(e.exit("codeFlowValue"),a(l)):(e.consume(l),s)}function u(l){return e.exit("codeIndented"),t(l)}}function G5(e,t,n){const i=this;return r;function r(a){return i.parser.lazy[i.now().line]?n(a):se(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r):Oe(e,o,"linePrefix",5)(a)}function o(a){const s=i.events[i.events.length-1];return s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(a):se(a)?r(a):n(a)}}const K5={name:"codeText",previous:Q5,resolve:Y5,tokenize:X5};function Y5(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 Q5(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function X5(e,t,n){let i=0,r,o;return a;function a(d){return e.enter("codeText"),e.enter("codeTextSequence"),s(d)}function s(d){return d===96?(e.consume(d),i++,s):(e.exit("codeTextSequence"),u(d))}function u(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),u):d===96?(o=e.enter("codeTextSequence"),r=0,c(d)):se(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),u):(e.enter("codeTextData"),l(d))}function l(d){return d===null||d===32||d===96||se(d)?(e.exit("codeTextData"),u(d)):(e.consume(d),l)}function c(d){return d===96?(e.consume(d),r++,c):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(o.type="codeTextData",l(d))}}class eJ{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&&Ti(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),Ti(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Ti(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);Ti(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Ti(this.left,n.reverse())}}}function Ti(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 zC(e){const t={};let n=-1,i,r,o,a,s,u,l;const c=new eJ(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"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(t,tJ(c,n)),n=t[n],l=!0);else if(i[1]._container){for(o=n,r=void 0;o--;)if(a=c.get(o),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(c.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=o);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(i[1].end={...c.get(r)[1].start},s=c.slice(r,n),s.unshift(i),c.splice(r,n-r+1,s))}}return bn(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!l}function tJ(e,t){const n=e.get(t)[1],i=e.get(t)[2];let r=t-1;const o=[];let a=n._tokenizer;a||(a=i.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const s=a.events,u=[],l={};let c,d,f=-1,p=n,g=0,m=0;const y=[m];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(c=i.sliceStream(p),p.next||c.push(null),d&&a.defineSkip(p.start),p._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(c),p._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]==="exit"&&s[f-1][0]==="enter"&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(m=f+1,y.push(m),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(a.events=[],p?(p._tokenizer=void 0,p.previous=void 0):y.pop(),f=y.length;f--;){const v=s.slice(y[f],y[f+1]),x=o.pop();u.push([x,x+v.length-1]),e.splice(x,2,v)}for(u.reverse(),f=-1;++f<u.length;)l[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return l}const nJ={resolve:iJ,tokenize:oJ},rJ={partial:!0,tokenize:aJ};function iJ(e){return zC(e),e}function oJ(e,t){let n;return i;function i(s){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(s)}function r(s){return s===null?o(s):se(s)?e.check(rJ,a,o)(s):(e.consume(s),r)}function o(s){return e.exit("chunkContent"),e.exit("content"),t(s)}function a(s){return e.consume(s),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function aJ(e,t,n){const i=this;return r;function r(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Oe(e,o,"linePrefix")}function o(a){if(a===null||se(a))return n(a);const s=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(a):e.interrupt(i.parser.constructs.flow,n,t)(a)}}function DC(e,t,n,i,r,o,a,s,u){const l=u||Number.POSITIVE_INFINITY;let c=0;return d;function d(v){return v===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(v),e.exit(o),f):v===null||v===32||v===41||ad(v)?n(v):(e.enter(i),e.enter(a),e.enter(s),e.enter("chunkString",{contentType:"string"}),m(v))}function f(v){return v===62?(e.enter(o),e.consume(v),e.exit(o),e.exit(r),e.exit(i),t):(e.enter(s),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(s),f(v)):v===null||v===60||se(v)?n(v):(e.consume(v),v===92?g:p)}function g(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function m(v){return!c&&(v===null||v===41||mt(v))?(e.exit("chunkString"),e.exit(s),e.exit(a),e.exit(i),t(v)):c<l&&v===40?(e.consume(v),c++,m):v===41?(e.consume(v),c--,m):v===null||v===32||v===40||ad(v)?n(v):(e.consume(v),v===92?y:m)}function y(v){return v===40||v===41||v===92?(e.consume(v),m):m(v)}}function UC(e,t,n,i,r,o){const a=this;let s=0,u;return l;function l(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),c}function c(p){return s>999||p===null||p===91||p===93&&!u||p===94&&!s&&"_hiddenFootnoteSupport"in a.parser.constructs?n(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),t):se(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||se(p)||s++>999?(e.exit("chunkString"),c(p)):(e.consume(p),u||(u=!_e(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),s++,d):d(p)}}function LC(e,t,n,i,r,o){let a;return s;function s(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),a=f===40?41:f,u):n(f)}function u(f){return f===a?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),t):(e.enter(o),l(f))}function l(f){return f===a?(e.exit(o),u(a)):f===null?n(f):se(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Oe(e,l,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===a||f===null||se(f)?(e.exit("chunkString"),l(f)):(e.consume(f),f===92?d:c)}function d(f){return f===a||f===92?(e.consume(f),c):c(f)}}function Li(e,t){let n;return i;function i(r){return se(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,i):_e(r)?Oe(e,i,n?"linePrefix":"lineSuffix")(r):t(r)}}const sJ={name:"definition",tokenize:uJ},lJ={partial:!0,tokenize:cJ};function uJ(e,t,n){const i=this;let r;return o;function o(p){return e.enter("definition"),a(p)}function a(p){return UC.call(i,e,s,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function s(p){return r=Jr(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):n(p)}function u(p){return mt(p)?Li(e,l)(p):l(p)}function l(p){return DC(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function c(p){return e.attempt(lJ,d,d)(p)}function d(p){return _e(p)?Oe(e,f,"whitespace")(p):f(p)}function f(p){return p===null||se(p)?(e.exit("definition"),i.parser.defined.push(r),t(p)):n(p)}}function cJ(e,t,n){return i;function i(s){return mt(s)?Li(e,r)(s):n(s)}function r(s){return LC(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(s)}function o(s){return _e(s)?Oe(e,a,"whitespace")(s):a(s)}function a(s){return s===null||se(s)?t(s):n(s)}}const dJ={name:"hardBreakEscape",tokenize:pJ};function pJ(e,t,n){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return se(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const fJ={name:"headingAtx",resolve:hJ,tokenize:mJ};function hJ(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"},bn(e,i,n-i+1,[["enter",r,t],["enter",o,t],["exit",o,t],["exit",r,t]])),e}function mJ(e,t,n){let i=0;return r;function r(c){return e.enter("atxHeading"),o(c)}function o(c){return e.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&i++<6?(e.consume(c),a):c===null||mt(c)?(e.exit("atxHeadingSequence"),s(c)):n(c)}function s(c){return c===35?(e.enter("atxHeadingSequence"),u(c)):c===null||se(c)?(e.exit("atxHeading"),t(c)):_e(c)?Oe(e,s,"whitespace")(c):(e.enter("atxHeadingText"),l(c))}function u(c){return c===35?(e.consume(c),u):(e.exit("atxHeadingSequence"),s(c))}function l(c){return c===null||c===35||mt(c)?(e.exit("atxHeadingText"),s(c)):(e.consume(c),l)}}const gJ=["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"],Hv=["pre","script","style","textarea"],vJ={concrete:!0,name:"htmlFlow",resolveTo:_J,tokenize:wJ},yJ={partial:!0,tokenize:SJ},bJ={partial:!0,tokenize:xJ};function _J(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 wJ(e,t,n){const i=this;let r,o,a,s,u;return l;function l(T){return c(T)}function c(T){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(T),d}function d(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),o=!0,m):T===63?(e.consume(T),r=3,i.interrupt?t:I):fn(T)?(e.consume(T),a=String.fromCharCode(T),y):n(T)}function f(T){return T===45?(e.consume(T),r=2,p):T===91?(e.consume(T),r=5,s=0,g):fn(T)?(e.consume(T),r=4,i.interrupt?t:I):n(T)}function p(T){return T===45?(e.consume(T),i.interrupt?t:I):n(T)}function g(T){const H="CDATA[";return T===H.charCodeAt(s++)?(e.consume(T),s===H.length?i.interrupt?t:V:g):n(T)}function m(T){return fn(T)?(e.consume(T),a=String.fromCharCode(T),y):n(T)}function y(T){if(T===null||T===47||T===62||mt(T)){const H=T===47,te=a.toLowerCase();return!H&&!o&&Hv.includes(te)?(r=1,i.interrupt?t(T):V(T)):gJ.includes(a.toLowerCase())?(r=6,H?(e.consume(T),v):i.interrupt?t(T):V(T)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(T):o?x(T):S(T))}return T===45||xt(T)?(e.consume(T),a+=String.fromCharCode(T),y):n(T)}function v(T){return T===62?(e.consume(T),i.interrupt?t:V):n(T)}function x(T){return _e(T)?(e.consume(T),x):F(T)}function S(T){return T===47?(e.consume(T),F):T===58||T===95||fn(T)?(e.consume(T),b):_e(T)?(e.consume(T),S):F(T)}function b(T){return T===45||T===46||T===58||T===95||xt(T)?(e.consume(T),b):A(T)}function A(T){return T===61?(e.consume(T),E):_e(T)?(e.consume(T),A):S(T)}function E(T){return T===null||T===60||T===61||T===62||T===96?n(T):T===34||T===39?(e.consume(T),u=T,C):_e(T)?(e.consume(T),E):P(T)}function C(T){return T===u?(e.consume(T),u=null,j):T===null||se(T)?n(T):(e.consume(T),C)}function P(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||mt(T)?A(T):(e.consume(T),P)}function j(T){return T===47||T===62||_e(T)?S(T):n(T)}function F(T){return T===62?(e.consume(T),D):n(T)}function D(T){return T===null||se(T)?V(T):_e(T)?(e.consume(T),D):n(T)}function V(T){return T===45&&r===2?(e.consume(T),Q):T===60&&r===1?(e.consume(T),ie):T===62&&r===4?(e.consume(T),Te):T===63&&r===3?(e.consume(T),I):T===93&&r===5?(e.consume(T),me):se(T)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(yJ,ve,G)(T)):T===null||se(T)?(e.exit("htmlFlowData"),G(T)):(e.consume(T),V)}function G(T){return e.check(bJ,z,ve)(T)}function z(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),U}function U(T){return T===null||se(T)?G(T):(e.enter("htmlFlowData"),V(T))}function Q(T){return T===45?(e.consume(T),I):V(T)}function ie(T){return T===47?(e.consume(T),a="",X):V(T)}function X(T){if(T===62){const H=a.toLowerCase();return Hv.includes(H)?(e.consume(T),Te):V(T)}return fn(T)&&a.length<8?(e.consume(T),a+=String.fromCharCode(T),X):V(T)}function me(T){return T===93?(e.consume(T),I):V(T)}function I(T){return T===62?(e.consume(T),Te):T===45&&r===2?(e.consume(T),I):V(T)}function Te(T){return T===null||se(T)?(e.exit("htmlFlowData"),ve(T)):(e.consume(T),Te)}function ve(T){return e.exit("htmlFlow"),t(T)}}function xJ(e,t,n){const i=this;return r;function r(a){return se(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o):n(a)}function o(a){return i.parser.lazy[i.now().line]?n(a):t(a)}}function SJ(e,t,n){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(tu,t,n)}}const IJ={name:"htmlText",tokenize:kJ};function kJ(e,t,n){const i=this;let r,o,a;return s;function s(I){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(I),u}function u(I){return I===33?(e.consume(I),l):I===47?(e.consume(I),A):I===63?(e.consume(I),S):fn(I)?(e.consume(I),P):n(I)}function l(I){return I===45?(e.consume(I),c):I===91?(e.consume(I),o=0,g):fn(I)?(e.consume(I),x):n(I)}function c(I){return I===45?(e.consume(I),p):n(I)}function d(I){return I===null?n(I):I===45?(e.consume(I),f):se(I)?(a=d,ie(I)):(e.consume(I),d)}function f(I){return I===45?(e.consume(I),p):d(I)}function p(I){return I===62?Q(I):I===45?f(I):d(I)}function g(I){const Te="CDATA[";return I===Te.charCodeAt(o++)?(e.consume(I),o===Te.length?m:g):n(I)}function m(I){return I===null?n(I):I===93?(e.consume(I),y):se(I)?(a=m,ie(I)):(e.consume(I),m)}function y(I){return I===93?(e.consume(I),v):m(I)}function v(I){return I===62?Q(I):I===93?(e.consume(I),v):m(I)}function x(I){return I===null||I===62?Q(I):se(I)?(a=x,ie(I)):(e.consume(I),x)}function S(I){return I===null?n(I):I===63?(e.consume(I),b):se(I)?(a=S,ie(I)):(e.consume(I),S)}function b(I){return I===62?Q(I):S(I)}function A(I){return fn(I)?(e.consume(I),E):n(I)}function E(I){return I===45||xt(I)?(e.consume(I),E):C(I)}function C(I){return se(I)?(a=C,ie(I)):_e(I)?(e.consume(I),C):Q(I)}function P(I){return I===45||xt(I)?(e.consume(I),P):I===47||I===62||mt(I)?j(I):n(I)}function j(I){return I===47?(e.consume(I),Q):I===58||I===95||fn(I)?(e.consume(I),F):se(I)?(a=j,ie(I)):_e(I)?(e.consume(I),j):Q(I)}function F(I){return I===45||I===46||I===58||I===95||xt(I)?(e.consume(I),F):D(I)}function D(I){return I===61?(e.consume(I),V):se(I)?(a=D,ie(I)):_e(I)?(e.consume(I),D):j(I)}function V(I){return I===null||I===60||I===61||I===62||I===96?n(I):I===34||I===39?(e.consume(I),r=I,G):se(I)?(a=V,ie(I)):_e(I)?(e.consume(I),V):(e.consume(I),z)}function G(I){return I===r?(e.consume(I),r=void 0,U):I===null?n(I):se(I)?(a=G,ie(I)):(e.consume(I),G)}function z(I){return I===null||I===34||I===39||I===60||I===61||I===96?n(I):I===47||I===62||mt(I)?j(I):(e.consume(I),z)}function U(I){return I===47||I===62||mt(I)?j(I):n(I)}function Q(I){return I===62?(e.consume(I),e.exit("htmlTextData"),e.exit("htmlText"),t):n(I)}function ie(I){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),X}function X(I){return _e(I)?Oe(e,me,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):me(I)}function me(I){return e.enter("htmlTextData"),a(I)}}const vh={name:"labelEnd",resolveAll:CJ,resolveTo:AJ,tokenize:PJ},EJ={tokenize:RJ},TJ={tokenize:OJ},$J={tokenize:NJ};function CJ(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&&bn(e,0,e.length,n),e}function AJ(e,t){let n=e.length,i=0,r,o,a,s;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(a){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"&&(a=n);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[o][1].start},end:{...e[a][1].end}},c={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[a-2][1].start}};return s=[["enter",u,t],["enter",l,t]],s=zt(s,e.slice(o+1,o+i+3)),s=zt(s,[["enter",c,t]]),s=zt(s,gh(t.parser.constructs.insideSpan.null,e.slice(o+i+4,a-3),t)),s=zt(s,[["exit",c,t],e[a-2],e[a-1],["exit",l,t]]),s=zt(s,e.slice(a+1)),s=zt(s,[["exit",u,t]]),bn(e,o,e.length,s),e}function PJ(e,t,n){const i=this;let r=i.events.length,o,a;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 s;function s(f){return o?o._inactive?d(f):(a=i.parser.defined.includes(Jr(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):n(f)}function u(f){return f===40?e.attempt(EJ,c,a?c:d)(f):f===91?e.attempt(TJ,c,a?l:d)(f):a?c(f):d(f)}function l(f){return e.attempt($J,c,d)(f)}function c(f){return t(f)}function d(f){return o._balanced=!0,n(f)}}function RJ(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 mt(d)?Li(e,o)(d):o(d)}function o(d){return d===41?c(d):DC(e,a,s,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return mt(d)?Li(e,u)(d):c(d)}function s(d){return n(d)}function u(d){return d===34||d===39||d===40?LC(e,l,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function l(d){return mt(d)?Li(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 OJ(e,t,n){const i=this;return r;function r(s){return UC.call(i,e,o,a,"reference","referenceMarker","referenceString")(s)}function o(s){return i.parser.defined.includes(Jr(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?t(s):n(s)}function a(s){return n(s)}}function NJ(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 jJ={name:"labelStartImage",resolveAll:vh.resolveAll,tokenize:MJ};function MJ(e,t,n){const i=this;return r;function r(s){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(s),e.exit("labelImageMarker"),o}function o(s){return s===91?(e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelImage"),a):n(s)}function a(s){return s===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(s):t(s)}}const zJ={name:"labelStartLink",resolveAll:vh.resolveAll,tokenize:DJ};function DJ(e,t,n){const i=this;return r;function r(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),o}function o(a){return a===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(a):t(a)}}const Xu={name:"lineEnding",tokenize:UJ};function UJ(e,t){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Oe(e,t,"linePrefix")}}const Ja={name:"thematicBreak",tokenize:LJ};function LJ(e,t,n){let i=0,r;return o;function o(l){return e.enter("thematicBreak"),a(l)}function a(l){return r=l,s(l)}function s(l){return l===r?(e.enter("thematicBreakSequence"),u(l)):i>=3&&(l===null||se(l))?(e.exit("thematicBreak"),t(l)):n(l)}function u(l){return l===r?(e.consume(l),i++,u):(e.exit("thematicBreakSequence"),_e(l)?Oe(e,s,"whitespace")(l):s(l))}}const dt={continuation:{tokenize:qJ},exit:HJ,name:"list",tokenize:ZJ},FJ={partial:!0,tokenize:JJ},BJ={partial:!0,tokenize:VJ};function ZJ(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,a=0;return s;function s(p){const g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:sd(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Ja,n,l)(p):l(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return n(p)}function u(p){return sd(p)&&++a<10?(e.consume(p),u):(!i.interrupt||a<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),l(p)):n(p)}function l(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(tu,i.interrupt?n:c,e.attempt(FJ,f,d))}function c(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function d(p){return _e(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 qJ(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check(tu,r,o);function r(s){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Oe(e,t,"listItemIndent",i.containerState.size+1)(s)}function o(s){return i.containerState.furtherBlankLines||!_e(s)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,a(s)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(BJ,t,a)(s))}function a(s){return i.containerState._closeFlow=!0,i.interrupt=void 0,Oe(e,e.attempt(dt,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s)}}function VJ(e,t,n){const i=this;return Oe(e,r,"listItemIndent",i.containerState.size+1);function r(o){const a=i.events[i.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===i.containerState.size?t(o):n(o)}}function HJ(e){e.exit(this.containerState.type)}function JJ(e,t,n){const i=this;return Oe(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const a=i.events[i.events.length-1];return!_e(o)&&a&&a[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const Jv={name:"setextUnderline",resolveTo:WJ,tokenize:GJ};function WJ(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 a={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",a,t]),e.splice(o+1,0,["exit",e[i][1],t]),e[i][1].end={...e[o][1].end}):e[i][1]=a,e.push(["exit",a,t]),e}function GJ(e,t,n){const i=this;let r;return o;function o(l){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=l,a(l)):n(l)}function a(l){return e.enter("setextHeadingLineSequence"),s(l)}function s(l){return l===r?(e.consume(l),s):(e.exit("setextHeadingLineSequence"),_e(l)?Oe(e,u,"lineSuffix")(l):u(l))}function u(l){return l===null||se(l)?(e.exit("setextHeadingLine"),t(l)):n(l)}}const KJ={tokenize:YJ};function YJ(e){const t=this,n=e.attempt(tu,i,e.attempt(this.parser.constructs.flowInitial,r,Oe(e,e.attempt(this.parser.constructs.flow,r,e.attempt(nJ,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 QJ={resolveAll:BC()},XJ=FC("string"),eW=FC("text");function FC(e){return{resolveAll:BC(e==="text"?tW:void 0),tokenize:t};function t(n){const i=this,r=this.parser.constructs[e],o=n.attempt(r,a,s);return a;function a(c){return l(c)?o(c):s(c)}function s(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),u}function u(c){return l(c)?(n.exit("data"),o(c)):(n.consume(c),u)}function l(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 BC(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 tW(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,a=-1,s=0,u;for(;o--;){const l=r[o];if(typeof l=="string"){for(a=l.length;l.charCodeAt(a-1)===32;)s++,a--;if(a)break;a=-1}else if(l===-2)u=!0,s++;else if(l!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){const l={type:n===e.length||u||s<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:i.start._bufferIndex+a,_index:i.start._index+o,line:i.end.line,column:i.end.column-s,offset:i.end.offset-s},end:{...i.end}};i.end={...l.start},i.start.offset===i.end.offset?Object.assign(i,l):(e.splice(n,0,["enter",l,t],["exit",l,t]),n+=2)}n++}return e}const nW={42:dt,43:dt,45:dt,48:dt,49:dt,50:dt,51:dt,52:dt,53:dt,54:dt,55:dt,56:dt,57:dt,62:NC},rW={91:sJ},iW={[-2]:Qu,[-1]:Qu,32:Qu},oW={35:fJ,42:Ja,45:[Jv,Ja],60:vJ,61:Jv,95:Ja,96:Vv,126:Vv},aW={38:MC,92:jC},sW={[-5]:Xu,[-4]:Xu,[-3]:Xu,33:jJ,38:MC,42:ld,60:[z5,IJ],91:zJ,92:[dJ,jC],93:vh,95:ld,96:K5},lW={null:[ld,QJ]},uW={null:[42,95]},cW={null:[]},dW=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:uW,contentInitial:rW,disable:cW,document:nW,flow:oW,flowInitial:iW,insideSpan:lW,string:aW,text:sW},Symbol.toStringTag,{value:"Module"}));function pW(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 a=[],s=[];const u={attempt:C(A),check:C(E),consume:x,enter:S,exit:b,interrupt:C(E,{interrupt:!0})},l={code:null,containerState:{},defineSkip:m,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d};let c=t.tokenize.call(l,u);return t.resolveAll&&o.push(t),l;function d(D){return a=zt(a,D),y(),a[a.length-1]!==null?[]:(P(t,0),l.events=gh(o,l.events,l),l.events)}function f(D,V){return hW(p(D),V)}function p(D){return fW(a,D)}function g(){const{_bufferIndex:D,_index:V,line:G,column:z,offset:U}=i;return{_bufferIndex:D,_index:V,line:G,column:z,offset:U}}function m(D){r[D.line]=D.column,F()}function y(){let D;for(;i._index<a.length;){const V=a[i._index];if(typeof V=="string")for(D=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===D&&i._bufferIndex<V.length;)v(V.charCodeAt(i._bufferIndex));else v(V)}}function v(D){c=c(D)}function x(D){se(D)?(i.line++,i.column=1,i.offset+=D===-3?2:1,F()):D!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===a[i._index].length&&(i._bufferIndex=-1,i._index++)),l.previous=D}function S(D,V){const G=V||{};return G.type=D,G.start=g(),l.events.push(["enter",G,l]),s.push(G),G}function b(D){const V=s.pop();return V.end=g(),l.events.push(["exit",V,l]),V}function A(D,V){P(D,V.from)}function E(D,V){V.restore()}function C(D,V){return G;function G(z,U,Q){let ie,X,me,I;return Array.isArray(z)?ve(z):"tokenize"in z?ve([z]):Te(z);function Te(le){return we;function we(vt){const sn=vt!==null&&le[vt],Rt=vt!==null&&le.null,Qe=[...Array.isArray(sn)?sn:sn?[sn]:[],...Array.isArray(Rt)?Rt:Rt?[Rt]:[]];return ve(Qe)(vt)}}function ve(le){return ie=le,X=0,le.length===0?Q:T(le[X])}function T(le){return we;function we(vt){return I=j(),me=le,le.partial||(l.currentConstruct=le),le.name&&l.parser.constructs.disable.null.includes(le.name)?te():le.tokenize.call(V?Object.assign(Object.create(l),V):l,u,H,te)(vt)}}function H(le){return D(me,I),U}function te(le){return I.restore(),++X<ie.length?T(ie[X]):Q}}}function P(D,V){D.resolveAll&&!o.includes(D)&&o.push(D),D.resolve&&bn(l.events,V,l.events.length-V,D.resolve(l.events.slice(V),l)),D.resolveTo&&(l.events=D.resolveTo(l.events,l))}function j(){const D=g(),V=l.previous,G=l.currentConstruct,z=l.events.length,U=Array.from(s);return{from:z,restore:Q};function Q(){i=D,l.previous=V,l.currentConstruct=G,l.events.length=z,s=U,F()}}function F(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function fW(e,t){const n=t.start._index,i=t.start._bufferIndex,r=t.end._index,o=t.end._bufferIndex;let a;if(n===r)a=[e[n].slice(i,o)];else{if(a=e.slice(n,r),i>-1){const s=a[0];typeof s=="string"?a[0]=s.slice(i):a.shift()}o>0&&a.push(e[r].slice(0,o))}return a}function hW(e,t){let n=-1;const i=[];let r;for(;++n<e.length;){const o=e[n];let a;if(typeof o=="string")a=o;else switch(o){case-5:{a="\r";break}case-4:{a=`
|
|
144
|
+
`;break}case-3:{a=`\r
|
|
145
|
+
`;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(o)}r=o===-2,i.push(a)}return i.join("")}function mW(e){const i={constructs:x5([dW,...(e||{}).extensions||[]]),content:r(A5),defined:[],document:r(R5),flow:r(KJ),lazy:{},string:r(XJ),text:r(eW)};return i;function r(o){return a;function a(s){return pW(i,o,s)}}}function gW(e){for(;!zC(e););return e}const Wv=/[\0\t\n\r]/g;function vW(){let e=1,t="",n=!0,i;return r;function r(o,a,s){const u=[];let l,c,d,f,p;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),d=0,t="",n&&(o.charCodeAt(0)===65279&&d++,n=void 0);d<o.length;){if(Wv.lastIndex=d,l=Wv.exec(o),f=l&&l.index!==void 0?l.index:o.length,p=o.charCodeAt(f),!l){t=o.slice(d);break}if(p===10&&d===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),d<f&&(u.push(o.slice(d,f)),e+=f-d),p){case 0:{u.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,u.push(-2);e++<c;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}d=f+1}return s&&(i&&u.push(-5),t&&u.push(t),u.push(null)),u}}const yW=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function bW(e){return e.replace(yW,_W)}function _W(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),o=r===120||r===88;return OC(n.slice(o?2:1),o?16:10)}return mh(n)||e}const ZC={}.hasOwnProperty;function wW(e,t,n){return typeof t!="string"&&(n=t,t=void 0),xW(n)(gW(mW(n).document().write(vW()(e,t,!0))))}function xW(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(zn),autolinkProtocol:j,autolinkEmail:j,atxHeading:o(Ue),blockQuote:o(Rt),characterEscape:j,characterReference:j,codeFenced:o(Qe),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(Qe,a),codeText:o(Cr,a),codeTextData:j,data:j,codeFlowValue:j,definition:o(He),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(Le),hardBreakEscape:o(Be),hardBreakTrailing:o(Be),htmlFlow:o(ye,a),htmlFlowData:j,htmlText:o(ye,a),htmlTextData:j,image:o(yt),label:a,link:o(zn),listItem:o(Ne),listItemValue:f,listOrdered:o(Y,d),listUnordered:o(Y),paragraph:o(or),reference:T,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Ue),strong:o(oa),thematicBreak:o(sa)},exit:{atxHeading:u(),atxHeadingSequence:A,autolink:u(),autolinkEmail:sn,autolinkProtocol:vt,blockQuote:u(),characterEscapeValue:F,characterReferenceMarkerHexadecimal:te,characterReferenceMarkerNumeric:te,characterReferenceValue:le,characterReference:we,codeFenced:u(y),codeFencedFence:m,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:F,codeIndented:u(v),codeText:u(U),codeTextData:F,data:F,definition:u(),definitionDestinationString:b,definitionLabelString:x,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(V),hardBreakTrailing:u(V),htmlFlow:u(G),htmlFlowData:F,htmlText:u(z),htmlTextData:F,image:u(ie),label:me,labelText:X,lineEnding:D,link:u(Q),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:H,resourceDestinationString:I,resourceTitleString:Te,resource:ve,setextHeading:u(P),setextHeadingLineSequence:C,setextHeadingText:E,strong:u(),thematicBreak:u()}};qC(t,(e||{}).mdastExtensions||[]);const n={};return i;function i(N){let Z={type:"root",children:[]};const ne={stack:[Z],tokenStack:[],config:t,enter:s,exit:l,buffer:a,resume:c,data:n},he=[];let be=-1;for(;++be<N.length;)if(N[be][1].type==="listOrdered"||N[be][1].type==="listUnordered")if(N[be][0]==="enter")he.push(be);else{const rt=he.pop();be=r(N,rt,be)}for(be=-1;++be<N.length;){const rt=t[N[be][0]];ZC.call(rt,N[be][1].type)&&rt[N[be][1].type].call(Object.assign({sliceSerialize:N[be][2].sliceSerialize},ne),N[be][1])}if(ne.tokenStack.length>0){const rt=ne.tokenStack[ne.tokenStack.length-1];(rt[1]||Gv).call(ne,void 0,rt[0])}for(Z.position={start:Fn(N.length>0?N[0][1].start:{line:1,column:1,offset:0}),end:Fn(N.length>0?N[N.length-2][1].end:{line:1,column:1,offset:0})},be=-1;++be<t.transforms.length;)Z=t.transforms[be](Z)||Z;return Z}function r(N,Z,ne){let he=Z-1,be=-1,rt=!1,Sn,Ot,Dn,Nt;for(;++he<=ne;){const Xe=N[he];switch(Xe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Xe[0]==="enter"?be++:be--,Nt=void 0;break}case"lineEndingBlank":{Xe[0]==="enter"&&(Sn&&!Nt&&!be&&!Dn&&(Dn=he),Nt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Nt=void 0}if(!be&&Xe[0]==="enter"&&Xe[1].type==="listItemPrefix"||be===-1&&Xe[0]==="exit"&&(Xe[1].type==="listUnordered"||Xe[1].type==="listOrdered")){if(Sn){let Un=he;for(Ot=void 0;Un--;){const Zt=N[Un];if(Zt[1].type==="lineEnding"||Zt[1].type==="lineEndingBlank"){if(Zt[0]==="exit")continue;Ot&&(N[Ot][1].type="lineEndingBlank",rt=!0),Zt[1].type="lineEnding",Ot=Un}else if(!(Zt[1].type==="linePrefix"||Zt[1].type==="blockQuotePrefix"||Zt[1].type==="blockQuotePrefixWhitespace"||Zt[1].type==="blockQuoteMarker"||Zt[1].type==="listItemIndent"))break}Dn&&(!Ot||Dn<Ot)&&(Sn._spread=!0),Sn.end=Object.assign({},Ot?N[Ot][1].start:Xe[1].end),N.splice(Ot||he,0,["exit",Sn,Xe[2]]),he++,ne++}if(Xe[1].type==="listItemPrefix"){const Un={type:"listItem",_spread:!1,start:Object.assign({},Xe[1].start),end:void 0};Sn=Un,N.splice(he,0,["enter",Un,Xe[2]]),he++,ne++,Dn=void 0,Nt=!0}}}return N[Z][1]._spread=rt,ne}function o(N,Z){return ne;function ne(he){s.call(this,N(he),he),Z&&Z.call(this,he)}}function a(){this.stack.push({type:"fragment",children:[]})}function s(N,Z,ne){this.stack[this.stack.length-1].children.push(N),this.stack.push(N),this.tokenStack.push([Z,ne||void 0]),N.position={start:Fn(Z.start),end:void 0}}function u(N){return Z;function Z(ne){N&&N.call(this,ne),l.call(this,ne)}}function l(N,Z){const ne=this.stack.pop(),he=this.tokenStack.pop();if(he)he[0].type!==N.type&&(Z?Z.call(this,N,he[0]):(he[1]||Gv).call(this,N,he[0]));else throw new Error("Cannot close `"+N.type+"` ("+Ui({start:N.start,end:N.end})+"): it’s not open");ne.position.end=Fn(N.end)}function c(){return _5(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(N){if(this.data.expectingFirstListItemValue){const Z=this.stack[this.stack.length-2];Z.start=Number.parseInt(this.sliceSerialize(N),10),this.data.expectingFirstListItemValue=void 0}}function p(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.lang=N}function g(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.meta=N}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function v(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N.replace(/(\r?\n|\r)$/g,"")}function x(N){const Z=this.resume(),ne=this.stack[this.stack.length-1];ne.label=Z,ne.identifier=Jr(this.sliceSerialize(N)).toLowerCase()}function S(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.title=N}function b(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.url=N}function A(N){const Z=this.stack[this.stack.length-1];if(!Z.depth){const ne=this.sliceSerialize(N).length;Z.depth=ne}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function C(N){const Z=this.stack[this.stack.length-1];Z.depth=this.sliceSerialize(N).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function j(N){const ne=this.stack[this.stack.length-1].children;let he=ne[ne.length-1];(!he||he.type!=="text")&&(he=aa(),he.position={start:Fn(N.start),end:void 0},ne.push(he)),this.stack.push(he)}function F(N){const Z=this.stack.pop();Z.value+=this.sliceSerialize(N),Z.position.end=Fn(N.end)}function D(N){const Z=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ne=Z.children[Z.children.length-1];ne.position.end=Fn(N.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Z.type)&&(j.call(this,N),F.call(this,N))}function V(){this.data.atHardBreak=!0}function G(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function z(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function U(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function Q(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=Z,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function ie(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=Z,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function X(N){const Z=this.sliceSerialize(N),ne=this.stack[this.stack.length-2];ne.label=bW(Z),ne.identifier=Jr(Z).toLowerCase()}function me(){const N=this.stack[this.stack.length-1],Z=this.resume(),ne=this.stack[this.stack.length-1];if(this.data.inReference=!0,ne.type==="link"){const he=N.children;ne.children=he}else ne.alt=Z}function I(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.url=N}function Te(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.title=N}function ve(){this.data.inReference=void 0}function T(){this.data.referenceType="collapsed"}function H(N){const Z=this.resume(),ne=this.stack[this.stack.length-1];ne.label=Z,ne.identifier=Jr(this.sliceSerialize(N)).toLowerCase(),this.data.referenceType="full"}function te(N){this.data.characterReferenceType=N.type}function le(N){const Z=this.sliceSerialize(N),ne=this.data.characterReferenceType;let he;ne?(he=OC(Z,ne==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):he=mh(Z);const be=this.stack[this.stack.length-1];be.value+=he}function we(N){const Z=this.stack.pop();Z.position.end=Fn(N.end)}function vt(N){F.call(this,N);const Z=this.stack[this.stack.length-1];Z.url=this.sliceSerialize(N)}function sn(N){F.call(this,N);const Z=this.stack[this.stack.length-1];Z.url="mailto:"+this.sliceSerialize(N)}function Rt(){return{type:"blockquote",children:[]}}function Qe(){return{type:"code",lang:null,meta:null,value:""}}function Cr(){return{type:"inlineCode",value:""}}function He(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Le(){return{type:"emphasis",children:[]}}function Ue(){return{type:"heading",depth:0,children:[]}}function Be(){return{type:"break"}}function ye(){return{type:"html",value:""}}function yt(){return{type:"image",title:null,url:"",alt:null}}function zn(){return{type:"link",title:null,url:"",children:[]}}function Y(N){return{type:"list",ordered:N.type==="listOrdered",start:null,spread:N._spread,children:[]}}function Ne(N){return{type:"listItem",spread:N._spread,checked:null,children:[]}}function or(){return{type:"paragraph",children:[]}}function oa(){return{type:"strong",children:[]}}function aa(){return{type:"text",value:""}}function sa(){return{type:"thematicBreak"}}}function Fn(e){return{line:e.line,column:e.column,offset:e.offset}}function qC(e,t){let n=-1;for(;++n<t.length;){const i=t[n];Array.isArray(i)?qC(e,i):SW(e,i)}}function SW(e,t){let n;for(n in t)if(ZC.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 Gv(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Ui({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Ui({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Ui({start:t.start,end:t.end})+") is still open")}function IW(e){const t=this;t.parser=n;function n(i){return wW(i,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function kW(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 EW(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
146
|
+
`}]}function TW(e,t){const n=t.value?t.value+`
|
|
147
|
+
`:"",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 $W(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function CW(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function AW(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),r=yi(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let a,s=e.footnoteCounts.get(i);s===void 0?(s=0,e.footnoteOrder.push(i),a=e.footnoteOrder.length):a=o+1,s+=1,e.footnoteCounts.set(i,s);const u={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(s>1?"-"+s:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,u);const l={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,l),e.applyData(t,l)}function PW(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 RW(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function VC(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 a=r[r.length-1];return a&&a.type==="text"?a.value+=i:r.push({type:"text",value:i}),r}function OW(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return VC(e,t);const r={src:yi(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 NW(e,t){const n={src:yi(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 jW(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 MW(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return VC(e,t);const r={href:yi(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 zW(e,t){const n={href:yi(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 DW(e,t,n){const i=e.all(t),r=n?UW(n):HC(t),o={},a=[];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 s=-1;for(;++s<i.length;){const c=i[s];(r||s!==0||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
|
|
148
|
+
`}),c.type==="element"&&c.tagName==="p"&&!r?a.push(...c.children):a.push(c)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
|
|
149
|
+
`});const l={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,l),e.applyData(t,l)}function UW(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=HC(n[i])}return t}function HC(e){const t=e.spread;return t??e.children.length>1}function LW(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 a=i[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.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 FW(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function BW(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function ZW(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qW(e,t){const n=e.all(t),i=n.shift(),r=[];if(i){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},s=dh(t.children[1]),u=EC(t.children[t.children.length-1]);s&&u&&(a.position={start:s,end:u}),r.push(a)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function VW(e,t,n){const i=n?n.children:void 0,o=(i?i.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,s=a?a.length:t.children.length;let u=-1;const l=[];for(;++u<s;){const d=t.children[u],f={},p=a?a[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};d&&(g.children=e.all(d),e.patch(d,g),g=e.applyData(d,g)),l.push(g)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(l,!0)};return e.patch(t,c),e.applyData(t,c)}function HW(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Kv=9,Yv=32;function JW(e){const t=String(e),n=/\r?\n|\r/g;let i=n.exec(t),r=0;const o=[];for(;i;)o.push(Qv(t.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(t);return o.push(Qv(t.slice(r),r>0,!1)),o.join("")}function Qv(e,t,n){let i=0,r=e.length;if(t){let o=e.codePointAt(i);for(;o===Kv||o===Yv;)i++,o=e.codePointAt(i)}if(n){let o=e.codePointAt(r-1);for(;o===Kv||o===Yv;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function WW(e,t){const n={type:"text",value:JW(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function GW(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const KW={blockquote:kW,break:EW,code:TW,delete:$W,emphasis:CW,footnoteReference:AW,heading:PW,html:RW,imageReference:OW,image:NW,inlineCode:jW,linkReference:MW,link:zW,listItem:DW,list:LW,paragraph:FW,root:BW,strong:ZW,table:qW,tableCell:HW,tableRow:VW,text:WW,thematicBreak:GW,toml:Ra,yaml:Ra,definition:Ra,footnoteDefinition:Ra};function Ra(){}const JC=-1,nu=0,Fi=1,Os=2,yh=3,bh=4,_h=5,wh=6,WC=7,GC=8,Xv=typeof self=="object"?self:globalThis,YW=(e,t)=>{const n=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,a]=t[r];switch(o){case nu:case JC:return n(a,r);case Fi:{const s=n([],r);for(const u of a)s.push(i(u));return s}case Os:{const s=n({},r);for(const[u,l]of a)s[i(u)]=i(l);return s}case yh:return n(new Date(a),r);case bh:{const{source:s,flags:u}=a;return n(new RegExp(s,u),r)}case _h:{const s=n(new Map,r);for(const[u,l]of a)s.set(i(u),i(l));return s}case wh:{const s=n(new Set,r);for(const u of a)s.add(i(u));return s}case WC:{const{name:s,message:u}=a;return n(new Xv[s](u),r)}case GC:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:s}=new Uint8Array(a);return n(new DataView(s),a)}}return n(new Xv[o](a),r)};return i},ey=e=>YW(new Map,e)(0),zr="",{toString:QW}={},{keys:XW}=Object,$i=e=>{const t=typeof e;if(t!=="object"||!e)return[nu,t];const n=QW.call(e).slice(8,-1);switch(n){case"Array":return[Fi,zr];case"Object":return[Os,zr];case"Date":return[yh,zr];case"RegExp":return[bh,zr];case"Map":return[_h,zr];case"Set":return[wh,zr];case"DataView":return[Fi,n]}return n.includes("Array")?[Fi,n]:n.includes("Error")?[WC,n]:[Os,n]},Oa=([e,t])=>e===nu&&(t==="function"||t==="symbol"),eG=(e,t,n,i)=>{const r=(a,s)=>{const u=i.push(a)-1;return n.set(s,u),u},o=a=>{if(n.has(a))return n.get(a);let[s,u]=$i(a);switch(s){case nu:{let c=a;switch(u){case"bigint":s=GC,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);c=null;break;case"undefined":return r([JC],a)}return r([s,c],a)}case Fi:{if(u){let f=a;return u==="DataView"?f=new Uint8Array(a.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(a)),r([u,[...f]],a)}const c=[],d=r([s,c],a);for(const f of a)c.push(o(f));return d}case Os:{if(u)switch(u){case"BigInt":return r([u,a.toString()],a);case"Boolean":case"Number":case"String":return r([u,a.valueOf()],a)}if(t&&"toJSON"in a)return o(a.toJSON());const c=[],d=r([s,c],a);for(const f of XW(a))(e||!Oa($i(a[f])))&&c.push([o(f),o(a[f])]);return d}case yh:return r([s,a.toISOString()],a);case bh:{const{source:c,flags:d}=a;return r([s,{source:c,flags:d}],a)}case _h:{const c=[],d=r([s,c],a);for(const[f,p]of a)(e||!(Oa($i(f))||Oa($i(p))))&&c.push([o(f),o(p)]);return d}case wh:{const c=[],d=r([s,c],a);for(const f of a)(e||!Oa($i(f)))&&c.push(o(f));return d}}const{message:l}=a;return r([s,{name:u,message:l}],a)};return o},ty=(e,{json:t,lossy:n}={})=>{const i=[];return eG(!(t||n),!!t,new Map,i)(e),i},Ns=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?ey(ty(e,t)):structuredClone(e):(e,t)=>ey(ty(e,t));function tG(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 nG(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function rG(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||tG,i=e.options.footnoteBackLabel||nG,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},s=[];let u=-1;for(;++u<e.footnoteOrder.length;){const l=e.footnoteById.get(e.footnoteOrder[u]);if(!l)continue;const c=e.all(l),d=String(l.identifier).toUpperCase(),f=yi(d.toLowerCase());let p=0;const g=[],m=e.footnoteCounts.get(d);for(;m!==void 0&&++p<=m;){g.length>0&&g.push({type:"text",value:" "});let x=typeof n=="string"?n:n(u,p);typeof x=="string"&&(x={type:"text",value:x}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(x)?x:[x]})}const y=c[c.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const x=y.children[y.children.length-1];x&&x.type==="text"?x.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else c.push(...g);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(c,!0)};e.patch(l,v),s.push(v)}if(s.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Ns(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
150
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(s,!0)},{type:"text",value:`
|
|
151
|
+
`}]}}const KC=(function(e){if(e==null)return sG;if(typeof e=="function")return ru(e);if(typeof e=="object")return Array.isArray(e)?iG(e):oG(e);if(typeof e=="string")return aG(e);throw new Error("Expected function, string, or object as test")});function iG(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=KC(e[n]);return ru(i);function i(...r){let o=-1;for(;++o<t.length;)if(t[o].apply(this,r))return!0;return!1}}function oG(e){const t=e;return ru(n);function n(i){const r=i;let o;for(o in e)if(r[o]!==t[o])return!1;return!0}}function aG(e){return ru(t);function t(n){return n&&n.type===e}}function ru(e){return t;function t(n,i,r){return!!(lG(n)&&e.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function sG(){return!0}function lG(e){return e!==null&&typeof e=="object"&&"type"in e}const YC=[],uG=!0,ny=!1,cG="skip";function dG(e,t,n,i){let r;typeof t=="function"&&typeof n!="function"?(i=n,n=t):r=t;const o=KC(r),a=i?-1:1;s(e,void 0,[])();function s(u,l,c){const d=u&&typeof u=="object"?u:{};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 ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=YC,g,m,y;if((!t||o(u,l,c[c.length-1]||void 0))&&(p=pG(n(u,c)),p[0]===ny))return p;if("children"in u&&u.children){const v=u;if(v.children&&p[0]!==cG)for(m=(i?v.children.length:-1)+a,y=c.concat(v);m>-1&&m<v.children.length;){const x=v.children[m];if(g=s(x,m,y)(),g[0]===ny)return g;m=typeof g[1]=="number"?g[1]:m+a}}return p}}}function pG(e){return Array.isArray(e)?e:typeof e=="number"?[uG,e]:e==null?YC:[e]}function QC(e,t,n,i){let r,o,a;typeof t=="function"&&typeof n!="function"?(o=void 0,a=t,r=n):(o=t,a=n,r=i),dG(e,o,s,r);function s(u,l){const c=l[l.length-1],d=c?c.children.indexOf(u):void 0;return a(u,d,c)}}const ud={}.hasOwnProperty,fG={};function hG(e,t){const n=t||fG,i=new Map,r=new Map,o=new Map,a={...KW,...n.handlers},s={all:l,applyData:gG,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:a,one:u,options:n,patch:mG,wrap:yG};return QC(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)}}),s;function u(c,d){const f=c.type,p=s.handlers[f];if(ud.call(s.handlers,f)&&p)return p(s,c,d);if(s.options.passThrough&&s.options.passThrough.includes(f)){if("children"in c){const{children:m,...y}=c,v=Ns(y);return v.children=s.all(c),v}return Ns(c)}return(s.options.unknownHandler||vG)(s,c,d)}function l(c){const d=[];if("children"in c){const f=c.children;let p=-1;for(;++p<f.length;){const g=s.one(f[p],c);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=ry(g.value)),!Array.isArray(g)&&g.type==="element")){const m=g.children[0];m&&m.type==="text"&&(m.value=ry(m.value))}Array.isArray(g)?d.push(...g):d.push(g)}}}return d}}function mG(e,t){e.position&&(t.position=QH(e))}function gG(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 a="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:a}}n.type==="element"&&o&&Object.assign(n.properties,Ns(o)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function vG(e,t){const n=t.data||{},i="value"in t&&!(ud.call(n,"hProperties")||ud.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 yG(e,t){const n=[];let i=-1;for(t&&n.push({type:"text",value:`
|
|
152
|
+
`});++i<e.length;)i&&n.push({type:"text",value:`
|
|
153
|
+
`}),n.push(e[i]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
154
|
+
`}),n}function ry(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function iy(e,t){const n=hG(e,t),i=n.one(e,void 0),r=rG(n),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
155
|
+
`},r),o}function bG(e,t){return e&&"run"in e?async function(n,i){const r=iy(n,{file:i,...t});await e.run(r,i)}:function(n,i){return iy(n,{file:i,...e||t})}}function oy(e){if(e)throw e}var ec,ay;function _G(){if(ay)return ec;ay=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(l){return typeof Array.isArray=="function"?Array.isArray(l):t.call(l)==="[object Array]"},o=function(l){if(!l||t.call(l)!=="[object Object]")return!1;var c=e.call(l,"constructor"),d=l.constructor&&l.constructor.prototype&&e.call(l.constructor.prototype,"isPrototypeOf");if(l.constructor&&!c&&!d)return!1;var f;for(f in l);return typeof f>"u"||e.call(l,f)},a=function(l,c){n&&c.name==="__proto__"?n(l,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):l[c.name]=c.newValue},s=function(l,c){if(c==="__proto__")if(e.call(l,c)){if(i)return i(l,c).value}else return;return l[c]};return ec=function u(){var l,c,d,f,p,g,m=arguments[0],y=1,v=arguments.length,x=!1;for(typeof m=="boolean"&&(x=m,m=arguments[1]||{},y=2),(m==null||typeof m!="object"&&typeof m!="function")&&(m={});y<v;++y)if(l=arguments[y],l!=null)for(c in l)d=s(m,c),f=s(l,c),m!==f&&(x&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=d&&r(d)?d:[]):g=d&&o(d)?d:{},a(m,{name:c,newValue:u(x,g,f)})):typeof f<"u"&&a(m,{name:c,newValue:f}));return m},ec}var wG=_G();const tc=Ho(wG);function cd(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 xG(){const e=[],t={run:n,use:i};return t;function n(...r){let o=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);s(null,...r);function s(u,...l){const c=e[++o];let d=-1;if(u){a(u);return}for(;++d<r.length;)(l[d]===null||l[d]===void 0)&&(l[d]=r[d]);r=l,c?SG(c,s)(...l):a(null,...l)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function SG(e,t){let n;return i;function i(...a){const s=e.length>a.length;let u;s&&a.push(r);try{u=e.apply(this,a)}catch(l){const c=l;if(s&&n)throw c;return r(c)}s||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(a,...s){n||(n=!0,t(a,...s))}function o(a){r(null,a)}}const dn={basename:IG,dirname:kG,extname:EG,join:TG,sep:"/"};function IG(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ia(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 a=-1,s=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else a<0&&(o=!0,a=r+1),s>-1&&(e.codePointAt(r)===t.codePointAt(s--)?s<0&&(i=r):(s=-1,i=a));return n===i?i=a:i<0&&(i=e.length),e.slice(n,i)}function kG(e){if(ia(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 EG(e){ia(e);let t=e.length,n=-1,i=0,r=-1,o=0,a;for(;t--;){const s=e.codePointAt(t);if(s===47){if(a){i=t+1;break}continue}n<0&&(a=!0,n=t+1),s===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 TG(...e){let t=-1,n;for(;++t<e.length;)ia(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":$G(n)}function $G(e){ia(e);const t=e.codePointAt(0)===47;let n=CG(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function CG(e,t){let n="",i=0,r=-1,o=0,a=-1,s,u;for(;++a<=e.length;){if(a<e.length)s=e.codePointAt(a);else{if(s===47)break;s=47}if(s===47){if(!(r===a-1||o===1))if(r!==a-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(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",i=0):(n=n.slice(0,u),i=n.length-1-n.lastIndexOf("/")),r=a,o=0;continue}}else if(n.length>0){n="",i=0,r=a,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),i=a-r-1;r=a,o=0}else s===46&&o>-1?o++:o=-1}return n}function ia(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const AG={cwd:PG};function PG(){return"/"}function dd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function RG(e){if(typeof e=="string")e=new URL(e);else if(!dd(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 OG(e)}function OG(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 nc=["history","path","basename","stem","extname","dirname"];class XC{constructor(t){let n;t?dd(t)?n={path:t}:typeof t=="string"||NG(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":AG.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<nc.length;){const o=nc[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)nc.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?dn.basename(this.path):void 0}set basename(t){ic(t,"basename"),rc(t,"basename"),this.path=dn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?dn.dirname(this.path):void 0}set dirname(t){sy(this.basename,"dirname"),this.path=dn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?dn.extname(this.path):void 0}set extname(t){if(rc(t,"extname"),sy(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=dn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){dd(t)&&(t=RG(t)),ic(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?dn.basename(this.path,this.extname):void 0}set stem(t){ic(t,"stem"),rc(t,"stem"),this.path=dn.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 nt(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 rc(e,t){if(e&&e.includes(dn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+dn.sep+"`")}function ic(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function sy(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function NG(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const jG=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),MG={}.hasOwnProperty;class xh extends jG{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=xG()}copy(){const t=new xh;let n=-1;for(;++n<this.attachers.length;){const i=this.attachers[n];t.use(...i)}return t.data(tc(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(sc("data",this.frozen),this.namespace[t]=n,this):MG.call(this.namespace,t)&&this.namespace[t]||void 0:t?(sc("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=Na(t),i=this.parser||this.Parser;return oc("parse",i),i(String(n),n)}process(t,n){const i=this;return this.freeze(),oc("process",this.parser||this.Parser),ac("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(o,a){const s=Na(t),u=i.parse(s);i.run(u,s,function(c,d,f){if(c||!d||!f)return l(c);const p=d,g=i.stringify(p,f);UG(g)?f.value=g:f.result=g,l(c,f)});function l(c,d){c||!d?a(c):o?o(d):n(void 0,d)}}}processSync(t){let n=!1,i;return this.freeze(),oc("processSync",this.parser||this.Parser),ac("processSync",this.compiler||this.Compiler),this.process(t,r),uy("processSync","process",n),i;function r(o,a){n=!0,oy(o),i=a}}run(t,n,i){ly(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(a,s){const u=Na(n);r.run(t,u,l);function l(c,d,f){const p=d||t;c?s(c):a?a(p):i(void 0,p,f)}}}runSync(t,n){let i=!1,r;return this.run(t,n,o),uy("runSync","run",i),r;function o(a,s){oy(a),r=s,i=!0}}stringify(t,n){this.freeze();const i=Na(n),r=this.compiler||this.Compiler;return ac("stringify",r),ly(t),r(t,i)}use(t,...n){const i=this.attachers,r=this.namespace;if(sc("use",this.frozen),t!=null)if(typeof t=="function")u(t,n);else if(typeof t=="object")Array.isArray(t)?s(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(l){if(typeof l=="function")u(l,[]);else if(typeof l=="object")if(Array.isArray(l)){const[c,...d]=l;u(c,d)}else a(l);else throw new TypeError("Expected usable value, not `"+l+"`")}function a(l){if(!("plugins"in l)&&!("settings"in l))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");s(l.plugins),l.settings&&(r.settings=tc(!0,r.settings,l.settings))}function s(l){let c=-1;if(l!=null)if(Array.isArray(l))for(;++c<l.length;){const d=l[c];o(d)}else throw new TypeError("Expected a list of plugins, not `"+l+"`")}function u(l,c){let d=-1,f=-1;for(;++d<i.length;)if(i[d][0]===l){f=d;break}if(f===-1)i.push([l,...c]);else if(c.length>0){let[p,...g]=c;const m=i[f][1];cd(m)&&cd(p)&&(p=tc(!0,m,p)),i[f]=[l,p,...g]}}}}const zG=new xh().freeze();function oc(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ac(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function sc(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 ly(e){if(!cd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function uy(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Na(e){return DG(e)?e:new XC(e)}function DG(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function UG(e){return typeof e=="string"||LG(e)}function LG(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const FG="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",cy=[],dy={allowDangerousHtml:!0},BG=/^(https?|ircs?|mailto|xmpp)$/i,ZG=[{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 qG(e){const t=VG(e),n=HG(e);return JG(t.runSync(t.parse(n),n),e)}function VG(e){const t=e.rehypePlugins||cy,n=e.remarkPlugins||cy,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...dy}:dy;return zG().use(IW).use(n).use(bG,i).use(t)}function HG(e){const t=e.children||"",n=new XC;return typeof t=="string"&&(n.value=t),n}function JG(e,t){const n=t.allowedElements,i=t.allowElement,r=t.components,o=t.disallowedElements,a=t.skipHtml,s=t.unwrapDisallowed,u=t.urlTransform||WG;for(const c of ZG)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+FG+c.id,void 0);return QC(e,l),r5(e,{Fragment:h.Fragment,components:r,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function l(c,d,f){if(c.type==="raw"&&f&&typeof d=="number")return a?f.children.splice(d,1):f.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let p;for(p in Yu)if(Object.hasOwn(Yu,p)&&Object.hasOwn(c.properties,p)){const g=c.properties[p],m=Yu[p];(m===null||m.includes(c.tagName))&&(c.properties[p]=u(String(g||""),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 s&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d}}}function WG(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||BG.test(e.slice(0,t))?e:""}const GG=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),KG=(e,t)=>{if(!e||!t)return!1;const n=i=>{const{position:r,data:o,...a}=i||{};return a};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&GG(e.children,t.children)},Sh=(e,t)=>KG(e.node,t.node),YG=(e={})=>Object.fromEntries(Object.entries(e??{}).map(([t,n])=>{if(!n)return[t,n];const i=n,r=({node:o,...a})=>h.jsx(i,{...a});return[t,$.memo(r,Sh)]})),Ih=$.createContext(null),eA=()=>$.useContext(Ih)!==null,QG=({children:e,...t})=>h.jsx(Ih.Provider,{value:t,children:e}),XG=$.memo(QG,Sh),e7=({node:e,...t})=>h.jsx("pre",{...t}),t7=({node:e,...t})=>h.jsx("code",{...t}),kh=({node:e,components:{Pre:t,Code:n},code:i})=>h.jsx(t,{children:h.jsx(n,{node:e,children:i})}),n7=()=>null,r7=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},language:o,code:a})=>{const s=$.useMemo(()=>({Pre:t,Code:n}),[t,n]),u=o?i:kh;return h.jsxs(h.Fragment,{children:[h.jsx(r,{node:e,language:o,code:a}),h.jsx(u,{node:e,components:s,language:o??"unknown",code:a})]})};var lc={exports:{}};var py;function i7(){return py||(py=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var o="",a=0;a<arguments.length;a++){var s=arguments[a];s&&(o=r(o,i(s)))}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 a="";for(var s in o)t.call(o,s)&&o[s]&&(a=r(a,s));return a}function r(o,a){return a?o?o+" "+a:o+a:o}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(lc)),lc.exports}var o7=i7();const tA=Ho(o7),fy=({className:e,...t})=>({className:n,...i})=>({className:tA(e,n),...t,...i}),a7=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},componentsByLanguage:o={},children:a,...s})=>{const u=$.useContext(Ih),l=fy(u),c=Et(y=>h.jsx(t,{...l(y)})),d=fy(s),f=Et(y=>h.jsx(n,{...d(y)})),p=/language-(\w+)/.exec(s.className||"")?.[1]??"";if(typeof a!="string")return h.jsx(kh,{node:e,components:{Pre:c,Code:f},code:a});const g=o[p]?.SyntaxHighlighter??i,m=o[p]?.CodeHeader??r;return h.jsx(r7,{node:e,components:{Pre:c,Code:f,SyntaxHighlighter:g,CodeHeader:m},language:p||"unknown",code:a})},s7=({node:e,components:t,componentsByLanguage:n,...i})=>eA()?h.jsx(a7,{node:e,components:t,componentsByLanguage:n,...i}):h.jsx(t.Code,{...i}),l7=$.memo(s7,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Sh(e,t)),{useSmooth:u7,useSmoothStatus:c7,withSmoothContextProvider:d7}=Mk,p7=({components:e,componentsByLanguage:t,smooth:n=!0,preprocess:i,...r})=>{const o=BE(),a=$.useMemo(()=>i?{...o,text:i(o.text)}:o,[o,i]),{text:s}=u7(a,n),{pre:u=e7,code:l=t7,SyntaxHighlighter:c=kh,CodeHeader:d=n7}=e??{},f=$.useMemo(()=>({Pre:u,Code:l,SyntaxHighlighter:c,CodeHeader:d}),[u,l,c,d]),p=Et(m=>h.jsx(l7,{components:f,componentsByLanguage:t,...m})),g=$.useMemo(()=>{const{pre:m,code:y,SyntaxHighlighter:v,CodeHeader:x,...S}=e??{};return{...S,pre:XG,code:p}},[p,e]);return h.jsx(qG,{components:g,...r,children:s})},nA=$.forwardRef(({className:e,containerProps:t,containerComponent:n="div",...i},r)=>{const o=c7();return h.jsx(n,{"data-status":o.type,...t,className:tA(e,t?.className),ref:r,children:h.jsx(p7,{...i})})});nA.displayName="MarkdownTextPrimitive";const f7=d7(nA);function h7(e){return $.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 m7=()=>{const{plugins:e}=_.useElements(),t=h7(e);return h.jsx(f7,{remarkPlugins:[wA],className:"aui-md",components:y7,componentsByLanguage:t})},rA=$.memo(m7),g7=({language:e,code:t})=>{const i=_.useAssistantState(({message:s})=>s).status?.type==="complete",{isCopied:r,copyToClipboard:o}=v7(),a=()=>{!t||r||o(t)};return i?h.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:[h.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),h.jsxs(Ft,{tooltip:"Copy",onClick:a,children:[!r&&h.jsx(Mf,{}),r&&h.jsx(Wn,{})]})]}):null},v7=({copiedDuration:e=3e3}={})=>{const[t,n]=$.useState(!1);return{isCopied:t,copyToClipboard:r=>{r&&navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},y7=YG({h1:({className:e,...t})=>h.jsx("h1",{className:_.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>h.jsx("h2",{className:_.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})=>h.jsx("h3",{className:_.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})=>h.jsx("h4",{className:_.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})=>h.jsx("h5",{className:_.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>h.jsx("h6",{className:_.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>h.jsx("p",{className:_.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>h.jsx("a",{className:_.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>h.jsx("blockquote",{className:_.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>h.jsx("ul",{className:_.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>h.jsx("ol",{className:_.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>h.jsx("hr",{className:_.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>h.jsx("table",{className:_.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>h.jsx("th",{className:_.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})=>h.jsx("td",{className:_.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})=>h.jsx("tr",{className:_.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})=>h.jsx("sup",{className:_.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>h.jsx("pre",{className:_.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=eA();return h.jsx("code",{className:_.cn(!i&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...n})},CodeHeader:g7});var iu="Collapsible",[b7]=Wo(iu),[_7,Eh]=b7(iu),iA=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:i,defaultOpen:r,disabled:o,onOpenChange:a,...s}=e,[u,l]=Zl({prop:i,defaultProp:r??!1,onChange:a,caller:iu});return h.jsx(_7,{scope:n,disabled:o,contentId:Fr(),open:u,onOpenToggle:w.useCallback(()=>l(c=>!c),[l]),children:h.jsx(We.div,{"data-state":$h(u),"data-disabled":o?"":void 0,...s,ref:t})})});iA.displayName=iu;var oA="CollapsibleTrigger",aA=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,...i}=e,r=Eh(oA,n);return h.jsx(We.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":$h(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...i,ref:t,onClick:Re(e.onClick,r.onOpenToggle)})});aA.displayName=oA;var Th="CollapsibleContent",sA=w.forwardRef((e,t)=>{const{forceMount:n,...i}=e,r=Eh(Th,e.__scopeCollapsible);return h.jsx(Mn,{present:n||r.open,children:({present:o})=>h.jsx(w7,{...i,ref:t,present:o})})});sA.displayName=Th;var w7=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:i,children:r,...o}=e,a=Eh(Th,n),[s,u]=w.useState(i),l=w.useRef(null),c=Ge(t,l),d=w.useRef(0),f=d.current,p=w.useRef(0),g=p.current,m=a.open||s,y=w.useRef(m),v=w.useRef(void 0);return w.useEffect(()=>{const x=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(x)},[]),Lt(()=>{const x=l.current;if(x){v.current=v.current||{transitionDuration:x.style.transitionDuration,animationName:x.style.animationName},x.style.transitionDuration="0s",x.style.animationName="none";const S=x.getBoundingClientRect();d.current=S.height,p.current=S.width,y.current||(x.style.transitionDuration=v.current.transitionDuration,x.style.animationName=v.current.animationName),u(i)}},[a.open,i]),h.jsx(We.div,{"data-state":$h(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:m&&r})});function $h(e){return e?"open":"closed"}var x7=iA;function S7({...e}){return h.jsx(x7,{"data-slot":"collapsible",...e})}function I7({...e}){return h.jsx(aA,{"data-slot":"collapsible-trigger",...e})}function k7({...e}){return h.jsx(sA,{"data-slot":"collapsible-content",...e})}const hy=200,lA=({className:e,children:t})=>{const n=$.useRef(null),[i,r]=$.useState(!1),o=XL(n,hy),a=$.useCallback(s=>{s||o(),r(s)},[o]);return h.jsx(S7,{ref:n,open:i,onOpenChange:a,className:_.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${hy}ms`},children:t})};lA.displayName="ReasoningRoot";const E7=({className:e})=>h.jsx("div",{className:_.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)}),T7=({active:e,className:t})=>h.jsxs(I7,{className:_.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:[h.jsx(d2,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),h.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[h.jsx("span",{children:"Reasoning"}),e?h.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),h.jsx(_s,{className:_.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")})]}),uA=({className:e,children:t,"aria-busy":n})=>h.jsxs(k7,{className:_.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,h.jsx(E7,{})]});uA.displayName="ReasoningContent";const cA=({className:e,children:t})=>h.jsx("div",{className:_.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});cA.displayName="ReasoningText";const $7=()=>h.jsx(rA,{}),C7=({children:e,startIndex:t,endIndex:n})=>{const i=_.useAssistantState(({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 h.jsxs(lA,{children:[h.jsx(T7,{active:i}),h.jsx(uA,{"aria-busy":i,children:h.jsx(cA,{children:e})})]})},dA=$.memo($7);dA.displayName="Reasoning";const pA=$.memo(C7);pA.displayName="ReasoningGroup";function fA({...e}){return h.jsx(JU,{"data-slot":"popover",...e})}function hA({...e}){return h.jsx(WU,{"data-slot":"popover-trigger",...e})}function mA({className:e,align:t="center",sideOffset:n=4,...i}){return h.jsx(GU,{children:h.jsx(KU,{"data-slot":"popover-content",align:t,sideOffset:n,className:_.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 A7=gC("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 P7(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 R7(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function O7(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function gA({status:e}){return h.jsxs("div",{className:_.cn(A7({status:e})),children:[e==="pending"&&null,e==="running"&&h.jsx(ws,{className:"size-4 animate-spin"}),e==="complete"&&h.jsx(Wn,{className:"size-4"}),e==="error"&&h.jsx(Qo,{className:"size-4"}),e==="approval"&&h.jsx(ws,{className:"text-muted-foreground size-4 animate-spin"})]})}function N7({content:e}){const[t,n]=$.useState(!1),i=async r=>{r.stopPropagation(),await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)};return h.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?h.jsx(Wn,{className:"size-4"}):h.jsx(Mf,{className:"size-4"})})}function vA({text:e,language:t,className:n}){const[i,r]=$.useState(null);return $.useEffect(()=>{t&&xA.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?h.jsx("div",{className:_.cn("w-full bg-slate-800/90",n),dangerouslySetInnerHTML:{__html:i}}):h.jsx("pre",{className:_.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",n),children:e})}function j7({data:e}){const t=`data:image/png;base64,${e}`;return h.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
141
156
|
linear-gradient(135deg, #ccc 25%, transparent 25%),
|
|
142
157
|
linear-gradient(45deg, transparent 75%, #ccc 75%),
|
|
143
|
-
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:m.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function h2({content:e}){return m.jsx("div",{className:"w-full",children:e.content.map((t,r)=>{switch(t.type){case"text":{const o=c2(t._meta?.["getgram.ai/mime-type"]??"text/plain"),n=d2(t.text,o);return m.jsx(f0,{text:n,language:o},r)}case"image":return m.jsx(m2,{data:t.data},r);default:return m.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},r)}})})}function am({title:e,content:t,defaultExpanded:r=!1,highlightSyntax:o=!0,language:n="json"}){const[i,a]=z.useState(r),s=p2(t),l=s?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return m.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[m.jsxs("button",{onClick:()=>a(!i),className:"hover:bg-accent/50 flex w-full cursor-pointer items-center justify-between px-4 py-2.5 text-left transition-colors",children:[m.jsx("span",{className:"text-muted-foreground text-sm",children:e}),m.jsxs("div",{className:"flex items-center gap-1",children:[m.jsx(f2,{content:l}),m.jsx(W_,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",i&&"rotate-90")})]})]}),i&&m.jsx("div",{className:"border-border border-t",children:s?m.jsx(h2,{content:t}):o?m.jsx(f0,{text:l,language:n}):m.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:l})})]})}function g2({name:e,icon:t,provider:r,status:o="complete",request:n,result:i,defaultExpanded:a=!1,className:s,onApproveOnce:l,onApproveForSession:u,onDeny:c}){const d=o==="approval"&&l!==void 0&&c!==void 0,[f,p]=z.useState(a),g=n!==void 0||i!==void 0,[h,b]=z.useState("one-time"),[y,x]=z.useState(!1);z.useEffect(()=>{!d&&f&&!a&&p(!1)},[d]);const $=()=>{h==="for-session"&&u?u():l&&l()};return m.jsxs("div",{"data-slot":"tool-ui",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",s),children:[r&&m.jsxs("div",{"data-slot":"tool-ui-provider",className:T.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?m.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):m.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:r.charAt(0).toUpperCase()}),m.jsx("span",{className:"text-sm font-medium",children:r})]}),m.jsxs("button",{onClick:()=>g&&p(!f),disabled:!g,className:T.cn("flex w-full items-center gap-2 px-4 py-3 text-left",g&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[m.jsx(p0,{status:o}),m.jsx("span",{className:T.cn("flex-1 text-sm",!r&&d&&"shimmer"),children:e}),g&&m.jsx(Ti,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&g&&m.jsxs("div",{"data-slot":"tool-ui-content",children:[n!==void 0&&m.jsx(am,{title:"Arguments",content:n,highlightSyntax:!0,language:"json"}),i!==void 0&&m.jsx(am,{title:"Output",content:i,highlightSyntax:!0,language:"json"})]}),d&&m.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:[m.jsx("div",{children:m.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),m.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[m.jsxs($t,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[m.jsx(Eo,{className:"mr-1 size-3"}),"Deny"]}),m.jsxs("div",{className:"flex items-center",children:[m.jsxs($t,{variant:"default",size:"sm",onClick:$,className:"flex cursor-pointer justify-between gap-1 rounded-r-none bg-emerald-600 hover:bg-emerald-700",children:[m.jsx(nr,{className:"mr-1 size-3"}),m.jsx("span",{className:"min-w-[110px]",children:h==="one-time"?"Approve this time":"Approve always"})]}),m.jsxs(l0,{open:y,onOpenChange:x,children:[m.jsx(c0,{asChild:!0,children:m.jsx($t,{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:m.jsx(Ti,{className:"size-3"})})}),m.jsxs(d0,{align:"end",className:"w-64 p-1",sideOffset:4,children:[m.jsxs("button",{onClick:()=>{b("one-time"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(nr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="one-time"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve only once"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),u&&m.jsxs("button",{onClick:()=>{b("for-session"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[m.jsx(nr,{className:T.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="for-session"&&"invisible")}),m.jsxs("div",{className:"flex flex-col gap-0.5",children:[m.jsx("span",{className:"text-sm",children:"Approve always"}),m.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function v2({title:e,icon:t,status:r="complete",defaultExpanded:o=!1,children:n,className:i}){const[a,s]=z.useState(o);return m.jsxs("div",{"data-slot":"tool-ui-group",className:T.cn("border-border bg-card overflow-hidden rounded-lg border",i),children:[m.jsxs("button",{onClick:()=>s(!a),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||m.jsx(p0,{status:r==="running"?"running":"complete"}),m.jsx("span",{className:T.cn("flex-1 text-sm font-medium",r==="running"&&"shimmer"),children:e}),m.jsx(Ti,{className:T.cn("text-muted-foreground size-4 transition-transform duration-200",a&&"rotate-180")})]}),a&&m.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:n})]})}const y2=({toolName:e,toolCallId:t,status:r,result:o,args:n})=>{const{pendingApprovals:i,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:l}=J_(),u=i.get(t),d=L.useAssistantState(({message:x})=>x).parts.filter(x=>x.type==="tool-call"),f=d.findIndex(x=>x.toolName===e),p=()=>{s(t)},g=()=>{a(e),s(t)},h=()=>{l(t)},b=()=>u?"approval":r.type==="incomplete"?"error":r.type==="complete"?o&&typeof o=="object"&&"isError"in o&&o.isError?"error":"complete":"running",y=()=>{if(o!==void 0)return typeof o=="object"&&o!==null&&"content"in o&&Array.isArray(o.content)||typeof o=="string",o};return m.jsx("div",{className:T.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:m.jsx(g2,{name:e,status:b(),request:n,result:y(),onApproveOnce:u?p:void 0,onApproveForSession:u?g:void 0,onDeny:u?h:void 0,className:"rounded-none border-0"})})},$d=()=>{const{config:e}=T.useElements(),t=e.theme??{};return z.useMemo(()=>{const{colorScheme:r="light"}=t;return{className:r==="dark"||r==="system"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":void 0}},[t])},or=[.23,1,.32,1];function b2(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const _2=({children:e})=>{const t=L.useAssistantState(({message:s})=>s).parts,r=t.filter(s=>s.type==="tool-call"),o=r.some(s=>s.status?.type==="running"),{config:n}=T.useElements(),i=n.tools?.expandToolGroupsByDefault??!1,a=z.useMemo(()=>{const s=t.filter(l=>l.type==="tool-call");return s.length===0?"No tools called":s.length===1?`Calling ${b2(s[0].toolName)}...`:o?`Calling ${s.length} tools...`:`Executed ${s.length} tools`},[t,o]);return n.tools?.components?.[r[0]?.toolName]?e:r.length===1?m.jsx("div",{className:T.cn("my-4 w-full max-w-xl"),children:m.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):m.jsx("div",{className:"my-4 w-full max-w-xl",children:m.jsx(v2,{title:a,status:o?"running":"complete",defaultExpanded:i,children:e})})},w2=()=>m.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:[m.jsx("strong",{children:"Warning:"})," You are using an API key directly in the client. Please"," ",m.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"})," ","before deploying to production."]}),Sd=()=>{const e=$d(),t=T.useDensity(),{config:r}=T.useElements(),o=r.components??{},n=r.api&&"UNSAFE_apiKey"in r.api;return m.jsx(Zt.LazyMotion,{features:Zt.domAnimation,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",children:m.jsx(L.ThreadPrimitive.Root,{className:T.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",e.className),children:m.jsxs(L.ThreadPrimitive.Viewport,{className:T.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",t("p-lg")),children:[m.jsx(L.ThreadPrimitive.If,{empty:!0,children:o.ThreadWelcome?m.jsx(o.ThreadWelcome,{}):m.jsx($2,{})}),n&&m.jsx(w2,{}),m.jsx(L.ThreadPrimitive.Messages,{components:{UserMessage:o.UserMessage??C2,EditComposer:o.EditComposer??A2,AssistantMessage:o.AssistantMessage??O2}}),m.jsx(L.ThreadPrimitive.If,{empty:!1,children:m.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),m.jsx(I2,{})]})})})})},x2=()=>m.jsx(L.ThreadPrimitive.ScrollToBottom,{asChild:!0,children:m.jsx(ct,{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:m.jsx(vN,{})})}),$2=()=>{const{config:e}=T.useElements(),t=T.useDensity(),{title:r,subtitle:o}=e.welcome??{},n=e.variant==="standalone";return m.jsxs("div",{className:T.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",n?"items-center justify-center":"",t("gap-lg")),children:[m.jsx("div",{className:T.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:m.jsxs("div",{className:T.cn("aui-thread-welcome-message flex flex-col",n?"items-center text-center":"size-full justify-start",t("gap-sm"),!n&&t("py-md")),children:[m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:or},className:T.cn("aui-thread-welcome-message-motion-1 text-foreground font-semibold",t("text-title")),children:r}),m.jsx(Lt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:or},className:T.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:o})]})}),m.jsx(S2,{})]})},S2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),r=T.useDensity(),o=e.welcome?.suggestions??[],n=e.variant==="standalone";return o.length===0?null:m.jsx("div",{className:T.cn("aui-thread-welcome-suggestions w-full",r("gap-md"),r("py-lg"),n?"flex flex-wrap items-center justify-center":o.length===1?"flex":"grid max-w-fit @md:grid-cols-2"),children:o.map((i,a)=>m.jsx(Lt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*a,ease:or},className:T.cn("aui-thread-welcome-suggestion-display",!n&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:m.jsx(L.ThreadPrimitive.Suggestion,{prompt:i.action,send:!0,asChild:!0,children:m.jsxs($t,{variant:"ghost",className:T.cn("aui-thread-welcome-suggestion dark:hover:bg-accent/60 h-auto w-full border text-left whitespace-break-spaces",r("text-base"),n?`flex-row items-center ${r("gap-sm")} ${r("px-md")} ${r("py-sm")} ${t("full")}`:`w-full flex-1 flex-col flex-wrap items-start justify-start ${r("gap-sm")} ${r("px-lg")} ${r("py-md")} ${t("xl")}`),"aria-label":i.action,children:[m.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-foreground text-sm font-medium",children:i.title}),m.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:i.label})]})})},`suggested-action-${i.title}-${a}`))})},I2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),r=T.useDensity(),o=e.composer??{placeholder:"Send a message...",attachments:!0},n=e.components??{};return n.Composer?m.jsx(n.Composer,{}):m.jsxs("div",{className:T.cn("aui-composer-wrapper bg-background sticky bottom-0 flex w-full flex-col overflow-visible",r("gap-md"),r("py-md"),t("xl")),children:[m.jsx(x2,{}),m.jsxs(L.ComposerPrimitive.Root,{className:T.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:[o.attachments&&m.jsx(P6,{}),m.jsx(L.ComposerPrimitive.Input,{placeholder:o.placeholder,className:T.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",r("h-input"),r("text-base")),rows:1,autoFocus:!0,"aria-label":"Message input"}),m.jsx(E2,{})]})]})},k2=()=>{const{model:e,setModel:t}=T.useElements(),[r,o]=z.useState(!1),[n,i]=z.useState(!1),a=z.useRef(null),s=z.useRef(0),l=z.useRef(!1);z.useEffect(()=>{r&&!l.current&&requestAnimationFrame(()=>{const c=a.current;c&&c.scrollHeight>0&&(c.scrollTop=s.current)}),l.current=r},[r]),z.useEffect(()=>{r&&i(!1)},[r]);const u=c=>{s.current=c.currentTarget.scrollTop};return m.jsx(oS,{children:m.jsxs(ld,{open:n&&!r,onOpenChange:i,children:[m.jsxs(l0,{open:r,onOpenChange:o,children:[m.jsx(cd,{asChild:!0,children:m.jsx(c0,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"icon","data-state":r?"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:m.jsx(HN,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),m.jsx(d0,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:m.jsx("div",{ref:a,className:"max-h-48 overflow-y-auto",onScroll:u,children:Nc.map(c=>m.jsxs($t,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?m.jsx("div",{children:m.jsx(nr,{className:"size-4 text-emerald-500"})}):m.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),m.jsx(dd,{side:"bottom",align:"start",children:"Model Settings"})]})})},E2=()=>{const{config:e}=T.useElements(),t=T.useRadius(),r=e.composer??{attachments:!0};return m.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[m.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[r.attachments?m.jsx(C6,{}):m.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&m.jsx(k2,{})]}),m.jsx(L.ThreadPrimitive.If,{running:!1,children:m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx(ct,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:T.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:m.jsx(bN,{className:"aui-composer-send-icon size-5"})})})}),m.jsx(L.ThreadPrimitive.If,{running:!0,children:m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{type:"button",variant:"default",size:"icon",className:T.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:m.jsx(KN,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},T2=()=>m.jsx(L.MessagePrimitive.Error,{children:m.jsx(L.ErrorPrimitive.Root,{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:m.jsx(L.ErrorPrimitive.Message,{className:"aui-message-error-message line-clamp-2"})})}),O2=()=>{const{config:e}=T.useElements(),t=e.tools??{},r=e.components??{};return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.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:[m.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[m.jsx(L.MessagePrimitive.Parts,{components:{Text:r.Text??qS,Image:r.Image??N2,tools:{by_name:t.components,Fallback:r.ToolFallback??y2},Reasoning:r.Reasoning??YS,ReasoningGroup:r.ReasoningGroup??QS,ToolGroup:r.ToolGroup??_2}}),m.jsx(T2,{})]}),m.jsxs("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:[m.jsx(m0,{}),m.jsx(P2,{})]})]})})},N2=e=>m.jsx("img",{src:e.image}),P2=()=>m.jsxs(L.ActionBarPrimitive.Root,{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:[m.jsx(L.ActionBarPrimitive.Copy,{asChild:!0,children:m.jsxs(ct,{tooltip:"Copy",children:[m.jsx(L.MessagePrimitive.If,{copied:!0,children:m.jsx(nr,{})}),m.jsx(L.MessagePrimitive.If,{copied:!1,children:m.jsx(Pc,{})})]})}),m.jsx(L.ActionBarPrimitive.Reload,{asChild:!0,children:m.jsx(ct,{tooltip:"Refresh",children:m.jsx(JN,{})})})]}),C2=()=>{const e=T.useRadius();return m.jsx(L.MessagePrimitive.Root,{asChild:!0,children:m.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:[m.jsx(N6,{}),m.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[m.jsx("div",{className:T.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:m.jsx(L.MessagePrimitive.Parts,{})}),m.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:m.jsx(j2,{})})]}),m.jsx(m0,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},j2=()=>m.jsx(L.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:m.jsx(L.ActionBarPrimitive.Edit,{asChild:!0,children:m.jsx(ct,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:m.jsx(FN,{})})})}),A2=()=>m.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:m.jsxs(L.ComposerPrimitive.Root,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[m.jsx(L.ComposerPrimitive.Input,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),m.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[m.jsx(L.ComposerPrimitive.Cancel,{asChild:!0,children:m.jsx($t,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),m.jsx(L.ComposerPrimitive.Send,{asChild:!0,children:m.jsx($t,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),m0=({className:e,...t})=>m.jsxs(L.BranchPickerPrimitive.Root,{hideWhenSingleBranch:!0,className:T.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[m.jsx(L.BranchPickerPrimitive.Previous,{asChild:!0,children:m.jsx(ct,{tooltip:"Previous",children:m.jsx(IN,{})})}),m.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[m.jsx(L.BranchPickerPrimitive.Number,{})," / ",m.jsx(L.BranchPickerPrimitive.Count,{})]}),m.jsx(L.BranchPickerPrimitive.Next,{asChild:!0,children:m.jsx(ct,{tooltip:"Next",children:m.jsx(W_,{})})})]}),h0=()=>{const{config:e,isExpanded:t,setIsExpanded:r}=T.useElements(),o=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:r,defaultExpanded:o}},R2={layout:{duration:.25,ease:or}},z2=()=>{const{config:e}=T.useElements(),t=$d(),r=T.useRadius(),o=T.useDensity(),[n,i]=z.useState(e.modal?.defaultOpen??!1),{expandable:a,isExpanded:s,setIsExpanded:l}=h0(),u=e.modal?.title,c=e.modal?.icon,d=e.modal?.position??"bottom-right",f=M2(d),p=z.useMemo(()=>e.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[e.modal?.dimensions?.default]),g=z.useMemo(()=>e.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[e.modal?.dimensions?.expanded]),b=L.useAssistantState(({thread:v})=>v).messages.some(v=>v.status?.type==="running"),y=s?g.width:p.width,x=s?g.height:p.height,$=p.maxHeight;return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsx(Zt.MotionConfig,{reducedMotion:"user",transition:R2,children:m.jsx("div",{className:T.cn("aui-root aui-modal-anchor fixed z-10",f,t.className,r("lg"),n&&"shadow-xl"),children:m.jsx(Zt.AnimatePresence,{mode:"wait",children:n?m.jsxs(Lt.div,{layout:!0,layoutId:"chat-container",className:T.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",r("lg")),initial:!1,style:{originX:d.includes("left")?0:1,originY:d.includes("top")?0:1,width:y,height:x,maxHeight:$},children:[m.jsxs(Lt.div,{className:T.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",o("h-header"),o("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:or},children:[m.jsx("div",{className:T.cn("flex min-w-0 items-center"),children:m.jsxs("span",{className:T.cn("text-md flex items-center gap-2 truncate font-medium",b&&"shimmer"),children:[m.jsx("span",{className:"truncate",children:u}),b&&m.jsx(Oi,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),m.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[a?m.jsx("button",{type:"button",onClick:()=>l(v=>!v),className:T.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":s,"aria-label":s?"Collapse assistant":"Expand assistant",children:s?m.jsx(zN,{strokeWidth:2,className:"size-3.5 rotate-90"}):m.jsx(CN,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,m.jsx("button",{onClick:()=>{i(!1),l(!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 ${u}`,children:m.jsx(Eo,{className:"size-4.5"})})]})]}),m.jsx(Lt.div,{className:"aui-modal-thread w-full flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:or},children:m.jsx(Sd,{})})]},"chat"):m.jsx(Lt.button,{layout:!0,layoutId:"chat-container",onClick:()=>i(!0),className:T.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",r("full")),initial:!1,"aria-label":`Open ${u}`,style:{originX:1,originY:1},children:m.jsx(Lt.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:or},className:"flex size-full items-center justify-center",children:c?c("closed"):m.jsx(AN,{className:"size-6"})})},"button")})})})})};function M2(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:T.assertNever(e)}}const D2=()=>{const{config:e}=T.useElements(),t=$d(),r=e.sidecar??{},{title:o,dimensions:n}=r,{isExpanded:i,setIsExpanded:a}=h0(),l=L.useAssistantState(({thread:u})=>u).messages.some(u=>u.status?.type==="running");return m.jsx(Zt.LazyMotion,{features:Zt.domMax,children:m.jsxs(Lt.div,{initial:{width:n?.default?.width??"400px",height:n?.default?.height??"100vh"},animate:{width:i?n?.expanded?.width??"800px":n?.default?.width??"400px",height:i?n?.expanded?.height??"100%":n?.default?.height??"100vh"},transition:{duration:.3,ease:or},className:T.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",t.className),children:[m.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[m.jsxs("span",{className:T.cn("text-md flex items-center gap-2 font-medium",l&&"shimmer"),children:[o,l&&m.jsx(Oi,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]}),m.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:m.jsx(ct,{tooltip:i?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>a(u=>!u),children:i?m.jsx(DN,{className:"size-4.5"}):m.jsx(LN,{className:"size-4.5"})})})]}),m.jsx("div",{className:"aui-sidecar-content h-[calc(100%-3.5rem)] overflow-hidden",children:m.jsx(Sd,{})})]})})},U2=()=>{const{config:e}=T.useElements();switch(e.variant){case"standalone":return m.jsx(Sd,{});case"sidecar":return m.jsx(D2,{});default:return m.jsx(z2,{})}};exports.useGramElements=T.useElements;exports.Chat=U2;exports.GramElementsProvider=SM;exports.MODELS=Nc;exports.defineFrontendTool=mN;
|
|
158
|
+
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:h.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function M7({content:e}){return h.jsx("div",{className:"w-full",children:e.content.map((t,n)=>{switch(t.type){case"text":{const i=P7(t._meta?.["getgram.ai/mime-type"]??"text/plain"),r=R7(t.text,i);return h.jsx(vA,{text:r,language:i},n)}case"image":return h.jsx(j7,{data:t.data},n);default:return h.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},n)}})})}function my({title:e,content:t,defaultExpanded:n=!1,highlightSyntax:i=!0,language:r="json"}){const[o,a]=$.useState(n),s=O7(t),u=s?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return h.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[h.jsxs("button",{onClick:()=>a(!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:[h.jsx("span",{className:"text-muted-foreground text-sm",children:e}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(N7,{content:u}),h.jsx(cT,{className:_.cn("text-muted-foreground size-4 transition-transform duration-200",o&&"rotate-90")})]})]}),o&&h.jsx("div",{className:"border-border border-t",children:s?h.jsx(M7,{content:t}):i?h.jsx(vA,{text:u,language:r}):h.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:u})})]})}function z7({name:e,icon:t,provider:n,status:i="complete",request:r,result:o,defaultExpanded:a=!1,className:s,onApproveOnce:u,onApproveForSession:l,onDeny:c}){const d=i==="approval"&&u!==void 0&&c!==void 0,[f,p]=$.useState(a),g=r!==void 0||o!==void 0,[m,y]=$.useState("one-time"),[v,x]=$.useState(!1);$.useEffect(()=>{!d&&f&&!a&&p(!1)},[d]);const S=()=>{m==="for-session"&&l?l():u&&u()};return h.jsxs("div",{"data-slot":"tool-ui",className:_.cn("border-border bg-card overflow-hidden rounded-lg border",s),children:[n&&h.jsxs("div",{"data-slot":"tool-ui-provider",className:_.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?h.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):h.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:n.charAt(0).toUpperCase()}),h.jsx("span",{className:"text-sm font-medium",children:n})]}),h.jsxs("button",{onClick:()=>g&&p(!f),disabled:!g,className:_.cn("flex w-full items-center gap-2 px-4 py-3 text-left",g&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[h.jsx(gA,{status:i}),h.jsx("span",{className:_.cn("flex-1 text-sm",!n&&d&&"shimmer"),children:e}),g&&h.jsx(_s,{className:_.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&g&&h.jsxs("div",{"data-slot":"tool-ui-content",children:[r!==void 0&&h.jsx(my,{title:"Arguments",content:r,highlightSyntax:!0,language:"json"}),o!==void 0&&h.jsx(my,{title:"Output",content:o,highlightSyntax:!0,language:"json"})]}),d&&h.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:[h.jsx("div",{children:h.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[h.jsxs(tn,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[h.jsx(Qo,{className:"mr-1 size-3"}),"Deny"]}),h.jsxs("div",{className:"flex items-center",children:[h.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:[h.jsx(Wn,{className:"mr-1 size-3"}),h.jsx("span",{className:"min-w-[110px]",children:m==="one-time"?"Approve this time":"Approve always"})]}),h.jsxs(fA,{open:v,onOpenChange:x,children:[h.jsx(hA,{asChild:!0,children:h.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:h.jsx(_s,{className:"size-3"})})}),h.jsxs(mA,{align:"end",className:"w-64 p-1",sideOffset:4,children:[h.jsxs("button",{onClick:()=>{y("one-time"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[h.jsx(Wn,{className:_.cn("relative top-1 mt-0.5 size-3 shrink-0",m!=="one-time"&&"invisible")}),h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-sm",children:"Approve only once"}),h.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),l&&h.jsxs("button",{onClick:()=>{y("for-session"),x(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[h.jsx(Wn,{className:_.cn("relative top-1 mt-0.5 size-3 shrink-0",m!=="for-session"&&"invisible")}),h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-sm",children:"Approve always"}),h.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function D7({title:e,icon:t,status:n="complete",defaultExpanded:i=!1,children:r,className:o}){const[a,s]=$.useState(i);return h.jsxs("div",{"data-slot":"tool-ui-group",className:_.cn("border-border bg-card overflow-hidden rounded-lg border",o),children:[h.jsxs("button",{onClick:()=>s(!a),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||h.jsx(gA,{status:n==="running"?"running":"complete"}),h.jsx("span",{className:_.cn("flex-1 text-sm font-medium",n==="running"&&"shimmer"),children:e}),h.jsx(_s,{className:_.cn("text-muted-foreground size-4 transition-transform duration-200",a&&"rotate-180")})]}),a&&h.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:r})]})}const U7=({toolName:e,toolCallId:t,status:n,result:i,args:r})=>{const{pendingApprovals:o,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:u}=nk(),l=o.get(t),d=_.useAssistantState(({message:x})=>x).parts.filter(x=>x.type==="tool-call"),f=d.findIndex(x=>x.toolName===e),p=()=>{s(t)},g=()=>{a(e),s(t)},m=()=>{u(t)},y=()=>l?"approval":n.type==="incomplete"?"error":n.type==="complete"?i&&typeof i=="object"&&"isError"in i&&i.isError?"error":"complete":"running",v=()=>{if(i!==void 0)return typeof i=="object"&&i!==null&&"content"in i&&Array.isArray(i.content)||typeof i=="string",i};return h.jsx("div",{className:_.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:h.jsx(z7,{name:e,status:y(),request:r,result:v(),onApproveOnce:l?p:void 0,onApproveForSession:l?g:void 0,onDeny:l?m:void 0,className:"rounded-none border-0"})})},Ch=()=>{const{config:e}=_.useElements(),t=e.theme??{};return $.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])},Gn=[.23,1,.32,1];function L7(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const F7=({children:e})=>{const t=_.useAssistantState(({message:s})=>s).parts,n=t.filter(s=>s.type==="tool-call"),i=n.some(s=>s.status?.type==="running"),{config:r}=_.useElements(),o=r.tools?.expandToolGroupsByDefault??!1,a=$.useMemo(()=>{const s=t.filter(u=>u.type==="tool-call");return s.length===0?"No tools called":s.length===1?`Calling ${L7(s[0].toolName)}...`:i?`Calling ${s.length} tools...`:`Executed ${s.length} tools`},[t,i]);return r.tools?.components?.[n[0]?.toolName]?e:n.length===1?h.jsx("div",{className:_.cn("my-4 w-full max-w-xl"),children:h.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):h.jsx("div",{className:"my-4 w-full max-w-xl",children:h.jsx(D7,{title:a,status:i?"running":"complete",defaultExpanded:o,children:e})})},B7=()=>h.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:[h.jsx("strong",{children:"Warning:"})," You are using an API key directly in the client. Please"," ",h.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"})," ","before deploying to production."]}),Ah=()=>{const e=Ch(),t=_.useDensity(),{config:n}=_.useElements(),i=n.components??{},r=n.api&&"UNSAFE_apiKey"in n.api;return h.jsx($n.LazyMotion,{features:$n.domAnimation,children:h.jsx($n.MotionConfig,{reducedMotion:"user",children:h.jsx(iT,{className:_.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",e.className),children:h.jsxs(aT,{className:_.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",t("p-lg")),children:[h.jsx(no,{empty:!0,children:i.ThreadWelcome?h.jsx(i.ThreadWelcome,{}):h.jsx(q7,{})}),r&&h.jsx(B7,{}),h.jsx(WL,{components:{UserMessage:i.UserMessage??X7,EditComposer:i.EditComposer??tK,AssistantMessage:i.AssistantMessage??K7}}),h.jsx(no,{empty:!1,children:h.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),h.jsx(H7,{})]})})})})},Z7=()=>h.jsx(KL,{asChild:!0,children:h.jsx(Ft,{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:h.jsx(s2,{})})}),q7=()=>{const{config:e}=_.useElements(),t=_.useDensity(),{title:n,subtitle:i}=e.welcome??{},r=e.variant==="standalone";return h.jsxs("div",{className:_.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",r?"items-center justify-center":"",t("gap-lg")),children:[h.jsx("div",{className:_.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:h.jsxs("div",{className:_.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:[h.jsx(En.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:Gn},className:_.cn("aui-thread-welcome-message-motion-1 text-foreground font-semibold",t("text-title")),children:n}),h.jsx(En.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:Gn},className:_.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:i})]})}),h.jsx(V7,{})]})},V7=()=>{const{config:e}=_.useElements(),t=_.useRadius(),n=_.useDensity(),i=e.welcome?.suggestions??[],r=e.variant==="standalone";return i.length===0?null:h.jsx("div",{className:_.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,a)=>h.jsx(En.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*a,ease:Gn},className:_.cn("aui-thread-welcome-suggestion-display",!r&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:h.jsx(QL,{prompt:o.action,send:!0,asChild:!0,children:h.jsxs(tn,{variant:"ghost",className:_.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:[h.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-foreground text-sm font-medium",children:o.title}),h.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:o.label})]})})},`suggested-action-${o.title}-${a}`))})},H7=()=>{const{config:e}=_.useElements(),t=_.useRadius(),n=_.useDensity(),i=e.composer??{placeholder:"Send a message...",attachments:!0},r=e.components??{};return r.Composer?h.jsx(r.Composer,{}):h.jsxs("div",{className:_.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:[h.jsx(Z7,{}),h.jsxs(Of,{className:_.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&&h.jsx(TH,{}),h.jsx(jf,{placeholder:i.placeholder,className:_.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"}),h.jsx(W7,{})]})]})},J7=()=>{const{model:e,setModel:t}=_.useElements(),[n,i]=$.useState(!1),[r,o]=$.useState(!1),a=$.useRef(null),s=$.useRef(0),u=$.useRef(!1);$.useEffect(()=>{n&&!u.current&&requestAnimationFrame(()=>{const c=a.current;c&&c.scrollHeight>0&&(c.scrollTop=s.current)}),u.current=n},[n]),$.useEffect(()=>{n&&o(!1)},[n]);const l=c=>{s.current=c.currentTarget.scrollTop};return h.jsx(W$,{children:h.jsxs(nh,{open:r&&!n,onOpenChange:o,children:[h.jsxs(fA,{open:n,onOpenChange:i,children:[h.jsx(rh,{asChild:!0,children:h.jsx(hA,{asChild:!0,children:h.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:h.jsx(D2,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),h.jsx(mA,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:h.jsx("div",{ref:a,className:"max-h-48 overflow-y-auto",onScroll:l,children:af.map(c=>h.jsxs(tn,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?h.jsx("div",{children:h.jsx(Wn,{className:"size-4 text-emerald-500"})}):h.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),h.jsx(ih,{side:"bottom",align:"start",children:"Model Settings"})]})})},W7=()=>{const{config:e}=_.useElements(),t=_.useRadius(),n=e.composer??{attachments:!0};return h.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[h.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[n.attachments?h.jsx($H,{}):h.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&h.jsx(J7,{})]}),h.jsx(no,{running:!1,children:h.jsx(YE,{asChild:!0,children:h.jsx(Ft,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:_.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:h.jsx(u2,{className:"aui-composer-send-icon size-5"})})})}),h.jsx(no,{running:!0,children:h.jsx(XE,{asChild:!0,children:h.jsx(tn,{type:"button",variant:"default",size:"icon",className:_.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:h.jsx(L2,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},G7=()=>h.jsx(WE,{children:h.jsx(nT,{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:h.jsx(rT,{className:"aui-message-error-message line-clamp-2"})})}),K7=()=>{const{config:e}=_.useElements(),t=e.tools??{},n=e.components??{};return h.jsx(Pf,{asChild:!0,children:h.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:[h.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[h.jsx(Rf,{components:{Text:n.Text??rA,Image:n.Image??Y7,tools:{by_name:t.components,Fallback:n.ToolFallback??U7},Reasoning:n.Reasoning??dA,ReasoningGroup:n.ReasoningGroup??pA,ToolGroup:n.ToolGroup??F7}}),h.jsx(G7,{})]}),h.jsxs("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:[h.jsx(yA,{}),h.jsx(Q7,{})]})]})})},Y7=e=>h.jsx("img",{src:e.image}),Q7=()=>h.jsxs(gf,{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:[h.jsx(Lk,{asChild:!0,children:h.jsxs(Ft,{tooltip:"Copy",children:[h.jsx(ys,{copied:!0,children:h.jsx(Wn,{})}),h.jsx(ys,{copied:!1,children:h.jsx(Mf,{})})]})}),h.jsx(Qz,{asChild:!0,children:h.jsx(Ft,{tooltip:"Refresh",children:h.jsx(M2,{})})})]}),X7=()=>{const e=_.useRadius();return h.jsx(Pf,{asChild:!0,children:h.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:[h.jsx(EH,{}),h.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[h.jsx("div",{className:_.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:h.jsx(Rf,{})}),h.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:h.jsx(eK,{})})]}),h.jsx(yA,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},eK=()=>h.jsx(gf,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:h.jsx(eD,{asChild:!0,children:h.jsx(Ft,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:h.jsx(R2,{})})})}),tK=()=>h.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:h.jsxs(Of,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[h.jsx(jf,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),h.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[h.jsx(XE,{asChild:!0,children:h.jsx(tn,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),h.jsx(YE,{asChild:!0,children:h.jsx(tn,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),yA=({className:e,...t})=>h.jsxs(GE,{hideWhenSingleBranch:!0,className:_.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[h.jsx(nL,{asChild:!0,children:h.jsx(Ft,{tooltip:"Previous",children:h.jsx(m2,{})})}),h.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[h.jsx(UE,{})," / ",h.jsx(DE,{})]}),h.jsx(eL,{asChild:!0,children:h.jsx(Ft,{tooltip:"Next",children:h.jsx(cT,{})})})]}),bA=()=>{const{config:e,isExpanded:t,setIsExpanded:n}=_.useElements(),i=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:n,defaultExpanded:i}},nK={layout:{duration:.25,ease:Gn}},rK=()=>{const{config:e}=_.useElements(),t=Ch(),n=_.useRadius(),i=_.useDensity(),[r,o]=$.useState(e.modal?.defaultOpen??!1),{expandable:a,isExpanded:s,setIsExpanded:u}=bA(),l=e.modal?.title,c=e.modal?.icon,d=e.modal?.position??"bottom-right",f=iK(d),p=$.useMemo(()=>e.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[e.modal?.dimensions?.default]),g=$.useMemo(()=>e.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[e.modal?.dimensions?.expanded]),y=_.useAssistantState(({thread:b})=>b).messages.some(b=>b.status?.type==="running"),v=s?g.width:p.width,x=s?g.height:p.height,S=p.maxHeight;return h.jsx($n.LazyMotion,{features:$n.domMax,children:h.jsx($n.MotionConfig,{reducedMotion:"user",transition:nK,children:h.jsx("div",{className:_.cn("aui-root aui-modal-anchor fixed z-10",f,t.className,n("lg"),r&&"shadow-xl"),children:h.jsx($n.AnimatePresence,{mode:"wait",children:r?h.jsxs(En.div,{layout:!0,layoutId:"chat-container",className:_.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",n("lg")),initial:!1,style:{originX:d.includes("left")?0:1,originY:d.includes("top")?0:1,width:v,height:x,maxHeight:S},children:[h.jsxs(En.div,{className:_.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",i("h-header"),i("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:Gn},children:[h.jsx("div",{className:_.cn("flex min-w-0 items-center"),children:h.jsxs("span",{className:_.cn("text-md flex items-center gap-2 truncate font-medium",y&&"shimmer"),children:[h.jsx("span",{className:"truncate",children:l}),y&&h.jsx(ws,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),h.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[a?h.jsx("button",{type:"button",onClick:()=>u(b=>!b),className:_.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":s,"aria-label":s?"Collapse assistant":"Expand assistant",children:s?h.jsx(E2,{strokeWidth:2,className:"size-3.5 rotate-90"}):h.jsx(x2,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,h.jsx("button",{onClick:()=>{o(!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 ${l}`,children:h.jsx(Qo,{className:"size-4.5"})})]})]}),h.jsx(En.div,{className:"aui-modal-thread w-full flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:Gn},children:h.jsx(Ah,{})})]},"chat"):h.jsx(En.button,{layout:!0,layoutId:"chat-container",onClick:()=>o(!0),className:_.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",n("full")),initial:!1,"aria-label":`Open ${l}`,style:{originX:1,originY:1},children:h.jsx(En.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:Gn},className:"flex size-full items-center justify-center",children:c?c("closed"):h.jsx(I2,{className:"size-6"})})},"button")})})})})};function iK(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:_.assertNever(e)}}const oK=()=>{const{config:e}=_.useElements(),t=Ch(),n=e.sidecar??{},{title:i,dimensions:r}=n,{isExpanded:o,setIsExpanded:a}=bA(),u=_.useAssistantState(({thread:l})=>l).messages.some(l=>l.status?.type==="running");return h.jsx($n.LazyMotion,{features:$n.domMax,children:h.jsxs(En.div,{initial:{width:r?.default?.width??"400px",height:r?.default?.height??"100vh"},animate:{width:o?r?.expanded?.width??"800px":r?.default?.width??"400px",height:o?r?.expanded?.height??"100%":r?.default?.height??"100vh"},transition:{duration:.3,ease:Gn},className:_.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",t.className),children:[h.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[h.jsxs("span",{className:_.cn("text-md flex items-center gap-2 font-medium",u&&"shimmer"),children:[i,u&&h.jsx(ws,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]}),h.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:h.jsx(Ft,{tooltip:o?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>a(l=>!l),children:o?h.jsx($2,{className:"size-4.5"}):h.jsx(A2,{className:"size-4.5"})})})]}),h.jsx("div",{className:"aui-sidecar-content h-[calc(100%-3.5rem)] overflow-hidden",children:h.jsx(Ah,{})})]})})},aK=()=>{const{config:e}=_.useElements();switch(e.variant){case"standalone":return h.jsx(Ah,{});case"sidecar":return h.jsx(oK,{});default:return h.jsx(rK,{})}};exports.useGramElements=_.useElements;exports.Chat=aK;exports.GramElementsProvider=f3;exports.MODELS=af;exports.defineFrontendTool=i2;
|
|
144
159
|
//# sourceMappingURL=elements.cjs.map
|