1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,97311,73957,3591,t=>{"use strict";let r,a,n,i,o,s,l,u,c,d,p;t.s(["BIGINT_FORMAT_RANGES",()=>tC,"CONSTANT_CATCH",()=>ra,"Class",()=>t6,"NUMBER_FORMAT_RANGES",()=>tA,"aborted",()=>tU,"allowsEval",()=>tm,"assert",()=>eX,"assertEqual",()=>eW,"assertIs",()=>eK,"assertNever",()=>eY,"assertNotEqual",()=>eG,"assignProp",()=>te,"attachSchema",()=>tB,"base64ToUint8Array",()=>tX,"base64urlToUint8Array",()=>t0,"cached",()=>e4,"captureStackTrace",()=>th,"cleanEnum",()=>tY,"cleanRegex",()=>e5,"clone",()=>tE,"cloneDef",()=>ts,"codePointLength",()=>tW,"constantCatch",()=>rn,"createTransparentProxy",()=>tx,"defineLazy",()=>e8,"defineLazyInternal",()=>rt,"derived",()=>t8,"esc",()=>td,"escapeRegex",()=>tk,"explicitlyAborted",()=>tL,"extend",()=>tP,"finalizeIssue",()=>tq,"floatSafeRemainder",()=>e9,"getElementAtPath",()=>tl,"getEnumValues",()=>eQ,"getLengthableOrigin",()=>tG,"getParsedType",()=>tb,"getSizableOrigin",()=>tV,"hexToUint8Array",()=>t2,"hide",()=>t3,"installLazyProp",()=>rr,"isObject",()=>tf,"isPlainObject",()=>tg,"issue",()=>tK,"joinValues",()=>e0,"jsonStringifyReplacer",()=>e1,"members",()=>t5,"merge",()=>tN,"mergeDefs",()=>to,"normalizeParams",()=>tS,"nullish",()=>e6,"numKeys",()=>tv,"objectClone",()=>e7,"omit",()=>tR,"optionalKeys",()=>tT,"own",()=>t9,"parsedType",()=>tH,"partial",()=>tj,"pick",()=>tO,"prefixIssues",()=>tF,"primitiveTypes",()=>t_,"promiseAllObject",()=>tu,"propertyKeyTypes",()=>tw,"randomString",()=>tc,"rawShape",()=>tt,"required",()=>tD,"safeExtend",()=>t$,"shallowClone",()=>ty,"slugify",()=>tp,"stringifyPrimitive",()=>tI,"toZod",()=>eH,"uint8ArrayToBase64",()=>tQ,"uint8ArrayToBase64url",()=>t1,"uint8ArrayToHex",()=>t4,"unwrapMessage",()=>tZ],99918);var h,f,m,g,y,v,b,w,_,k,E,S,x,I,T,A,C,O,M,R,P,z,$,N,j,D,U,L,F,Z,B,q,V,J,W,G,H,K,Y,X,Q,ee,et,er,ea,en,ei,eo,es,el,eu,ec=t.i(52889),ed="vercel.ai.error",ep=Symbol.for(ed),eh=class t extends(f=Error,h=ep,f){constructor({name:t,message:r,cause:a}){super(r),this[h]=!0,this.name=t,this.cause=a}static isInstance(r){return t.hasMarker(r,ed)}static hasMarker(t,r){let a=Symbol.for(r);return null!=t&&"object"==typeof t&&a in t&&"boolean"==typeof t[a]&&!0===t[a]}},ef="AI_APICallError",em=`vercel.ai.error.${ef}`,eg=Symbol.for(em),ey=class extends(g=eh,m=eg,g){constructor({message:t,url:r,requestBodyValues:a,statusCode:n,responseHeaders:i,responseBody:o,cause:s,isRetryable:l=null!=n&&(408===n||409===n||429===n||n>=500),data:u}){super({name:ef,message:t,cause:s}),this[m]=!0,this.url=r,this.requestBodyValues=a,this.statusCode=n,this.responseHeaders=i,this.responseBody=o,this.isRetryable=l,this.data=u}static isInstance(t){return eh.hasMarker(t,em)}},ev="AI_EmptyResponseBodyError",eb=`vercel.ai.error.${ev}`,ew=Symbol.for(eb),e_=class extends(v=eh,y=ew,v){constructor({message:t="Empty response body"}={}){super({name:ev,message:t}),this[y]=!0}static isInstance(t){return eh.hasMarker(t,eb)}},ek=Symbol.for("vercel.ai.error.AI_EvaluationUnsupportedQuestionTypeError");function eE(t){return null==t?"unknown error":"string"==typeof t?t:t instanceof Error?t.toString():JSON.stringify(t)}var eS="AI_InvalidArgumentError",ex=`vercel.ai.error.${eS}`,eI=Symbol.for(ex),eT=class extends(w=eh,b=eI,w){constructor({message:t,cause:r,argument:a}){super({name:eS,message:t,cause:r}),this[b]=!0,this.argument=a}static isInstance(t){return eh.hasMarker(t,ex)}},eA=Symbol.for("vercel.ai.error.AI_InvalidPromptError");Symbol.for("vercel.ai.error.AI_InvalidResponseDataError");var eC="AI_JSONParseError",eO=`vercel.ai.error.${eC}`,eM=Symbol.for(eO),eR=class extends(k=eh,_=eM,k){constructor({text:t,cause:r}){super({name:eC,message:`JSON parsing failed: Text: ${t}. 2Error message: ${eE(r)}`,cause:r}),this[_]=!0,this.text=t}static isInstance(t){return eh.hasMarker(t,eO)}},eP=Symbol.for("vercel.ai.error.AI_LoadAPIKeyError");Symbol.for("vercel.ai.error.AI_LoadSettingError");Symbol.for("vercel.ai.error.AI_NoContentGeneratedError");var ez="AI_NoSuchModelError",e$=`vercel.ai.error.${ez}`,eN=Symbol.for(e$),ej=class extends(S=eh,E=eN,S){constructor({errorName:t=ez,modelId:r,modelType:a,message:n=`No such ${a}: ${r}`}){super({name:t,message:n}),this[E]=!0,this.modelId=r,this.modelType=a}static isInstance(t){return eh.hasMarker(t,e$)}}
2,eD=Symbol.for("vercel.ai.error.AI_NoSuchProviderReferenceError");Symbol.for("vercel.ai.error.AI_TooManyEmbeddingValuesForCallError");var eU="AI_TypeValidationError",eL=`vercel.ai.error.${eU}`,eF=Symbol.for(eL),eZ=class t extends(I=eh,x=eF,I){constructor({value:t,cause:r,context:a}){let n="Type validation failed";if((null==a?void 0:a.field)&&(n+=` for ${a.field}`),(null==a?void 0:a.entityName)||(null==a?void 0:a.entityId)){n+=" (";const t=[];a.entityName&&t.push(a.entityName),a.entityId&&t.push(`id: "${a.entityId}"`),n+=t.join(", "),n+=")"}super({name:eU,message:`${n}: Value: ${JSON.stringify(t)}. 3Error message: ${eE(r)}`,cause:r}),this[x]=!0,this.value=t,this.context=a}static isInstance(t){return eh.hasMarker(t,eL)}static wrap({value:r,cause:a,context:n}){var i,o,s;return t.isInstance(a)&&a.value===r&&(null==(i=a.context)?void 0:i.field)===(null==n?void 0:n.field)&&(null==(o=a.context)?void 0:o.entityName)===(null==n?void 0:n.entityName)&&(null==(s=a.context)?void 0:s.entityId)===(null==n?void 0:n.entityId)?a:new t({value:r,cause:a,context:n})}},eB="AI_UnsupportedFunctionalityError",eq=`vercel.ai.error.${eB}`,eV=Symbol.for(eq),eJ=class extends(A=eh,T=eV,A){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:eB,message:r}),this[T]=!0,this.functionality=t}static isInstance(t){return eh.hasMarker(t,eq)}};function eW(t){return t}function eG(t){return t}function eH(){return t=>t}function eK(t){}function eY(t){throw Error("Unexpected value in exhaustive check")}function eX(t){}function eQ(t){let r=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,a])=>-1===r.indexOf(+t)).map(([t,r])=>r)}function e0(t,r="|"){return t.map(t=>tI(t)).join(r)}function e1(t,r){return"bigint"==typeof r?r.toString():r}class e2{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return void 0!==t&&(this._value=t(),this._getter=void 0),this._value}}function e4(t){return new e2(t)}function e6(t){return null==t}function e5(t){let r=+!!t.startsWith("^"),a=t.endsWith("$")?t.length-1:t.length;return t.slice(r,a)}function e9(t,r){let a=t/r,n=Math.round(a),i=4*Number.EPSILON*Math.max(Math.abs(a),1);return Math.abs(a-n)<i?0:a-n}let e3=Symbol("evaluating");function e8(t,r,a){let n;
3Object.defineProperty(t,r,{get(){if(n!==e3)return void 0===n&&(n=e3,n=a()),n},set(a){Object.defineProperty(t,r,{value:a})},configurable:!0})}function e7(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function te(t,r,a){Object.defineProperty(t,r,{value:a,writable:!0,enumerable:!0,configurable:!0})}function tt(t){let r=Object.getOwnPropertyDescriptor(t,"shape");return r?.get?r.get.raw:r?.value}function tr(t){return tt(t._zod.def)??t._zod.def.shape}function ta(t,r,a){Object.defineProperty(t,r,{get(){let t=a();return te(this,r,t),t},enumerable:!0,configurable:!0})}function tn(t,r,a){r in t?te(t,r,a):t[r]=a}function ti(t,r,a,n){let i=tr(r);for(let o of a){let a=Object.getOwnPropertyDescriptor(i,o);a.enumerable&&(a.get?ta(t,o,()=>{let t=r._zod.def.shape[o];return n?n(t,o):t}):tn(t,o,n?n(a.value,o):a.value))}}function to(...t){let r={};for(let a of t)Object.assign(r,Object.getOwnPropertyDescriptors(a));return Object.defineProperties({},r)}function ts(t){return to(t._zod.def)}function tl(t,r){return r?r.reduce((t,r)=>t?.[r],t):t}function tu(t){let r=Object.keys(t);return Promise.all(r.map(r=>t[r])).then(t=>{let a={};for(let n=0;n<r.length;n++)a[r[n]]=t[n];return a})}function tc(t=10){let r="abcdefghijklmnopqrstuvwxyz",a="";for(let n=0;n<t;n++)a+=r[Math.floor(Math.random()*r.length)];return a}function td(t){return JSON.stringify(t)}function tp(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}let th="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function tf(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let tm=e4(()=>{if(rc.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(t){return!1}});function tg(t){if(!1===tf(t))return!1;let r=t.constructor;if(void 0===r||"function"!=typeof r)return!0;let a=r.prototype;return!1!==tf(a)&&!1!==Object.prototype.hasOwnProperty.call(a,"isPrototypeOf")}function ty(t){return tg(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function tv(t){let r=0;for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&r++;return r}let tb=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(t))return"array";if(null===t)return"null";if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return"promise";if("u">typeof Map&&t instanceof Map)return"map";if("u">typeof Set&&t instanceof Set)return"set";if("u">typeof Date&&t instanceof Date)return"date";if("u">typeof File&&t instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${r}`)}},tw=new Set(["string","number","symbol"]),t_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function tk(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tE(t,r,a){let n=new t._zod.constr(r??t._zod.def);return(!r||a?.parent)&&(n._zod.parent=t),n}function tS(t){if(!t)return{};if("string"==typeof t)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return(delete t.message,"string"==typeof t.error)?{...t,error:()=>t.error}:t}function tx(t){let r;return new Proxy({},{get:(a,n,i)=>(r??(r=t()),Reflect.get(r,n,i)),set:(a,n,i,o)=>(r??(r=t()),Reflect.set(r,n,i,o)),has:(a,n)=>(r??(r=t()),Reflect.has(r,n)),deleteProperty:(a,n)=>(r??(r=t()),Reflect.deleteProperty(r,n)),ownKeys:a=>(r??(r=t()),Reflect.ownKeys(r)),getOwnPropertyDescriptor:(a,n)=>(r??(r=t()),Reflect.getOwnPropertyDescriptor(r,n)),defineProperty:(a,n,i)=>(r??(r=t()),Reflect.defineProperty(r,n,i))})}function tI(t){return"bigint"==typeof t?t.toString()+"n":"string"==typeof t?`"${t}"`:`${t}`}function tT(t){return Object.keys(t).filter(r=>void 0!==t[r]._zod.optin&&"optional"===t[r]._zod.optout)}let tA={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tC={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function tO(t,r){let a=t._zod.def,n=a.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return ti(i,t,tM(t,r)),tE(t,to(a,{shape:i,checks:[]}))}function tM(t,r){let a=tr(t),n=[];for(let t of Reflect.ownKeys(r)){if(!Object.getOwnPropertyDescriptor(a,t)?.enumerable)throw Error(`Unrecognized key: "${String(t)}"`);r[t]&&n.push(t)}return n}function tR(t,r){let a=t._zod.def,n=a.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(tM(t,r)),o={};return ti(o,t,Reflect.ownKeys(tr(t)).filter(t=>!i.has(t))),tE(t,to(a,{shape:o,checks:[]}))}function tP(t,r){if(!tg(r))throw Error("Invalid input to extend: expected a plain object");let a=t._zod.def.checks;if(a&&a.length>0){let a=tr(t);for(let t of Reflect.ownKeys(r))if(void 0!==Object.getOwnPropertyDescriptor(a,t))throw Error("Cannot over
3write keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return tE(t,to(t._zod.def,{shape:tz(t,r)}))}function tz(t,r){let a={};ti(a,t,Reflect.ownKeys(tr(t)));for(let t of Reflect.ownKeys(r)){let n=Object.getOwnPropertyDescriptor(r,t);n.enumerable&&(n.get?ta(a,t,()=>r[t]):tn(a,t,n.value))}return a}function t$(t,r){if(!tg(r))throw Error("Invalid input to safeExtend: expected a plain object");return tE(t,to(t._zod.def,{shape:tz(t,r)}))}function tN(t,r){if(!r?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(t._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let a={};ti(a,t,Reflect.ownKeys(tr(t))),ti(a,r,Reflect.ownKeys(tr(r)));let n=to(t._zod.def,{shape:a,get catchall(){return r._zod.def.catchall},checks:r._zod.def.checks??[]});return tE(t,n)}function tj(t,r,a,n="partial"){let i=r._zod.def.checks;if(i&&i.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let o=a?new Set(tM(r,a)):void 0,s={};return ti(s,r,Reflect.ownKeys(tr(r)),t&&((r,a)=>o&&!o.has(a)?r:new t({type:"optional",innerType:r}))),tE(r,to(r._zod.def,{shape:s,checks:[]}))}function tD(t,r,a){let n=a?new Set(tM(r,a)):void 0,i={};return ti(i,r,Reflect.ownKeys(tr(r)),(r,a)=>n&&!n.has(a)?r:new t({type:"nonoptional",innerType:r})),tE(r,to(r._zod.def,{shape:i}))}function tU(t,r=0){if(!0===t.aborted)return!0;for(let a=r;a<t.issues.length;a++)if(t.issues[a]?.continue!==!0)return!0;return!1}function tL(t,r=0){if(!0===t.aborted)return!0;for(let a=r;a<t.issues.length;a++)if(t.issues[a]?.continue===!1)return!0;return!1}function tF(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function tZ(t){return"string"==typeof t?t:t?.message}function tB(t,r,a){var n;for(let i=r;i<t.length;i++)(n=t[i]).schema??(n.schema=a)}function tq(t,r,a){let n=t.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?t.schema??(t.schema=t.inst):t.schema=t.inst);let i=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,o=t.message?t.message:tZ(t.inst?._zod.def?.error?.(t))??tZ(i?.(t))??tZ(r?.error?.(t))??tZ(a.customError?.(t))??tZ(a.localeError?.(t))??"Invalid input",s={};for(let r of Object.keys(t))"inst"!==r&&"schema"!==r&&"continue"!==r&&"input"!==r&&"__proto__"!==r&&(s[r]=t[r]);return s.path??(s.path=[]),s.message=o,r?.reportInput&&(s.input=t.input),s}function tV(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}let tJ=/[\uD800-\uDBFF]/;function tW(t){let r=t.length;if(!tJ.test(t))return r;let a=r;for(let n=0;n<r-1;n++)(64512&t.charCodeAt(n))==55296&&(64512&t.charCodeAt(n+1))==56320&&(a--,n++);return a}function tG(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function tH(t){let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"nan":"number";case"object":if(null===t)return"null";if(Array.isArray(t))return"array";if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}return r}function tK(...t){let[r,a,n]=t;return"string"==typeof r?{message:r,code:"custom",input:a,inst:n}:{...r}}function tY(t){return Object.entries(t).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function tX(t){let r=atob(t),a=new Uint8Array(r.length);for(let t=0;t<r.length;t++)a[t]=r.charCodeAt(t);return a}function tQ(t){let r="";for(let a=0;a<t.length;a++)r+=String.fromCharCode(t[a]);return btoa(r)}function t0(t){let r=t.replace(/-/g,"+").replace(/_/g,"/"),a="=".repeat((4-r.length%4)%4);return tX(r+a)}function t1(t){return tQ(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function t2(t){let r=t.replace(/^0x/,"");if(r.length%2!=0)throw Error("Invalid hex string length");let a=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)a[t/2]=Number.parseInt(r.slice(t,t+2),16);return a}function t4(t){return Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("")}class t6{constructor(...t){}}function t5(t,r){for(let a in r){let n=Object.getOwnPropertyDescriptor(r,a);n.get?Object.defineProperty(t,a,{...n,enumerable:!1}):function(t,r,a){Object.defineProperty(t,r,{configurable:!0,get(){return this==null?a:t9(this,r,a.bind(this))},set(t){t9(this,r,t)}})}(t,a,n.value)}}function t9(t,r,a,n=!0){return Object.defineProperty(t,r,{configurable:!0,writable:!0,enumerable:n,value:a}),a}function t3(t,r,a){return t9(t,r,a,!1)}function t8(t,r){for(let a in t){let n=t[a];Object.defineProperty(r,a,{configurable:!0,enumerable:!0,get(){return t9(this,a,n(this))},set(t){t9(this,a,t)}})}return r}let t7=!1,re={configurable:!0,get(){t7=!0}};function rt(t,a,n){let i=Object.getPrototypeOf(t._zod);if(a in i&&r!==t._zod){r=void 0;return}r=t._zod,Object.defineProperty(i,a,{configurable:!0,get(){Object.defineProperty(this,a,re);let t=t7;t7=!1;try{let r=n(this);return t7?delete this[a]:Object.defineProperty(this,a,{configurable:!0,writable:!0,value:r}),t7=t7||t,r}catch(r){throw delete this[a],t7=t7||t,r}},set(t){Object.defineProperty(this,a,{configurable:!0,writable:!0,value:t})}})}function rr(t,r,a,n){let i,o=r in(i=Object.getPrototypeOf(t))?void 0:i;o&&Object.defineProperty(o,r,{configurable:!0,get(){let t={configurable:!0,writable:!0,enumerable:n,value:void 0};
3return Object.defineProperty(this,r,t),t.value=a(this),Object.defineProperty(this,r,t),t.value},set(t){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:n,value:t})}})}let ra="~constantCatch";function rn(t){let r=()=>t;return r[ra]=!0,r}let ri={value:void 0,enumerable:!1},ro="captureStackTrace"in Error?Error:null;function rs(t,r,a,n){function i(t){this.def=t,this.constr=c,this.traits=new Set}i.prototype={};let o=a&&new WeakSet;function s(n,s){if(n._zod){if(n._zod.traits.has(t))return}else{ri.value=new i(s);try{Object.defineProperty(n,"_zod",ri)}finally{ri.value=void 0}}if(n._zod.traits.add(t),r(n,s),o){let t=Object.getPrototypeOf(n),r=n._zod.constr.prototype,i=t;for(;i&&i!==r;)i=Object.getPrototypeOf(i);let s=i??t;o.has(s)||(o.add(s),t5(s,a))}let l=c.prototype;for(let t in l)Object.prototype.hasOwnProperty.call(l,t)&&(t in n||(n[t]=l[t].bind(n)))}let l=n?.Parent??Object;class u extends l{}function c(t){let r=n?.Parent?function(t){let r=ro;if(r){let a=r.stackTraceLimit;if("number"==typeof a){try{r.stackTraceLimit=0}catch{return ro=null,new t}try{return new t}finally{r.stackTraceLimit=a}}}return new t}(u):this;s(r,t);let a=r._zod.deferred;if(a){for(let t of a)t();r._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(r),r}return Object.defineProperty(u,"name",{value:t}),Object.defineProperty(c,"init",{value:s}),Object.defineProperty(c,Symbol.hasInstance,{value:r=>!!n?.Parent&&r instanceof n.Parent||r?._zod?.traits?.has(t)}),Object.defineProperty(c,"name",{value:t}),c}class rl extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ru extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(C=globalThis).__zod_globalConfig??(C.__zod_globalConfig={});let rc=globalThis.__zod_globalConfig;function rd(t){return t&&Object.assign(rc,t),rc}let rp={get:function(){let t=this._zod;return t.message??(t.message=JSON.stringify(t.def,e1,2)),t.message},set:function(t){this._zod.message=t},enumerable:!0,configurable:!0},rh={value:void 0,enumerable:!1},rf=new WeakSet([Object.prototype,Error.prototype]),rm=(t,r)=>{t.name="$ZodError",rh.value=r,Object.defineProperty(t,"issues",rh),rh.value=void 0,Object.defineProperty(t,"message",rp);let a=Object.getPrototypeOf(t);rf.has(a)||(rf.add(a),Object.defineProperty(a,"toString",{configurable:!0,enumerable:!1,get(){let t=()=>this.message;return Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0})}}))},rg=rs("$ZodError",rm),ry=rs("$ZodError",rm,void 0,{Parent:Error});function rv(t,r){return{callee:r?.callee??t,Err:r?.Err}}let rb=t=>{let r=(a,n,i,o)=>{let s=i?{...i,async:!1}:{async:!1},l=a._zod.run({value:n,issues:[]},s);if(l instanceof Promise)throw new rl;if(l.issues.length){let a=new(o?.Err??t)(l.issues.map(t=>tq(t,s,rd())));throw th(a,o?.callee??r),a}return l.value};return r},rw=rb(ry),r_=t=>{let r=async(a,n,i,o)=>{let s=i?{...i,async:!0}:{async:!0},l=a._zod.run({value:n,issues:[]},s);if(l instanceof Promise&&(l=await l),l.issues.length){let a=new(o?.Err??t)(l.issues.map(t=>tq(t,s,rd())));throw th(a,o?.callee??r),a}return l.value};return r},rk=r_(ry),rE=t=>(r,a,n)=>{let i=n?{...n,async:!1}:{async:!1},o=r._zod.run({value:a,issues:[]},i);if(o instanceof Promise)throw new rl;return o.issues.length?rS(t,o.issues,i):{success:!0,data:o.value}};function rS(t,r,a){let n;return{success:!1,get error(){return n||(n=new t(r.map(t=>tq(t,a,rd()))),r=void 0,a=void 0),n},set error(e){n=e,r=void 0,a=void 0}}}let rx=t=>async(r,a,n)=>{let i=n?{...n,async:!0}:{async:!0},o=r._zod.run({value:a,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?rS(t,o.issues,i):{success:!0,data:o.value}},rI=Symbol.for("zod.compile.invalid"),rT=Symbol.for("zod.compile.fallback"),rA=async(t,r,a)=>{let n=a?{...a,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),0===i.issues.length},rC=new WeakSet([Object.prototype,Error.prototype]);function rO(t,r,a){Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){let t=a(this);return Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0})}})}let rM=rs("ZodError",(t,r)=>{rg.init(t,r),t.name="ZodError";let a=Object.getPrototypeOf(t);rC.has(a)||(rC.add(a),rO(a,"format",t=>r=>(function(t,r=t=>t.message){let a={_errors:[]},n=(t,i=[])=>{for(let o of t.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(t=>n({issues:t},[...i,...o.path]));else if("invalid_key"===o.code)n({issues:o.issues},[...i,...o.path]);else if("invalid_element"===o.code)n({issues:o.issues},[...i,...o.path]);else{let t=[...i,...o.path];
3if(0===t.length)a._errors.push(r(o));else{let n=a,i=0;for(;i<t.length;){let a=t[i],s=i===t.length-1;if("_errors"===a){s&&n._errors.push(r(o)),i++;continue}Object.prototype.hasOwnProperty.call(n,a)||Object.defineProperty(n,a,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let l=n[a];s&&l._errors.push(r(o)),n=l,i++}}}};return n(t),a})(t,r)),rO(a,"flatten",t=>r=>(function(t,r=t=>t.message){let a={},n=[];for(let s of t.issues)if(s.path.length>0){var i,o;(i=s.path[0],o=()=>[],!Object.prototype.hasOwnProperty.call(a,i)&&("__proto__"===i?Object.defineProperty(a,i,{value:o(),writable:!0,enumerable:!0,configurable:!0}):a[i]=o()),a[i]).push(r(s))}else n.push(r(s));return{formErrors:n,fieldErrors:a}})(t,r)),rO(a,"addIssue",t=>r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,e1,2)}),rO(a,"addIssues",t=>r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,e1,2)}),Object.defineProperty(a,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),rR=rb(rM),rP=r_(rM),rz=rE(rM),r$=rx(rM),rN=(n=rb(rM),i=(t,r,a,o)=>n(t,r,a?{...a,direction:"backward"}:{direction:"backward"},rv(i,o))),rj=(o=rb(rM),s=(t,r,a,n)=>o(t,r,a,rv(s,n))),rD=(l=r_(rM),u=async(t,r,a,n)=>{let i=a?{...a,direction:"backward"}:{direction:"backward"};return await l(t,r,i,rv(u,n))}),rU=(c=r_(rM),d=async(t,r,a,n)=>await c(t,r,a,rv(d,n))),rL=(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return rE(rM)(t,r,n)},rF=(t,r,a)=>rE(rM)(t,r,a),rZ=async(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return rx(rM)(t,r,n)},rB=async(t,r,a)=>rx(rM)(t,r,a),rq=/^[cC][0-9a-z]{6,}$/,rV=/^[0-9a-z]+$/,rJ=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,rW=/^[0-9a-vA-V]{20}$/,rG=/^[A-Za-z0-9]{27}$/,rH=/^[a-zA-Z0-9_-]{21}$/;function rK(t){return RegExp(`^[a-zA-Z0-9_-]{${t}}$`)}let rY=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,rX=/^([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})$/,rQ=t=>t?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,r0=rQ(4),r1=rQ(6),r2=rQ(7),r4=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,r6=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;function r5(){return RegExp("^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")}let r9=/^(?:(?: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])$/,r3=/^(([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}|:))$/,r8=t=>{let r=tk(t??":");return RegExp(`^(?:[0-9A-F]{2}${r}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${r}){5}[0-9a-f]{2}$`)},r7=/^((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])$/,ae=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,at=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ar=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,aa=/^https?$/,an=/^\+[1-9]\d{6,14}$/,ai=/^\d(?:[ -]?\d){11,18}$/,ao=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,as="(?:(?:\\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])))",al=RegExp(`^${as}$`);function au(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof t.precision?-1===t.precision?`${r}`:0===t.precision?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:t.seconds?`${r}:[0-5]\\d(?:\\.\\d+)?`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ac(t){return RegExp(`^${au(t)}$`)}function ad(t){let r=["Z"];t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let a=`${au({precision:t.precision,seconds:!0})}(?:${r.join("|")})`,n=t.local?`${a}|${au({precision:t.precision})}`:a;return RegExp(`^${as}T(?:${n})$`)}let ap=/^[\s\S]{0,}$/,ah=t=>{let r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${r}$`)},af=/^-?\d+n?$/,am=/^-?\d+$/,ag=/^-?\d+(?:\.\d+)?$/,ay=/^(?:true|false)$/i,av=/^null$/i,ab=/^undefined$/i,aw=/^[^A-Z]*$/,a_=/^[^a-z]*$/;function ak(t,r){return RegExp(`^[A-Za-z0-9+/]{${t}}${r}$`)}function aE(t){return RegExp(`^[A-Za-z0-9_-]{${t}}$`)}
3let aS=ak(22,"=="),ax=aE(22),aI=ak(27,"="),aT=aE(27),aA=ak(43,"="),aC=aE(43),aO=ak(64,""),aM=aE(64),aR=ak(86,"=="),aP=aE(86);t.s(["anyString",0,ap,"base64",0,at,"base64url",0,ar,"bigint",0,af,"boolean",0,ay,"browserEmail",0,/^[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])?)*$/,"cidrv4",0,r7,"cidrv6",0,ae,"creditCard",0,ai,"cuid",0,rq,"cuid2",0,rV,"currencyCode",0,/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,"date",0,al,"datetime",0,ad,"domain",0,/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,"duration",0,rY,"e164",0,an,"email",0,r4,"emoji",0,r5,"extendedDuration",0,/^[-+]?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)?)??$/,"guid",0,rX,"hex",0,/^[0-9a-fA-F]*$/,"hostname",0,/^(?=.{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])?)*\.?$/,"html5Email",0,/^[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])?)*$/,"httpProtocol",0,aa,"iban",0,ao,"idnEmail",0,r6,"integer",0,am,"ipv4",0,r9,"ipv6",0,r3,"ksuid",0,rG,"lowercase",0,aw,"mac",0,r8,"md5_base64",0,aS,"md5_base64url",0,ax,"md5_hex",0,/^[0-9a-fA-F]{32}$/,"nanoid",0,rH,"nanoidOfLength",0,rK,"null",0,av,"number",0,ag,"rfc5322Email",0,/^(([^<>()\[\]\\.,;:\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,}))$/,"sha1_base64",0,aI,"sha1_base64url",0,aT,"sha1_hex",0,/^[0-9a-fA-F]{40}$/,"sha256_base64",0,aA,"sha256_base64url",0,aC,"sha256_hex",0,/^[0-9a-fA-F]{64}$/,"sha384_base64",0,aO,"sha384_base64url",0,aM,"sha384_hex",0,/^[0-9a-fA-F]{96}$/,"sha512_base64",0,aR,"sha512_base64url",0,aP,"sha512_hex",0,/^[0-9a-fA-F]{128}$/,"string",0,ah,"time",0,ac,"ulid",0,rJ,"undefined",0,ab,"unicodeEmail",0,r6,"uppercase",0,a_,"uuid",0,rQ,"uuid4",0,r0,"uuid6",0,r1,"uuid7",0,r2,"xid",0,rW],15417);let az=rs("$ZodCheck",(t,r)=>{var a;t._zod??(t._zod={}),t._zod.def=r,(a=t._zod).onattach??(a.onattach=[])}),a$=t=>{let r=t.value;return!e6(r)&&void 0!==r.size},aN=t=>{let r=t.value;return!e6(r)&&void 0!==r.length},aj={number:"number",bigint:"bigint",object:"date"},aD=rs("$ZodCheckLessThan",(t,r)=>{az.init(t,r);let a=aj[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value<=r.value:n.value<r.value)||n.issues.push({origin:aj[typeof n.value]??a,code:"too_big",maximum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),aU=rs("$ZodCheckGreaterThan",(t,r)=>{az.init(t,r);let a=aj[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value>=r.value:n.value>r.value)||n.issues.push({origin:aj[typeof n.value]??a,code:"too_small",minimum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),aL=rs("$ZodCheckMultipleOf",(t,r)=>{az.init(t,r),t._zod.check=a=>{if(typeof a.value!=typeof r.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof a.value?r.value!==BigInt(0)&&a.value%r.value===BigInt(0):0===e9(a.value,r.value))||a.issues.push({origin:typeof a.value,code:"not_multiple_of",divisor:r.value,input:a.value,inst:t,continue:!r.abort})}}),aF=rs("$ZodCheckNumberFormat",(t,r)=>{az.init(t,r),r.format=r.format||"float64";let a=r.format?.includes("int"),n=a?"int":"number",[i,o]=tA[r.format];t._zod.check=s=>{let l=s.value;if(a){if(!Number.isInteger(l))return void s.issues.push({expected:n,format:r.format,code:"invalid_type",continue:!1,input:l,inst:t});if(!Number.isSafeInteger(l))return void(l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,
3continue:!r.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!r.abort}))}l<i&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!r.abort}),l>o&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!r.abort})}}),aZ=rs("$ZodCheckBigIntFormat",(t,r)=>{az.init(t,r);let[a,n]=tC[r.format];t._zod.check=i=>{let o=i.value;o<a&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:a,inclusive:!0,inst:t,continue:!r.abort}),o>n&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!r.abort})}}),aB=rs("$ZodCheckMaxSize",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=a$),t._zod.check=a=>{let n=a.value;n.size<=r.maximum||a.issues.push({origin:tV(n),code:"too_big",maximum:r.maximum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),aq=rs("$ZodCheckMinSize",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=a$),t._zod.check=a=>{let n=a.value;n.size>=r.minimum||a.issues.push({origin:tV(n),code:"too_small",minimum:r.minimum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),aV=rs("$ZodCheckSizeEquals",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=a$),t._zod.check=a=>{let n=a.value,i=n.size;if(i===r.size)return;let o=i>r.size;a.issues.push({origin:tV(n),...o?{code:"too_big",maximum:r.size}:{code:"too_small",minimum:r.size},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!r.abort})}}),aJ=rs("$ZodCheckMaxLength",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=aN),t._zod.check=a=>{let n=a.value,i=n.length;if(("string"==typeof n&&i>r.maximum?tW(n):i)<=r.maximum)return;let o=tG(n);a.issues.push({origin:o,code:"too_big",maximum:r.maximum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),aW=rs("$ZodCheckMinLength",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=aN),t._zod.check=a=>{let n=a.value,i=n.length;if(("string"==typeof n&&i>=r.minimum&&i<2*r.minimum?tW(n):i)>=r.minimum)return;let o=tG(n);a.issues.push({origin:o,code:"too_small",minimum:r.minimum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),aG=rs("$ZodCheckLengthEquals",(t,r)=>{var a;az.init(t,r),(a=t._zod.def).when??(a.when=aN),t._zod.check=a=>{let n=a.value,i=n.length,o="string"==typeof n&&i>=r.length&&i<=2*r.length?tW(n):i;if(o===r.length)return;let s=tG(n),l=o>r.length;a.issues.push({origin:s,...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!r.abort})}}),aH=rs("$ZodCheckStringFormat",(t,r)=>{var a,n;az.init(t,r),r.pattern?(a=t._zod).check??(a.check=a=>{r.pattern.lastIndex=0,r.pattern.test(a.value)||a.issues.push({origin:"string",code:"invalid_format",format:r.format,input:a.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(n=t._zod).check??(n.check=()=>{})}),aK=rs("$ZodCheckRegex",(t,r)=>{aH.init(t,r),t._zod.check=a=>{r.pattern.lastIndex=0,r.pattern.test(a.value)||a.issues.push({origin:"string",code:"invalid_format",format:"regex",input:a.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),aY=rs("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=aw),aH.init(t,r)}),aX=rs("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=a_),aH.init(t,r)}),aQ=rs("$ZodCheckIncludes",(t,r)=>{az.init(t,r);let a=tk(r.includes),n=new RegExp("number"==typeof r.position?`^.{${r.position},}${a}`:a);r.pattern=n,t._zod.check=a=>{a.value.includes(r.includes,r.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:a.value,inst:t,continue:!r.abort})}}),a0=rs("$ZodCheckStartsWith",(t,r)=>{az.init(t,r);let a=RegExp(`^${tk(r.prefix)}.*`);r.pattern??(r.pattern=a),t._zod.check=a=>{a.value.startsWith(r.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:a.value,inst:t,continue:!r.abort})}}),a1=rs("$ZodCheckEndsWith",(t,r)=>{az.init(t,r);let a=RegExp(`.*${tk(r.suffix)}$`);r.pattern??(r.pattern=a),t._zod.check=a=>{a.value.endsWith(r.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input
3:a.value,inst:t,continue:!r.abort})}});function a2(t,r,a){t.issues.length&&r.issues.push(...tF(a,t.issues))}let a4=rs("$ZodCheckProperties",(t,r)=>{let a;az.init(t,r),t3(t,Symbol.iterator,function*(){yield t}),t._zod.check=n=>{let i;if(null==n.value)return void n.issues.push({expected:"object",code:"invalid_type",input:n.value,inst:t});a??(a=Reflect.ownKeys(r.shape).map(t=>[t,r.shape[t]]));let o=n.value;for(let[t,r]of a){let a=r._zod.run({value:o[t],issues:[]},{});a instanceof Promise?(i??(i=[]),i.push(a.then(r=>a2(r,n,t)))):a2(a,n,t)}if(i)return Promise.all(i).then(()=>void 0)}}),a6=((t,r)=>{az.init(t,r);let a=new Set(r.mime);t._zod.check=n=>{a.has(n.value.type)||n.issues.push({code:"invalid_value",values:r.mime,input:n.value.type,inst:t,continue:!r.abort})}},rs("$ZodCheckOverwrite",(t,r)=>{az.init(t,r),t._zod.check=t=>{t.value=r.tx(t.value)}}));class a5{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if("function"==typeof t){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split("\n").filter(t=>t),a=Math.min(...r.map(t=>t.length-t.trimStart().length));for(let t of r.map(t=>t.slice(a)).map(t=>" ".repeat(2*this.indent)+t))this.content.push(t)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) { 4${r.join("\n")} 5};`)(...Object.values(this.closed))}}let a9={major:4,minor:6,patch:5},a3=rs("$ZodType",(t,r)=>{var a;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=a9;let n=t._zod.def.checks,i=t._zod.traits.has("$ZodCheck")?[t,...n??[]]:n?.length?[...n]:[];for(let r of i)for(let a of r._zod.onattach)a(t);if(0===i.length)(a=t._zod).deferred??(a.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(r,a,n)=>{let i;if(r.memo)return r;let o=tU(r);for(let s of a){if(s._zod.def.when){if(tL(r)||!s._zod.def.when(r))continue}else if(o)continue;let a=r.issues.length,l=s._zod.check(r);if(l instanceof Promise&&n?.async===!1)throw new rl;if(i||l instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await l,r.issues.length!==a&&(tB(r.issues,a,t),o||(o=tU(r,a)))});else{if(r.issues.length===a)continue;tB(r.issues,a,t),o||(o=tU(r,a))}}return i?i.then(()=>r):r},a=(a,n,o)=>{if(tU(a))return a.aborted=!0,a;let s=r(n,i,o);if(s instanceof Promise){if(!1===o.async)throw new rl;return s.then(r=>t._zod.parse(r,o))}return t._zod.parse(s,o)};t._zod.run=(n,o)=>{if(o.skipChecks)return t._zod.parse(n,o);if("backward"===o.direction){let r=t._zod.parse({value:n.value,issues:[]},{...o,skipChecks:!0});return r instanceof Promise?r.then(t=>a(t,n,o)):a(r,n,o)}let s=t._zod.parse(n,o);if(s instanceof Promise){if(!1===o.async)throw new rl;return s.then(t=>r(t,i,o))}return r(s,i,o)}}},{get"~standard"(){return t3(this,"~standard",ne(this))},set"~standard"(value){t9(this,"~standard",value)}}),a8=(t,r)=>t.issues.length?{issues:t.issues.map(t=>tq(t,r,rd()))}:{value:t.value};async function a7(t,r){let a={async:!0};return a8(await t._zod.run({value:r,issues:[]},a),a)}function ne(t){return{validate:r=>{let a={async:!1};try{let n=t._zod.run({value:r,issues:[]},a);if(!(n instanceof Promise))return a8(n,a)}catch(t){}return a7(t,r)},vendor:"zod",version:1}}let nt=rs("$ZodString",(t,r)=>{a3.init(t,r),t._zod.pattern=r.pattern??ap,t._zod.parse=(a,n)=>{if(r.coerce)try{a.value=String(a.value)}catch(t){}return"string"==typeof a.value||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),nr=rs("$ZodStringFormat",(t,r)=>{aH.init(t,r),nt.init(t,r)}),na=rs("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=rX),nr.init(t,r)}),nn=rs("$ZodUUID",(t,r)=>{if(r.version){let t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(void 0===t)throw Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=rQ(t))}else r.pattern??(r.pattern=rQ());nr.init(t,r)}),ni=rs("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=r4),nr.init(t,r)});function no(t){try{if("u">typeof URL&&"function"==typeof URL.canParse)return URL.canParse(t);return new URL(t),!0}catch{return!1}}let ns=/[\t\n\r]/g;function nl(t){return t.replace(ns,"")}let nu=rs("$ZodURL",(t,r)=>{nr.init(t,r),t._zod.check=a=>{try{var n,i;let o=a.value.trim(),s="normalize"in r||"hostname"in r||"protocol"in r?function(t,r){if(!r.normalize&&r.protocol?.source===aa.source&&!/^https?:\/\//i.test(t))return 1;try{if("u">typeof URL){let r=URL;if("function"==typeof r.parse)return r.parse(t)??2}return new URL(t)}catch{return 2}}(o,r):no(o)||2;if(1===s)return void a.issues.push({code:"invalid_format",format:"url",n
5ote:"Invalid URL format",input:a.value,inst:t,continue:!r.abort});if(2===s)return void a.issues.push({code:"invalid_format",format:"url",input:a.value,inst:t,continue:!r.abort});if(!0===s){a.value=nl(o);return}r.hostname&&((n=r.hostname).lastIndex=0,!n.test(s.hostname))&&a.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:r.hostname.source,input:a.value,inst:t,continue:!r.abort}),r.protocol&&((i=r.protocol).lastIndex=0,!i.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol))&&a.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:a.value,inst:t,continue:!r.abort}),a.value=r.normalize?s.href:nl(o);return}catch(n){a.issues.push({code:"invalid_format",format:"url",input:a.value,inst:t,continue:!r.abort})}}}),nc=rs("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=r5()),nr.init(t,r)}),nd=rs("$ZodNanoID",(t,r)=>{if(void 0!==r.length&&(!Number.isInteger(r.length)||r.length<1))throw Error(`Invalid nanoid length: ${r.length}`);r.pattern??(r.pattern=void 0===r.length?rH:rK(r.length)),nr.init(t,r)}),np=rs("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=rq),nr.init(t,r)}),nh=rs("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=rV),nr.init(t,r)}),nf=rs("$ZodULID",(t,r)=>{r.pattern??(r.pattern=rJ),nr.init(t,r)}),nm=rs("$ZodXID",(t,r)=>{r.pattern??(r.pattern=rW),nr.init(t,r)}),ng=rs("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=rG),nr.init(t,r)}),ny=rs("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=ad(r)),nr.init(t,r)}),nv=rs("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=al),nr.init(t,r)}),nb=rs("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=ac(r)),nr.init(t,r)}),nw=rs("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=rY),nr.init(t,r)}),n_=rs("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=r9),nr.init(t,r)}),nk=/^[0-9a-fA-F:.]+$/;function nE(t){return!!nk.test(t)&&no(`http://[${t}]`)}let nS=rs("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=r3),nr.init(t,r),t._zod.check=a=>{nE(a.value)||a.issues.push({code:"invalid_format",format:"ipv6",input:a.value,inst:t,continue:!r.abort})}}),nx=((t,r)=>{r.pattern??(r.pattern=r8(r.delimiter)),nr.init(t,r)},rs("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=r7),nr.init(t,r)})),nI=rs("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=ae),nr.init(t,r),t._zod.check=a=>{!function(t){let r=t.split("/");if(2!==r.length)return!1;let[a,n]=r;if(!n)return!1;let i=Number(n);return`${i}`===n&&!(i<0)&&!(i>128)&&nE(a)}(a.value)&&a.issues.push({code:"invalid_format",format:"cidrv6",input:a.value,inst:t,continue:!r.abort})}});function nT(t){if(""===t)return!0;if(/\s/.test(t)||t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}let nA=/^[0-9a-zA-Z+/]*={0,2}$/,nC=rs("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=nA),nr.init(t,r),t._zod.check=a=>{nT(a.value)||a.issues.push({code:"invalid_format",format:"base64",input:a.value,inst:t,continue:!r.abort})}}),nO=/^[A-Za-z0-9_-]*$/,nM=rs("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=nO),nr.init(t,r),t._zod.check=a=>{!function(t){if(!nO.test(t))return!1;let r=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return nT(r.padEnd(4*Math.ceil(r.length/4),"="))}(a.value)&&a.issues.push({code:"invalid_format",format:"base64url",input:a.value,inst:t,continue:!r.abort})}}),nR=rs("$ZodE164",(t,r)=>{r.pattern??(r.pattern=an),nr.init(t,r)}),nP=/[- ]/g,nz=((t,r)=>{r.pattern??(r.pattern=ai),nr.init(t,r),t._zod.check=a=>{var n;n=a.value,ai.test(n)&&function(t){let r=t.length,a=1,n=0;for(;r;){let i=t.charCodeAt(--r)-48;a^=1,n+=a?[0,2,4,6,8,1,3,5,7,9][i]:i}return n%10==0}(n.replace(nP,""))||a.issues.push({code:"invalid_format",format:"credit_card",input:a.value,inst:t,continue:!r.abort})}},rs("$ZodJWT",(t,r)=>{nr.init(t,r),t._zod.check=a=>{!function(t,r=null){try{let a=t.split(".");if(3!==a.length)return!1;let[n]=a;if(!n)return!1;let i=JSON.parse(atob(n));if("typ"in i&&i?.typ!=="JWT"||!i.alg||r&&(!("alg"in i)||i.alg!==r))return!1;return!0}catch{return!1}}(a.value,r.alg)&&a.issues.push({code:"invalid_format",format:"jwt",input:a.value,inst:t,continue:!r.abort})}})),n$=((t,r)=>{nr.init(t,r),t._zod.check=a=>{r.fn(a.value)||a.issues.push({code:"invalid_format",format:r.format,input:a.value,inst:t,continue:!r.abort})}},rs("$ZodNumber",(t,r)=>{a3.init(t,r),t._zod.pattern=ag,t._zod.parse=(a,n)=>{if(r.coerce)try{a.value=Number(a.value)}catch(t){}let i=a.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return a;let o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return a.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),a}})),nN=rs("$ZodNumberFormat",(t,r)=>{aF.init(t,r),n$.init(t,r)}),nj=rs("$ZodBoolean",(t,r)=>{a3.init(t,r),t._zod.pattern=ay,t._zod.parse=(a,n)=>{if(r.coerce)try{a.value=!!a.value}catch(t){}let i=a.value;return"boolean"==typeof i||a.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),a}}),nD=rs("$ZodBigInt",(t,r)=>{a3.init(t,r),t._zod.pattern=af,t._zod.parse=(a,n)=>
5{if(r.coerce)try{a.value=BigInt(a.value)}catch(t){}return"bigint"==typeof a.value||a.issues.push({expected:"bigint",code:"invalid_type",input:a.value,inst:t}),a}}),nU=((t,r)=>{aZ.init(t,r),nD.init(t,r)},rs("$ZodNull",(t,r)=>{a3.init(t,r),t._zod.pattern=av,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{let n=r.value;return null===n||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}})),nL=rs("$ZodAny",(t,r)=>{a3.init(t,r),t._zod.parse=t=>t}),nF=rs("$ZodUnknown",(t,r)=>{a3.init(t,r),t._zod.parse=t=>t}),nZ=rs("$ZodNever",(t,r)=>{a3.init(t,r),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function nB(t,r,a){t.issues.length&&r.issues.push(...tF(a,t.issues)),r.value[a]=t.value}(t,r)=>{a3.init(t,r),t._zod.parse=(r,a)=>{let n=r.value;return void 0===n||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:t}),r}},(t,r)=>{a3.init(t,r),t._zod.parse=(a,n)=>{if(r.coerce)try{a.value=new Date(a.value)}catch(t){}let i=a.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||a.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:t}),a}};let nq=rs("$ZodArray",(t,r)=>{a3.init(t,r);let a=rc.memoizer;a?.attach(t),t._zod.parse=(n,i)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=a?a.alloc(t,n,Array(o.length),i):Array(o.length);let s=[],l=i?.abortEarly;for(let t=0;t<o.length;t++){let a=o[t],u=r.element._zod.run({value:a,issues:[]},i);if(u instanceof Promise)s.push(u.then(r=>nB(r,n,t)));else if(nB(u,n,t),l&&0!==u.issues.length&&tU(u))break}return s.length?Promise.all(s).then(()=>n):n}});function nV(t,r,a,n,i,o){let s=a in n,l="optional"===o;if(s||!l||"optional"!==i){if(t.issues.length){if(void 0!==i&&l&&!s)return;r.issues.push(...tF(a,t.issues))}if(!s&&void 0===i){t.issues.length||r.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[a]});return}void 0===t.value?(s||"defaulted"===i&&!l)&&(r.value[a]=void 0):r.value[a]=t.value}}let nJ=[];function nW(t){let r=Object.keys(t.shape),a=Object.getOwnPropertySymbols(t.shape),n=a.length?a:nJ,i=n.length?[...r,...n]:r;for(let r of i)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(r)}": expected a Zod schema`);let o=tT(t.shape);return{...t,allKeys:i,symbolKeys:n,keySet:new Set(r),numKeys:r.length,optionalKeys:new Set(o)}}function nG(t,r,a,n,i,o,s){let l=[],u=i.keySet,c=i.catchall._zod,d=c.def.type,p=c.optin,h=c.optout,f=0;for(let i in r){if(s&&a.issues.length!==f){if(tU(a,f))break;f=a.issues.length}if(u.has(i))continue;if("__proto__"===i){"never"===d&&l.push(i);continue}if("never"===d){l.push(i);continue}let o=c.run({value:r[i],issues:[]},n);o instanceof Promise?t.push(o.then(t=>nV(t,a,i,r,p,h))):nV(o,a,i,r,p,h)}return(l.length&&a.issues.push({code:"unrecognized_keys",keys:l,input:r,inst:o,continue:!0}),t.length)?Promise.all(t).then(()=>a):a}let nH=rs("$ZodObject",(t,r)=>{let a;a3.init(t,r);let n=Object.getOwnPropertyDescriptor(r,"shape"),i=n?.get?n.get.raw:r.shape??{};if(i){let t=()=>{let a={...i};return Object.defineProperty(r,"shape",{value:a}),t.raw=a,a};t.raw=i,Object.defineProperty(r,"shape",{get:t})}let o=e4(()=>nW(r));rt(t,"propValues",t=>{let r=t.def.shape,a={};for(let t in r){let n=r[t]._zod;if(n.values){for(let r of(Object.prototype.hasOwnProperty.call(a,t)||te(a,t,new Set),n.values))a[t].add(r);void 0!==n.optin&&a[t].add(void 0)}}return a});let s=r.catchall,l=rc.memoizer;l?.attach(t),t._zod.parse=(r,n)=>{a??(a=o.value);let i=r.value;if(!tf(i))return r.issues.push({expected:"object",code:"invalid_type",input:i,inst:t}),r;r.value=l?l.alloc(t,r,{},n):{};let u=[],c=a.shape,d=n?.abortEarly,p=r.issues.length;for(let t of a.allKeys){if(d&&r.issues.length!==p){if(tU(r,p))break;p=r.issues.length}if("__proto__"===t)continue;let a=c[t],o=a._zod.optin,s=a._zod.optout,l=a._zod.run({value:i[t],issues:[]},n);l instanceof Promise?u.push(l.then(a=>nV(a,r,t,i,o,s))):nV(l,r,t,i,o,s)}return s?nG(u,i,r,n,o.value,t,!0===d):u.length?Promise.all(u).then(()=>r):r}}),nK=rs("$ZodObjectJIT",(t,r)=>{let a,n;nH.init(t,r);let i=t._zod.parse,o=e4(()=>
5nW(r)),s=rc.memoizer,l=!rc.jitless,u=l&&tm.value,c=r.catchall;t._zod.parse=(d,p)=>{n??(n=o.value);let h=d.value;return tf(h)?l&&u&&p?.async===!1&&!0!==p.jitless?(a||(a=(r=>{let a=o.value,n=a.symbolKeys,i=new a5(["payload","ctx"],{shape:r,inst:t,memo:s,syms:n}),l=t=>`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`,u=(t,r)=>` 6 let ${t}_ab = false; 7 for (let i = 0; i < ${t}.issues.length; i++) { 8 const iss = ${t}.issues[i]; 9 iss.path = iss.path ? [${r}, ...iss.path] : [${r}]; 10 payload.issues.push(iss); 11 if (iss.continue !== true) ${t}_ab = true; 12 } 13 if (${t}_ab && ctx && ctx.abortEarly) { 14 payload.value = newResult; 15 return payload; 16 }`;i.write("const input = payload.value;");let c=Object.create(null),d=0;for(let t of a.allKeys)c[t]=`key_${d++}`;for(let t of(i.write(s?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};"),a.allKeys)){if("__proto__"===t)continue;let a=c[t],o="symbol"==typeof t?`syms[${n.indexOf(t)}]`:td(t),s=`${o} in input`,d=r[t],p=d?._zod?.optin,h=void 0!==p,f=d?._zod?.optout==="optional";if(i.write(`const ${a} = ${l(o)};`),h&&f){let t="optional"===p?`${a}_present`:`${a}.value !== undefined || ${a}_present`;i.write(` 17 const ${a}_present = ${s}; 18 if (!${a}.issues.length || ${a}_present) { 19 if (${a}.issues.length) {${u(a,o)} 20 } 21 22 if (${t}) { 23 newResult[${o}] = ${a}.value; 24 } 25 } 26 27 `)}else h?(i.write(` 28 if (${a}.issues.length) {${u(a,o)} 29 } 30 `),"defaulted"===p?i.write(`newResult[${o}] = ${a}.value;`):i.write(` 31 if (${a}.value !== undefined || ${s}) { 32 newResult[${o}] = ${a}.value; 33 } 34 `)):i.write(` 35 const ${a}_present = ${s}; 36 if (${a}.issues.length) {${u(a,o)} 37 } 38 if (!${a}_present && !${a}.issues.length) { 39 payload.issues.push({ 40 code: "invalid_type", 41 expected: "nonoptional", 42 input: undefined, 43 path: [${o}] 44 }); 45 if (ctx && ctx.abortEarly) { 46 payload.value = newResult; 47 return payload; 48 } 49 } 50 51 if (${a}_present) { 52 newResult[${o}] = ${a}.value; 53 } 54 55 `)}return i.write("payload.value = newResult;"),i.write("return payload;"),i.compile()})(r.shape)),d=a(d,p),c)?nG([],h,d,p,n,t,p?.abortEarly===!0):d:i(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d)}});function nY(t,r,a,n){for(let a of t)if(0===a.issues.length)return r.value=a.value,r;let i=t.filter(t=>!tU(t));return 1===i.length?(r.value=i[0].value,i[0]):(r.issues.push({code:"invalid_union",input:r.value,inst:a,errors:t.map(t=>t.issues.map(t=>tq(t,n,rd())))}),r)}let nX=rs("$ZodUnion",(t,r)=>{a3.init(t,r),rt(t,"optin",t=>t.def.options.some(t=>"defaulted"===t._zod.optin)?"defaulted":t.def.options.some(t=>void 0!==t._zod.optin)?"optional":void 0),rt(t,"optout",t=>t.def.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),rt(t,"values",t=>{if(t.def.options.every(t=>t._zod.values))return new Set(t.def.options.flatMap(t=>Array.from(t._zod.values)))}),rt(t,"pattern",t=>{if(t.def.options.every(t=>t._zod.pattern)){let r=t.def.options.map(t=>t._zod.pattern);return RegExp(`^(${r.map(t=>e5(t.source)).join("|")})$`)}});let a=1===r.options.length?r.options[0]._zod.run:null;t._zod.parse=(n,i)=>{if(a)return a(n,i);let o=!1,s=[];for(let t of r.options){let r=t._zod.run({value:n.value,issues:[]},i);if(r instanceof Promise)s.push(r),o=!0;else{if(0===r.issues.length)return r;s.push(r)}}return o?Promise.all(s).then(r=>nY(r,n,t,i)):nY(s,n,t,i)}});function nQ(t,r,a,n){let i=[];for(let r=0;r<t.length;r++)0===t[r].issues.length&&i.push(r);return 1===i.length?r.value=t[i[0]].value:0===i.length?r.issues.push({code:"invalid_union",input:r.value,inst:a,errors:t.map(t=>t.issues.map(t=>tq(t,n,rd())))}):r.issues.push({code:"invalid_union",input:r.value,inst:a,errors:[],inclusive:!1,matches:i}),r}(t,r)=>{nX.init(t,r),r.inclusive=!1;let a=1===r.options.length?r.options[0]._zod.run:null;t._zod.parse=(n,i)=>{if(a)return a(n,i);let o=!1,s=[];for(let t of r.options){let r=t._zod.run({value:n.value,issues:[]},i);r instanceof Promise?(s.push(r),o=!0):s.push(r)}return o?Promise.all(s).then(r=>nQ(r,n,t,i)):nQ(s,n,t,i)}};let n0=rs("$ZodDiscriminatedUnion",(t,r)=>{r.inclusive=!1,nX.init(t,r);let a=t._zod.parse;rt(t,"propValues",t=>{let r={},a=0;for(let n of t.def.options){let i=n._zod.propValues;if(!i||0===Object.keys(i).length)throw Error(`Invalid discriminated union option at index "${t.def.options.indexOf(n)}"`);for(let[n,o]of(i[t.def.discriminator]?.has(void 0)&&a++,Object.entries(i)))for(let t of(Object.prototype.hasOwnProperty.call(r,n)||te(r,n,new Set),o))r[n].add(t)}return!t.def.unionFallback&&a>1&&r[t.def.discriminator]?.delete(void 0),r}),r.options.forEach((t,a)=>{let n=tt(t._zod.def);if(n&&!Object.prototype.hasOwnProperty.call(n,r.discriminator))throw Error(`Invalid discriminated union option at index "${a}"`)});let n=e4(()=>(function(t){let r=new Map;for(let a of t.options){let n=a._zod.propValues?.[t.discriminator];
55if(!n||0===n.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let t of n)if(r.has(t)){if(void 0!==t)throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,null)}else r.set(t,a)}return r})(r));t._zod.parse=(i,o)=>{let s=i.value;if(!tf(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;let l=s?.[r.discriminator],u=n.value.get(l);return u&&(void 0!==l||"backward"!==o.direction)?u._zod.run(i,o):r.unionFallback||"backward"===o.direction?a(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:r.discriminator,options:Array.from(n.value.keys()).filter(t=>null!==n.value.get(t)),input:s,path:[r.discriminator],inst:t}),i)}}),n1=rs("$ZodIntersection",(t,r)=>{a3.init(t,r),t._zod.parse=(t,a)=>{let n=t.value,i=r.left._zod.run({value:n,issues:[]},a),o=r.right._zod.run({value:n,issues:[]},a);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([r,a])=>n2(t,r,a)):n2(t,i,o)}});function n2(t,r,a){let n,i=new Map,o=new Map,s=(t,r)=>{let a;if("unrecognized_keys"!==t.code||t.path?.length)if("invalid_key"!==t.code||"record"!==t.origin||t.path?.length!==1)return!1;else{let r=String(t.path[0]);o.has(r)||o.set(r,t),a=[r]}else n??(n=t),a=t.keys;for(let t of a)i.has(t)||i.set(t,{}),i.get(t)[r]=!0;return!0};for(let a of r.issues)s(a,"l")||t.issues.push(a);for(let r of a.issues)s(r,"r")||t.issues.push(r);let l=[...i].filter(([,t])=>t.l&&t.r).map(([t])=>t);if(l.length){let r=n?l.filter(t=>n.keys.includes(t)):[];for(let a of(r.length&&t.issues.push({...n,keys:r}),l))!r.includes(a)&&o.has(a)&&t.issues.push(o.get(a))}let u=function t(r,a){if(r===a||r instanceof Date&&a instanceof Date&&+r==+a)return{valid:!0,data:r};if(tg(r)&&tg(a)){let n=Object.keys(a),i=Object.keys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...a};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,i)){if("__proto__"===n)continue;let i=t(r[n],a[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};o[n]=i.data}return{valid:!0,data:o}}if(Array.isArray(r)&&Array.isArray(a)){if(r.length!==a.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<r.length;i++){let o=t(r[i],a[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(r.value,a.value);if(!u.valid){if(tU(t))return t;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return t.value=u.data,t}let n4=rs("$ZodTuple",(t,r)=>{a3.init(t,r);let a=r.items,n=rc.memoizer;n?.attach(t),t._zod.parse=(i,o)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),i;i.value=n?n.alloc(t,i,[],o):[];let l=[],u=n6(a,"optin"),c=n6(a,"optout");if(!r.rest){if(s.length<u)return i.issues.push({code:"too_small",minimum:u,inclusive:!0,input:s,inst:t,origin:"array"}),i;s.length>a.length&&i.issues.push({code:"too_big",maximum:a.length,inclusive:!0,input:s,inst:t,origin:"array"})}let d=Array(a.length),p=r.rest?o?.abortEarly:void 0,h=!1;for(let t=0;t<a.length;t++){let r=a[t]._zod.run({value:s[t],issues:[]},o);r instanceof Promise?l.push(r.then(r=>{d[t]=r})):(d[t]=r,p&&!h&&r.issues.length&&(h=tU(r)))}if(r.rest&&!h){let t=a.length-1,n=s.slice(a.length),u=i.issues.length;for(let a of n){if(p&&i.issues.length!==u){if(tU(i,u))break;u=i.issues.length}t++;let n=r.rest._zod.run({value:a,issues:[]},o);n instanceof Promise?l.push(n.then(r=>n5(r,i,t))):n5(n,i,t)}}return l.length?Promise.all(l).then(()=>n9(d,i,a,s,c)):n9(d,i,a,s,c)}});function n6(t,r){for(let a=t.length-1;a>=0;a--)if(!("optin"===r?void 0!==t[a]._zod.optin:"optional"===t[a]._zod.optout))return a+1;return 0}function n5(t,r,a){t.issues.length&&r.issues.push(...tF(a,t.issues)),r.value[a]=t.value}function n9(t,r,a,n,i){for(let o=0;o<a.length;o++){let s=t[o],l=o<n.length;if(!l&&o>=i&&"optional"===a[o]._zod.optin){r.value.length=o;break}if(s.issues.length){if(!l&&o>=i){r.value.length=o;break}r.issues.push(...tF(o,s.issues))}r.value[o]=s.value}for(let t=r.value.length-1;t>=n.length;t--)if("optional"===a[t]._zod.optout&&void 0===r.value[t])r.value.length=t;else break;return r}let n3=rs("$ZodRecord",(t,r)=>{a3.init(t,r);let a=rc.memoizer;a?.attach(t),t._zod.parse=(n,i)=>{let o=n.value;if(!tg(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],l=r.keyType._zod.values;if(l&&!r.partial){let u;n.value=a?a.alloc(t,n,{},i):{};let c=new Set;for(let a of l)if("string"==typeof a||"number"==typeof a||"symbol"==typeof a){if(c.add("number"==typeof a?a.toString():a),"__proto__"===a)continue;let l=r.keyType._zod.run({value:a,issues:[]},i);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(t=>
55tq(t,i,rd())),input:a,path:[a],inst:t});continue}let u=l.value;if("__proto__"===u)continue;let d=r.valueType._zod.run({value:o[a],issues:[]},i);d instanceof Promise?s.push(d.then(t=>{t.issues.length&&n.issues.push(...tF(a,t.issues)),n.value[u]=t.value})):(d.issues.length&&n.issues.push(...tF(a,d.issues)),n.value[u]=d.value)}for(let t in o)if(!c.has(t))if("loose"===r.mode){if("__proto__"===t)continue;n.value[t]=o[t]}else(u=u??[]).push(t);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:u,continue:!0})}else{let u;for(let c of(n.value=a?a.alloc(t,n,{},i):{},Reflect.ownKeys(o))){if("__proto__"===c||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let a=r.keyType._zod.run({value:c,issues:[]},i);if(a instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof c&&ag.test(c)&&a.issues.length){let t=r.keyType._zod.run({value:Number(c),issues:[]},i);if(t instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===t.issues.length&&(a=t)}if(a.issues.length){"loose"===r.mode?n.value[c]=o[c]:l?(u=u??[]).push(c):n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(t=>tq(t,i,rd())),input:c,path:[c],inst:t});continue}let d=a.value;if("__proto__"===d)continue;let p=r.valueType._zod.run({value:o[c],issues:[]},i);p instanceof Promise?s.push(p.then(t=>{t.issues.length&&n.issues.push(...tF(c,t.issues)),n.value[d]=t.value})):(p.issues.length&&n.issues.push(...tF(c,p.issues)),n.value[d]=p.value)}u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:u,continue:!0})}return s.length?Promise.all(s).then(()=>n):n}});function n8(t,r,a,n,i,o,s){t.issues.length&&(tw.has(typeof n)?a.issues.push(...tF(n,t.issues)):a.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:t.issues.map(t=>tq(t,s,rd()))})),r.issues.length&&(tw.has(typeof n)?a.issues.push(...tF(n,r.issues)):a.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:n,issues:r.issues.map(t=>tq(t,s,rd()))})),a.value.set(t.value,r.value)}function n7(t,r){t.issues.length&&r.issues.push(...t.issues),r.value.add(t.value)}(t,r)=>{a3.init(t,r);let a=rc.memoizer;a?.attach(t),t._zod.parse=(n,i)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:t}),n;let s=[];n.value=a?a.alloc(t,n,new Map,i):new Map;let l=i?.abortEarly,u=n.issues.length;for(let[a,c]of o){if(l&&n.issues.length!==u){if(tU(n,u))break;u=n.issues.length}let d=r.keyType._zod.run({value:a,issues:[]},i),p=r.valueType._zod.run({value:c,issues:[]},i);d instanceof Promise||p instanceof Promise?s.push(Promise.all([d,p]).then(([r,s])=>{n8(r,s,n,a,o,t,i)})):n8(d,p,n,a,o,t,i)}return s.length?Promise.all(s).then(()=>n):n}},(t,r)=>{a3.init(t,r);let a=rc.memoizer;a?.attach(t),t._zod.parse=(n,i)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:t,expected:"set",code:"invalid_type"}),n;let s=[];n.value=a?a.alloc(t,n,new Set,i):new Set;let l=i?.abortEarly,u=n.issues.length;for(let t of o){if(l&&n.issues.length!==u){if(tU(n,u))break;u=n.issues.length}let a=r.valueType._zod.run({value:t,issues:[]},i);a instanceof Promise?s.push(a.then(t=>n7(t,n))):n7(a,n)}return s.length?Promise.all(s).then(()=>n):n}};let ie=rs("$ZodEnum",(t,r)=>{a3.init(t,r);let a=eQ(r.entries),n=new Set(a);t._zod.values=n,rt(t,"pattern",t=>{let r=eQ(t.def.entries).filter(t=>tw.has(typeof t));return new RegExp(r.length?`^(${r.map(t=>tk(t.toString())).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:a,input:o,inst:t}),r}}),it=rs("$ZodLiteral",(t,r)=>{a3.init(t,r);let a=new Set(r.values);t._zod.values=a,rt(t,"pattern",t=>{let r=t.def.values;return new RegExp(r.length?`^(${r.map(t=>"string"==typeof t?tk(t):t?tk(t.toString()):String(t)).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(n,i)=>{let o=n.value;return a.has(o)||n.issues.push({code:"invalid_value",values:r.values,input:o,inst:t}),n}}),ir=((t,r)=>{a3.init(t,r),t._zod.parse=(r,a)=>{let n=r.value;return n instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:n,inst:t}),r}},rs("$ZodTransform",(t,r)=>{a3.init(t,r),t._zod.optin="optional",rc.memoizer?.guard(t),t._zod.parse=(a,n)=>{if("backward"===n.direction)throw new ru(t.constructor.name);let i=r.transform(a.value,a);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(t=>(a.value=t,a));if(i instanceof Promise)throw new rl;return a.value=i,a}}));
55function ia(t,r){return t.value=r.issues.length?void 0:r.value,t}let ii=rs("$ZodOptional",(t,r)=>{a3.init(t,r),rt(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),t._zod.optout="optional",rt(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),rt(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${e5(r.source)})?$`):void 0}),t._zod.parse=(t,a)=>{if(void 0===t.value){if("defaulted"!==r.innerType._zod.optin)return t;let n=r.innerType._zod.run({value:t.value,issues:[]},a);return n instanceof Promise?n.then(r=>ia(t,r)):ia(t,n)}return r.innerType._zod.run(t,a)}}),io=rs("$ZodExactOptional",(t,r)=>{ii.init(t,r),rt(t,"values",t=>t.def.innerType._zod.values),rt(t,"pattern",t=>t.def.innerType._zod.pattern),t._zod.parse=(t,a)=>r.innerType._zod.run(t,a)}),is=rs("$ZodNullable",(t,r)=>{a3.init(t,r),rt(t,"optin",t=>t.def.innerType._zod.optin),rt(t,"optout",t=>t.def.innerType._zod.optout),rt(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${e5(r.source)}|null)$`):void 0}),rt(t,"values",t=>t.def.innerType._zod.values?new Set([...t.def.innerType._zod.values,null]):void 0),t._zod.parse=(t,a)=>null===t.value?t:r.innerType._zod.run(t,a)}),il=rs("$ZodDefault",(t,r)=>{a3.init(t,r),t._zod.optin="defaulted",rt(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,a)=>{if("backward"===a.direction)return r.innerType._zod.run(t,a);if(void 0===t.value)return t.value=r.defaultValue,t;let n=r.innerType._zod.run(t,a);return n instanceof Promise?n.then(t=>iu(t,r)):iu(n,r)}});function iu(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}let ic=rs("$ZodPrefault",(t,r)=>{a3.init(t,r),t._zod.optin="defaulted",rt(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,a)=>("backward"===a.direction||void 0===t.value&&(t.value=r.defaultValue),r.innerType._zod.run(t,a))}),id=rs("$ZodNonOptional",(t,r)=>{a3.init(t,r),rt(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r].filter(t=>void 0!==t)):void 0}),t._zod.parse=(a,n)=>{let i=r.innerType._zod.run(a,n);return i instanceof Promise?i.then(r=>ip(r,t)):ip(i,t)}});function ip(t,r){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function ih(t,r,a,n){return r.issues.length?t.value=a.catchValue({...r,value:t.value,error:{issues:r.issues.map(t=>tq(t,n,rd()))},input:t.value}):(t.value=r.value,r.memo&&(t.memo=!0)),t}(t,r)=>{a3.init(t,r),t._zod.parse=(t,a)=>{if("backward"===a.direction)throw new ru("ZodSuccess");let n=r.innerType._zod.run(t,a);return n instanceof Promise?n.then(r=>(t.value=0===r.issues.length,t)):(t.value=0===n.issues.length,t)}};let im=rs("$ZodCatch",(t,r)=>{a3.init(t,r),rt(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),rt(t,"optout",t=>t.def.innerType._zod.optout),rt(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,a)=>{if("backward"===a.direction)return r.innerType._zod.run(t,a);let n=r.innerType._zod.run({value:t.value,issues:[]},a);return n instanceof Promise?n.then(n=>ih(t,n,r,a)):ih(t,n,r,a)}}),ig=((t,r)=>{a3.init(t,r),t._zod.parse=(r,a)=>("number"==typeof r.value&&Number.isNaN(r.value)||r.issues.push({input:r.value,inst:t,expected:"nan",code:"invalid_type"}),r)},rs("$ZodPipe",(t,r)=>{a3.init(t,r),rt(t,"values",t=>t.def.in._zod.values),rt(t,"optin",t=>t.def.in._zod.optin),rt(t,"optout",t=>t.def.out._zod.optout),rt(t,"propValues",t=>t.def.in._zod.propValues),t._zod.parse=(t,a)=>{if("backward"===a.direction){let n=r.out._zod.run(t,a);return n instanceof Promise?n.then(t=>iy(t,r.in,a)):iy(n,r.in,a)}let n=r.in._zod.run(t,a);return n instanceof Promise?n.then(t=>iy(t,r.out,a)):iy(n,r.out,a)}}));function iy(t,r,a){return t.issues.some(t=>"unrecognized_keys"!==t.code)?(t.aborted=!0,t):r._zod.run({value:t.value,issues:t.issues},a)}function iv(t,r,a){if(t.issues.length)return t.aborted=!0,t;if("forward"===(a.direction||"forward")){let n=r.transform(t.value,t);return n instanceof Promise?n.then(n=>ib(t,n,r.out,a)):ib(t,n,r.out,a)}{let n=r.reverseTransform(t.value,t);return n instanceof Promise?n.then(n=>ib(t,n,r.in,a)):ib(t,n,r.in,a)}}function ib(t,r,a,n){return t.issues.length?(t.aborted=!0,t):a._zod.run({value:r,issues:t.issues},n)}(t,r)=>{a3.init(t,r),rt(t,"values",t=>t.def.in._zod.values),rt(t,"optin",t=>t.def.in._zod.optin),rt(t,"optout",t=>t.def.out._zod.optout),rt(t,"propValues",t=>t.def.in._zod.propValues),t._zod.parse=(t,a)=>{if("forward"===(a.direction||"forward")){let n=r.in._zod.run(t,a);return n instanceof Promise?n.then(t=>iv(t,r,a)):iv(n,r,a)}{let n=r.out._zod.run(t,a);return n instanceof Promise?n.then(t=>iv(t,r,a)):iv(n,r,a)}}},(t,r)=>{ig.init(t,r)};let iw=rs("$ZodReadonly",(t,r)=>{a3.init(t,r),rt(t,"propValues",t=>t.def.innerType._zod.propValues),rt(t,"values",t=>t.def.innerType._zod.values),rt(t,"optin",t=>t.def.innerType?._zod?.optin),rt(t,"optout",t=>t.def.innerType?._zod?.optout),t._zod.parse=(t,a)=>{if("backward"===a.direction)return r.innerType._zod.run(t,a);let n=r.innerType._zod.run(t,a);return n instanceof Promise?n.then(i_):i_(n)}});function i_(t){return t.memo||(t.value=Object.freeze(t.value)),t}(t,r)=>{a3.init(t,r);let a=[];for(let t of r.parts)if("object"==typeof t&&null!==t){let r=function t(r){let a=r._zod.def,n=r._zod.pattern?.source,i=a.innerType??r._zod.innerType;if(i){let r=i._zod.pattern?.source,a=t(i);return n&&r&&a&&a!==r?n.replace(e5(r),()=>e5(a)):n}if(a.options){let r=a.options.map(t);if(r.every(Boolean))return`^(${r.map(t=>e5(t)).join("|")})$`}return function(t){let r,a,n=t._zod.def,i=n.pattern,o=!!n.format?.includes("int");for(let t of n.checks??[]){let n=t._zod.def;n.pattern&&(i=n.pattern),o||(o=!!n.format?.includes("int"));let s=n.minimum??n.length,l=n.maximum??n.length;void 0!==s&&(void 0===r||s>r)&&(r=s),void 0!==l&&(void 0===a||l<a)&&(a=l)}if(i)return i.source;if(void 0!==r&&void 0!==a&&r>a)return"(?!)";if(void 0!==r||void 0!==a)return ah({minimum:r,maximum:a}).source;let s=t._zod.pattern;return(o&&s===ag?am:s)?.source}(r)}(t);if(!r)throw Error(`Invalid template literal part, no pattern found: ${[...t._zod.traits].shift()}`);a.push(e5(r))}else if(null===t||t_.has(typeof t))a.push(tk(`${t}`));else throw Error(`Invalid template literal part: ${t}`);t._zod.pattern=RegExp(`^${a.join("")}$`),t._zod.parse=(a,n)=>
55("string"!=typeof a.value?a.issues.push({input:a.value,inst:t,expected:"string",code:"invalid_type"}):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(a.value)||a.issues.push({input:a.value,inst:t,code:"invalid_format",format:r.format??"template_literal",pattern:t._zod.pattern.source})),a)},(t,r)=>{a3.init(t,r),t._zod.parse=(t,a)=>Promise.resolve(t.value).then(t=>r.innerType._zod.run({value:t,issues:[]},a))};let ik=rs("$ZodLazy",(t,r)=>{a3.init(t,r),e8(t._zod,"innerType",()=>(r._cachedInner||(r._cachedInner=r.getter()),r._cachedInner)),rt(t,"pattern",t=>t.innerType?._zod?.pattern),rt(t,"propValues",t=>t.innerType?._zod?.propValues),rt(t,"optin",t=>t.innerType?._zod?.optin??void 0),rt(t,"optout",t=>t.innerType?._zod?.optout??void 0),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),iE=rs("$ZodCustom",(t,r)=>{az.init(t,r),a3.init(t,r),t._zod.parse=(t,r)=>t,t._zod.check=a=>{let n=a.value,i=r.fn(n);if(i instanceof Promise)return i.then(r=>iS(r,a,n,t));iS(i,a,n,t)}});function iS(t,r,a,n){if(!t){let t={code:"custom",input:a,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(t.params=n._zod.def.params),r.issues.push(tK(t))}}(O=globalThis).__zod_globalRegistry??(O.__zod_globalRegistry=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let a=r[0];return this._map.set(t,a),a&&"object"==typeof a&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&"object"==typeof r&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let a={...this.get(r)??{}};delete a.id;let n={...a,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});let ix=globalThis.__zod_globalRegistry;function iI(t,...r){for(let a of r)for(let r of Reflect.ownKeys(a))Object.prototype.propertyIsEnumerable.call(a,r)&&te(t,r,a[r]);return t}function iT(t){let r=t?.target??"draft-2020-12";return"draft-4"===r&&(r="draft-04"),"draft-7"===r&&(r="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??ix,target:r,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function iA(t,r,a,n,i){let o="function"==typeof r.unrepresentable?r.unrepresentable({zodSchema:t,path:n.path,message:i}):r.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw Error(i);return Object.assign(a,o),!0}function iC(t,r,a={path:[],schemaPath:[]}){var n;let i=t._zod.def,o=r.seen.get(t);if(o)return o.count++,a.schemaPath.includes(t)&&(o.cycle=a.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:a.path};r.seen.set(t,s),r.sharedDefsExtractedFor=void 0,r.sharedEmitDoneFor=void 0;let l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{let n={...a,schemaPath:[...a.schemaPath,t],path:a.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(r,s.schema,n);else{let a=s.schema,o=r.processors[i.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(t,r,a,n)}let o=t._zod.parent;o&&(s.ref||(s.ref=o),iC(o,r,n),r.seen.get(o).isParent=!0)}let u=r.metadataRegistry.get(t);return u&&iI(s.schema,u),"input"===r.io&&function t(r,a){let n=a??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let i=r._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return t(i.element,n);if("set"===i.type)return t(i.valueType,n);if("lazy"===i.type)return t(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type||"catch"===i.type)return t(i.innerType,n);if("intersection"===i.type)return t(i.left,n)||t(i.right,n);if("record"===i.type||"map"===i.type)return t(i.keyType,n)||t(i.valueType,n);if("pipe"===i.type)return!!r._zod.traits.has("$ZodCodec")||t(i.in,n)||t(i.out,n);if("object"===i.type){for(let r in i.shape)if(t(i.shape[r],n))return!0;return!1}
55if("union"===i.type){for(let r of i.options)if(t(r,n))return!0;return!1}if("tuple"===i.type){for(let r of i.items)if(t(r,n))return!0;if(i.rest&&t(i.rest,n))return!0}return!1}(t)&&(delete s.schema.examples,delete s.schema.default),"input"===r.io&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,r.seen.get(t).schema}function iO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function iM(t,r){let a=t.seen.get(r);if(!a)throw Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let n=new Map;for(let r of t.seen.entries()){let a=t.metadataRegistry.get(r[0])?.id;if(a){let t=n.get(a);if(t&&t!==r[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,r[0])}}let i=r=>{if(r[1].schema.$ref)return;let n=r[1],{ref:i,defId:o}=(r=>{let n="draft-2020-12"===t.target?"$defs":"definitions";if(t.external){let a=t.external.registry.get(r[0])?.id,i=t.external.uri??(t=>t);if(a)return{ref:i(a)};let o=r[1].defId??r[1].schema.id??`schema${t.counter++}`;return r[1].defId=o,{defId:o,ref:`${i("__shared")}#/${n}/${iO(o)}`}}let i=`#/${n}/`;if(r[1]===a&&!r[1].schema.id)return{ref:"#"};let o=r[1].schema.id??`__schema${t.counter++}`;return{defId:o,ref:i+iO(o)}})(r);n.def={...n.schema},o&&(n.defId=o);let s=n.schema;for(let t in s)delete s[t];s.$ref=i};if("throw"===t.cycles)for(let r of t.seen.entries()){let t=r[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root> 56 57Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let n=a[1];if(r===a[0]){i(a);continue}if(t.external){let n=t.external.registry.get(a[0])?.id;if(r!==a[0]&&n){i(a);continue}}if(t.metadataRegistry.get(a[0])?.id||n.cycle){i(a);continue}n.count>1&&"ref"===t.reused&&i(a)}t.external&&(t.sharedDefsExtractedFor=t.external)}let iR=new Set(["type","properties","required","additionalProperties"]),iP=["oneOf","anyOf"];function iz(t){let r=t.additionalProperties;return void 0===r||!1===r||"object"!=typeof r||null===r?null:Object.keys(r).length?r:null}function i$(t){let r=[];for(let a of t){if("object"!=typeof a||"object"!==a.type)return null;for(let t in a)if(!iR.has(t))return null;r.push(a)}let a={},n=new Set;for(let t of r){for(let n in t.properties){if(Object.prototype.hasOwnProperty.call(a,n))continue;let t=[];for(let a of r){let r=a.properties?.[n]??iz(a);null!=r&&(t.some(t=>JSON.stringify(t)===JSON.stringify(r))||t.push(r))}te(a,n,1===t.length?t[0]:i$(t)??{allOf:t})}for(let r of t.required??[])n.add(r)}let i={type:"object",properties:a};if(n.size&&(i.required=[...n]),r.every(t=>!1===t.additionalProperties))i.additionalProperties=!1;else{let t=[];for(let a of r){let r=iz(a);r&&!t.some(t=>JSON.stringify(t)===JSON.stringify(r))&&t.push(r)}1===t.length?i.additionalProperties=t[0]:t.length>1&&(i.additionalProperties={allOf:t})}return i}function iN(t,r){let a=t.seen.get(r);if(!a)throw Error("Unprocessed schema. This is a bug in Zod.");let n=r=>{let a=t.seen.get(r);if(null===a.ref)return;let i=a.def??a.schema,o={...i},s=a.ref;if(a.ref=null,s){n(s);let a=t.seen.get(s),l=a.schema;if(l.$ref&&("draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target)?(i.allOf=i.allOf??[],i.allOf.push(l)):iI(i,l),iI(i,o),r._zod.parent===s)for(let t in i)"$ref"!==t&&"allOf"!==t&&(t in o||delete i[t]);if(l.$ref&&a.def)for(let t in i)"$ref"!==t&&"allOf"!==t&&t in a.def&&JSON.stringify(i[t])===JSON.stringify(a.def[t])&&delete i[t]}let l=r._zod.parent;if(l&&l!==s){n(l);let r=t.seen.get(l);if(r?.schema.$ref&&(i.$ref=r.schema.$ref,r.def))for(let t in i)"$ref"!==t&&"allOf"!==t&&t in r.def&&JSON.stringify(i[t])===JSON.stringify(r.def[t])&&delete i[t]}t.override({zodSchema:r,jsonSchema:i,path:a.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let r of[...t.seen.entries()].reverse())n(r[0]);if("openapi-3.0"!==t.target)for(let r of t.seen.entries())!function t(r){let a=r.anyOf;if(!Array.isArray(a)||0===a.length||void 0!==r.type)return;let n=[];for(let r of a){if(!r||"object"!=typeof r)return;t(r);let a=Object.keys(r);if(1!==a.length||"type"!==a[0])return;let i=r.type;for(let t of Array.isArray(i)?i:[i]){if("string"!=typeof t)return;n.includes(t)||n.push(t)}}delete r.anyOf,r.type=1===n.length?n[0]:n}(r[1].def??r[1].schema);for(let r of t.deferred)r();if(t.intersections.length){let r=new Map;for(let a of t.seen.values())for(let t of[a.schema,a.def]){let a=t?.allOf;if(!Array.isArray(a))continue;let n=r.get(a);n?n.push(t):r.set(a,[t])}for(let a of t.intersections)for(let t of r.get(a)??[])!function(t){let r=t.allOf;if(!Array.isArray(r)||r.length<2)return;for(let r of iR)if(r in t)return;let a=r.filter(t=>iP.some(r=>Array.isArray(t[r]))),n=null;if(a.length){let t=a[0],i=iP.find(r=>Array.isArray(t[r]));if(1!==Object.keys(t).length)return;let o=r.filter(r=>r!==t),s=t[i].map(t=>i$([...o,t]));if(s.some(t=>!t))return;n={[i]:s}}else n=i$(r);n&&(delete t.allOf,iI(t,n))}(t)}}let i={};
57if("draft-2020-12"===t.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===t.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===t.target?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(r)?.id;if(!a)throw Error("Schema is missing an `id` property");i.$id=t.external.uri(a)}iI(i,a.defId?a.schema:a.def??a.schema);let o=t.metadataRegistry.get(r)?.id;void 0!==o&&i.id===o&&delete i.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let r of t.seen.entries()){let t=r[1];t.def&&t.defId&&(t.def.id===t.defId&&delete t.def.id,te(s,t.defId,t.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&("draft-2020-12"===t.target?i.$defs=s:i.definitions=s);try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...r["~standard"],jsonSchema:{input:ij(r,"input",t.processors),output:ij(r,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch(t){throw Error("Error converting schema to JSON.")}}let ij=(t,r,a={})=>n=>{let{libraryOptions:i,target:o}=n??{},s=iT({...i??{},target:o,io:r,processors:a});return iC(t,s),iM(s,t),iN(s,t)},iD=(t,r,a)=>{(void 0===t[r]||a>t[r])&&(t[r]=a)},iU=(t,r,a)=>{(void 0===t[r]||a<t[r])&&(t[r]=a)},iL=(t,r)=>{iD(t,"minimum",r),iU(t,"maximum",r)},iF=(t,r)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(r)||t.multipleOf.push(r)},iZ=(t,r)=>{t.patterns??(t.patterns=new Set),t.patterns.add(r)},iB=(t,r)=>{t.mime=t.mime?t.mime.filter(t=>r.includes(t)):[...r]},iq=(t,r)=>{t.format=r,r.includes("int")&&(t.isInt=!0)},iV=(t,r)=>iD(t,"minimum",r.minimum),iJ=(t,r)=>iU(t,"maximum",r.maximum),iW=t=>(r,a)=>{iq(r,a.format);let[n,i]=t[a.format];iD(r,"minimum",n),iU(r,"maximum",i)},iG={greater_than:(t,r)=>iD(t,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(t,r)=>iU(t,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(t,r)=>iF(t,r.value),number_format:iW(tA),bigint_format:iW(tC),min_length:iV,max_length:iJ,length_equals:(t,r)=>iL(t,r.length),min_size:iV,max_size:iJ,size_equals:(t,r)=>iL(t,r.size),string_format:(t,r)=>{iq(t,r.format),r.pattern&&iZ(t,r.pattern),("base64"===r.format||"base64url"===r.format)&&(t.contentEncoding=r.format),(r.local||-1===r.precision)&&(t.laxFormat=!0)},mime_type:(t,r)=>iB(t,r.mime)};function iH(t){let r={},a=t._zod.def;for(let n of t._zod.traits.has("$ZodCheck")?[t,...a.checks??[]]:a.checks??[])iG[n._zod.def.check]?.(r,n._zod.def);let n=t._zod.bag;for(let t of(void 0!==n.minimum&&iD(r,"minimum",n.minimum),void 0!==n.exclusiveMinimum&&iD(r,"exclusiveMinimum",n.exclusiveMinimum),void 0!==n.maximum&&iU(r,"maximum",n.maximum),void 0!==n.exclusiveMaximum&&iU(r,"exclusiveMaximum",n.exclusiveMaximum),void 0!==n.multipleOf&&iF(r,n.multipleOf),void 0!==n.format&&(r.format??(r.format=n.format),n.format.includes("int")&&(r.isInt=!0)),n.mime&&iB(r,n.mime),n.patterns??[]))iZ(r,t);return r}let iK={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iY=new Map([[nA,at],[nO,ar]]),iX=t=>iY.get(t)??t,iQ=(t,r,a,n)=>{a.type="string";let{minimum:i,maximum:o,format:s,patterns:l,contentEncoding:u,laxFormat:c}=iH(t);if("number"==typeof i&&(a.minLength=i),"number"==typeof o&&(a.maxLength=o),s&&(a.format=iK[s]??s,""===a.format&&delete a.format,("time"===s||c)&&delete a.format),u&&(a.contentEncoding=u),l&&l.size>0){let t=[...l].map(iX);1===t.length?a.pattern=t[0].source:t.length>1&&(a.allOf=[...t.map(t=>({..."draft-07"===r.target||"draft-04"===r.target||"openapi-3.0"===r.target?{type:"string"}:{},pattern:t.source}))])}},i0=(t,r,a,n)=>{let{minimum:i,maximum:o,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:u,isInt:c}=iH(t);a.type=c?"integer":"number";let d="number"==typeof u&&u>=(i??-1/0),p="number"==typeof l&&l<=(o??1/0),h="draft-04"===r.target||"openapi-3.0"===r.target;if(d?h?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:"number"==typeof i&&(a.minimum=i),p?h?(a.maximum=l,a.exclusiveMaximum=!0):a.exclusiveMaximum=l:"number"==typeof o&&(a.maximum=o),s){let i=new Set;for(let o of s)Number.isFinite(o)&&0!==o?i.add(Math.abs(o)):iA(t,r,a,n,`A multipleOf divisor of ${o} cannot be represented in JSON Schema`);let[o,...l]=i;void 0!==o&&(a.multipleOf=o),l.length&&(a.allOf=[...a.allOf??[],...l.map(t=>({multipleOf:t}))])}},i1=(t,r,a,n)=>{a.type="boolean"},i2=(t,r,a,n)=>{iA(t,r,a,n,"BigInt cannot be represented in JSON Schema")},i4=(t,r,a,n)=>{"openapi-3.0"===r.target?(a.type="string",a.nullable=!0,a.enum=[null]):a.type="null"},i6=(t,r,a,n)=>{a.not={}},i5=(t,r,a,n)=>{},i9=(t,r,a,n)=>{},i3=(t,r,a,n)=>{let i=eQ(t._zod.def.entries);if(0===i.length){a.not={};return}i.every(t=>"number"==typeof t)&&(a.type="number"),i.every(t=>"string"==typeof t)&&(a.type="string"),a.enum=i},i8=(t,r,a,n)=>{let i=t._zod.def;if(0===i.values.length){a.not={};return}let o=[];for(let s of i.values)if(void 0===s){if(iA(t,r,a,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(iA(t,r,a,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(0===o.length);
57else if(1===o.length){let t=o[0];a.type=null===t?"null":typeof t,"draft-04"===r.target||"openapi-3.0"===r.target?a.enum=[t]:a.const=t}else o.every(t=>"number"==typeof t)&&(a.type="number"),o.every(t=>"string"==typeof t)&&(a.type="string"),o.every(t=>"boolean"==typeof t)&&(a.type="boolean"),o.every(t=>null===t)&&(a.type="null"),a.enum=o},i7=(t,r,a,n)=>{iA(t,r,a,n,"Custom types cannot be represented in JSON Schema")},oe=(t,r,a,n)=>{iA(t,r,a,n,"Transforms cannot be represented in JSON Schema")},ot=(t,r,a,n)=>{let i=t._zod.def,{minimum:o,maximum:s}=iH(t);"number"==typeof o&&(a.minItems=o),"number"==typeof s&&(a.maxItems=s),a.type="array",a.items=iC(i.element,r,{...n,path:[...n.path,"items"]})};function or(t){let r=t._zod.def;return"pipe"===r.type&&r.in._zod.traits.has("$ZodTransform")?or(r.out):"catch"===r.type?or(r.innerType):t._zod.optin}let oa=(t,r,a,n)=>{let i=t._zod.def,o=i.shape;if(Object.getOwnPropertySymbols(o).length&&iA(t,r,a,n,"Symbol keys cannot be represented in JSON Schema"))return;for(let t in a.type="object",a.properties={},o)te(a.properties,t,iC(o[t],r,{...n,path:[...n.path,"properties",t]}));let s=[];for(let t of Object.keys(o)){let a=i.shape[t];("input"===r.io?void 0===or(a):void 0===a._zod.optout)&&s.push(t)}s.length>0&&(a.required=s),i.catchall?._zod.def.type==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=iC(i.catchall,r,{...n,path:[...n.path,"additionalProperties"]})):"output"===r.io&&(a.additionalProperties=!1)},on=(t,r,a,n)=>{let i=t._zod.def,o=!1===i.inclusive,s=i.options.map((t,a)=>iC(t,r,{...n,path:[...n.path,o?"oneOf":"anyOf",a]}));o?a.oneOf=s:a.anyOf=s},oi=(t,r,a,n)=>{let i=t._zod.def,o=iC(i.left,r,{...n,path:[...n.path,"allOf",0]}),s=iC(i.right,r,{...n,path:[...n.path,"allOf",1]}),l=t=>"allOf"in t&&1===Object.keys(t).length,u=[...l(o)?o.allOf:[o],...l(s)?s.allOf:[s]];a.allOf=u,r.intersections.push(u)},oo=new WeakMap,os=(t,r,a,n)=>{let i=t._zod.def;a.type="object";let o=i.keyType,s=iH(o).patterns;if("loose"===i.mode&&s&&s.size>0){let t=iC(i.valueType,r,{...n,path:[...n.path,"patternProperties","*"]});for(let r of(a.patternProperties={},s))te(a.patternProperties,iX(r).source,t)}else{if("draft-07"===r.target||"draft-2020-12"===r.target){a.propertyNames=iC(i.keyType,r,{...n,path:[...n.path,"propertyNames"]});let o=oo.get(r);o||(o=[],oo.set(r,o),r.deferred.push(()=>(function(t){let r=new Map;for(let a of t.seen.values())a.def&&!r.has(a.schema)&&r.set(a.schema,a);let a=new Map;for(let n of oo.get(t)??[]){let i=t.seen.get(n),o=(i?.def??i?.schema)?.propertyNames;if(!o||!0===o||a.has(o))continue;let s=function t(r,a,n){if(a.$ref){if(n.has(a))return a;n.add(a);let i=r.get(a)?.def;if(!i)return a;let o=t(r,i,n);return o===i?a:o}for(let i of["anyOf","oneOf"]){let o=a[i];if(!Array.isArray(o))continue;let s=o.map(a=>t(r,a,n));s.some((t,r)=>t!==o[r])&&(a={...a,[i]:s})}let i=Array.isArray(a.type)?a.type:[a.type],o=!i.includes("string")&&i.some(t=>"number"===t||"integer"===t),s=a.enum??(void 0!==a.const?[a.const]:void 0);if(!o&&!s?.some(t=>"number"==typeof t))return a;let{minimum:l,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:p,format:h,id:f,...m}=a;return m.enum?m.enum=m.enum.map(t=>"number"==typeof t?String(t):t):"number"==typeof m.const&&(m.const=String(m.const)),o&&(m.type="string",s||(m.pattern=(i.includes("number")?ag:am).source)),m}(r,o,new Set);s!==o&&a.set(o,s)}if(a.size)for(let r of t.seen.values())for(let t of[r.schema,r.def]){let r=t&&a.get(t.propertyNames);r&&(t.propertyNames=r)}})(r))),o.push(t)}a.additionalProperties=iC(i.valueType,r,{...n,path:[...n.path,"additionalProperties"]})}let l=o._zod.values,u="input"===r.io&&void 0!==or(i.valueType);if(l&&!i.partial&&!u){let t=[...l].filter(t=>"string"==typeof t||"number"==typeof t);t.length>0&&(a.required=t.map(String))}},ol=(t,r,a,n)=>{let i=t._zod.def,o=iC(i.innerType,r,n),s=r.seen.get(t);"openapi-3.0"===r.target?(s.ref=i.innerType,a.nullable=!0):a.anyOf=[o,{type:"null"}]},ou=(t,r,a,n)=>{let i=t._zod.def;iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType},oc=Symbol();function od(t,r,a,n,i){let o=!1,s=JSON.stringify(t,(t,r)=>"bigint"!=typeof r?r:(o=!0,null));return o?(iA(r,a,n,i,"BigInt defaults cannot be represented in JSON Schema"),oc):JSON.parse(s)}let op=(t,r,a,n)=>{let i=t._zod.def;iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType;let o=od(i.defaultValue,t,r,a,n);o!==oc&&(a.default=o)},oh=(t,r,a,n)=>{let i=t._zod.def;if(iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType,"input"!==r.io)return;let o=od(i.defaultValue,t,r,a,n);o!==oc&&(a._prefault=o)},of=(t,r,a,n)=>{let i,o=t._zod.def;iC(o.innerType,r,n),r.seen.get(t).ref=o.innerType;try{i=o.catchValue(void 0)}catch{iA(t,r,a,n,"Dynamic catch values are not supported in JSON Schema");return}a.default=i},om=(t,r,a,n)=>{let i=t._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s="input"===r.io?o?i.out:i.in:i.out;iC(s,r,n),r.seen.get(t).ref=s},og=(t,r,a,n)=>{let i=t._zod.def;iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType,a.readOnly=!0},oy=(t,r,a,n)=>{let i=t._zod.def;iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType},ov=(t,r,a,n)=>{let i=t._zod.innerType;iC(i,r,n),r.seen.get(t).ref=i},ob={string:iQ,number:i0,boolean:i1,bigint:i2,symbol:(t,r,a,n)=>{iA(t,r,a,n,"Symbols cannot be represented in JSON Schema")},null:i4,undefined:(t,r,a,n)=>{iA(t,r,a,n,"Undefined cannot be represented in JSON Schema")},void:(t,r,a,n)=>{iA(t,r,a,n,"Void cannot be represented in JSON Schema")},never:i6,any:i5,unknown:i9,date:(t,r,a,n)=>{iA(t,r,a,n,"Date cannot be represented in JSON Schema")},enum:i3,literal:i8,nan:(t,r,a,n)=>{iA(t,r,a,n,"NaN cannot be represented in JSON Schema")},template_literal:(t,r,a,n)=>{let i=t._zod.pattern;if(!i)throw Error("Pattern not found in template literal");a.type="string",a.pattern=i.source},file:(t,r,a,n)=>{a.type="string",a.format="binary",a.contentEncoding="binary";let{minimum:i,maximum:o,mime:s}=iH(t);void 0!==i&&(a.minLength=i),void 0!==o&&(a.maxLength=o),s&&(0===s.length?a.not={}:1===s.length?a.contentMediaType=s[0]:a.anyOf=s.map(t=>({contentMediaType:t})))},success:(t,r,a,n)=>{a.type="boolean"},custom:i7,function:(t,r,a,n)=>{iA(t,r,a,n,"Function types cannot be represented in JSON Schema")},transform:oe,map:(t,r,a,n)=>{iA(t,r,a,n,"Map cannot be represented in JSON Schema")},set:(t,r,a,n)=>{iA(t,r,a,n,"Set cannot be represented in JSON Schema")},array:ot,object:oa,union:on,intersection:oi,tuple:(t,r,a,n)=>{let i=t._zod.def;a.type="array";
57let o="draft-2020-12"===r.target?"prefixItems":"items",s="draft-2020-12"===r.target||"openapi-3.0"===r.target?"items":"additionalItems",l=i.items.map((t,a)=>iC(t,r,{...n,path:[...n.path,o,a]})),u=i.rest?iC(i.rest,r,{...n,path:[...n.path,s,..."openapi-3.0"===r.target?[i.items.length]:[]]}):null,c=i.items.length;for(;c>0;){let t=i.items[c-1];if(!("input"===r.io?void 0!==or(t):"optional"===t._zod.optout))break;c--}let d=i.items.length,p=!i.rest;"draft-2020-12"===r.target?(a.prefixItems=l,p?a.items=!1:u&&(a.items=u)):"openapi-3.0"===r.target?(a.items={anyOf:l},u&&a.items.anyOf.push(u)):(a.items=l,p?a.additionalItems=!1:u&&(a.additionalItems=u)),c>0&&(a.minItems=c),p&&(a.maxItems=d);let{minimum:h,maximum:f}=iH(t);"number"==typeof h&&(a.minItems=h),"number"==typeof f&&(a.maxItems=f)},record:os,nullable:ol,nonoptional:ou,default:op,prefault:oh,catch:of,pipe:om,readonly:og,promise:(t,r,a,n)=>{let i=t._zod.def;iC(i.innerType,r,n),r.seen.get(t).ref=i.innerType},optional:oy,lazy:ov};class ow extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function o_(t){}function ok(t,r,a){return 100===a&&97===t.charCodeAt(r+1)&&116===t.charCodeAt(r+2)&&97===t.charCodeAt(r+3)&&58===t.charCodeAt(r+4)}function oE(t,r,a){return 101===a&&118===t.charCodeAt(r+1)&&101===t.charCodeAt(r+2)&&110===t.charCodeAt(r+3)&&116===t.charCodeAt(r+4)&&58===t.charCodeAt(r+5)}class oS extends TransformStream{constructor({onError:t,onRetry:r,onComment:a,maxBufferSize:n}={}){let i;super({start(o){i=function(t){if("function"==typeof t)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:r=o_,onError:a=o_,onRetry:n=o_,onComment:i,maxBufferSize:o}=t,s=[],l=0,u=!0,c,d="",p=0,h,f=!1;function m(){void 0!==o&&(l+d.length<=o||(f=!0,s.length=0,l=0,c=void 0,d="",p=0,h=void 0,a(new ow(`Buffered data exceeded max buffer size of ${o} characters`,{type:"max-buffer-size-exceeded"}))))}function g(t){let a=0;if(-1===t.indexOf("\r")){let n=t.indexOf(` 58`,a);for(;-1!==n;){if(a===n){p>0&&r({id:c,event:h,data:d}),c=void 0,d="",p=0,h=void 0,a=n+1,n=t.indexOf(` 59`,a);continue}let i=t.charCodeAt(a);if(ok(t,a,i)){let i=32===t.charCodeAt(a+5)?a+6:a+5,o=t.slice(i,n);if(0===p&&10===t.charCodeAt(n+1)){r({id:c,event:h,data:o}),c=void 0,d="",h=void 0,a=n+2,n=t.indexOf(` 60`,a);continue}d=0===p?o:`${d} 61${o}`,p++}else oE(t,a,i)?h=t.slice(32===t.charCodeAt(a+6)?a+7:a+6,n)||void 0:y(t,a,n);a=n+1,n=t.indexOf(` 62`,a)}return t.slice(a)}for(;a<t.length;){let r=t.indexOf("\r",a),n=t.indexOf(` 63`,a),i=-1;if(-1!==r&&-1!==n?i=r<n?r:n:-1!==r?i=r===t.length-1?-1:r:-1!==n&&(i=n),-1===i)break;y(t,a,i),a=i+1,13===t.charCodeAt(a-1)&&10===t.charCodeAt(a)&&a++}return t.slice(a)}function y(t,a,n){if(a===n)return void(p>0&&r({id:c,event:h,data:d}),c=void 0,d="",p=0,h=void 0);let o=t.charCodeAt(a);if(ok(t,a,o)){let r=32===t.charCodeAt(a+5)?a+6:a+5,i=t.slice(r,n);d=0===p?i:`${d} 64${i}`,p++;return}if(oE(t,a,o)){h=t.slice(32===t.charCodeAt(a+6)?a+7:a+6,n)||void 0;return}if(105===o&&100===t.charCodeAt(a+1)&&58===t.charCodeAt(a+2)){let r=t.slice(32===t.charCodeAt(a+3)?a+4:a+3,n);c=r.includes("\0")?void 0:r;return}if(58===o){i&&i(t.slice(a,n).slice(32===t.charCodeAt(a+1)?2:1));return}let s=t.slice(a,n),l=s.indexOf(":");if(-1===l)return void v(s,"",s);let u=s.slice(0,l),f=32===s.charCodeAt(l+1)?2:1;v(u,s.slice(l+f),s)}function v(t,r,i){switch(t){case"event":h=r||void 0;break;case"data":d=0===p?r:`${d} 65${r}`,p++;break;case"id":c=r.includes("\0")?void 0:r;break;case"retry":/^\d+$/.test(r)?n(parseInt(r,10)):a(new ow(`Invalid \`retry\` value: "${r}"`,{type:"invalid-retry",value:r,line:i}));break;default:a(new ow(`Unknown field "${t.length>20?`${t.slice(0,20)}\u2026`:t}"`,{type:"unknown-field",field:t,value:r,line:i}))}}return{feed:function(t){if(f)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(u&&(u=!1,239===t.charCodeAt(0)&&187===t.charCodeAt(1)&&191===t.charCodeAt(2)&&(t=t.slice(3))),0===s.length){let r=g(t);""!==r&&(s.push(r),l=r.length),m();return}if(-1===t.indexOf(` 66`)&&-1===t.indexOf("\r")){s.push(t),l+=t.length,m();return}s.push(t);let r=s.join("");s.length=0,l=0;let a=g(r);""!==a&&(s.push(a),l=a.length),m()},reset:function(t={}){if(t.consume&&s.length>0){let t=s.join("");y(t,0,t.length)}u=!0,c=void 0,d="",p=0,h=void 0,s.length=0,l=0,f=!1}}}({onEvent:t=>{o.enqueue(t)},onError(r){"function"==typeof t&&t(r),("terminate"===t||"max-buffer-size-exceeded"===r.type)&&o.error(r)},onRetry:r,onComment:a,maxBufferSize:n})},transform(t){i.feed(t)}})}}let ox=Symbol.for("workflow-serialize"),oI=Symbol.for("workflow-deserialize");function oT(...t){return t.reduce((t,r)=>({...t,...r}),{})}async function oA(t,r){if(null==t)return;let a=r?.abortSignal;return new Promise((r,n)=>{if(a?.aborted)return void n(oC());let i=setTimeout(()=>{o(),r()},t),o=()=>{clearTimeout(i),a?.removeEventListener("abort",s)},s=()=>{o(),n(oC())};a?.addEventListener("abort",s)})}function oC(){return new DOMException("Delay was aborted","AbortError")}var oO=new TextDecoder;async function oM(t){return"string"==typeof t?t:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?oO.decode(t):"u">typeof Blob&&t instanceof Blob?t.text():String(t)}async function oR(t,{highWaterMark:r=1048576,pollIntervalMs:a=20,abortSignal:n}={}){for(;1===t.readyState&&(t.bufferedAmount??0)>r;){if(n?.aborted===!0)return;await oA(a)}}var{btoa:oP,atob:oz}=globalThis;function o$(t){let r=[];for(let a=0;a<t.length;a+=4096)r.push(String.fromCodePoint(...t.subarray(a,a+4096)));return oP(r.join(""))}function oN(t){return Object.fromEntries([...t.headers])}function oj(t=globalThis){return t.window?"runtime/browser":t.navigator?.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}
66`:t.process?.versions?.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function oD(t){return(t instanceof Error||"function"==typeof DOMException&&t instanceof DOMException)&&("AbortError"===t.name||"ResponseAborted"===t.name||"TimeoutError"===t.name)}var oU=["fetch failed","failed to fetch"],oL=new Set(["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"]);function oF({error:t,url:r,requestBodyValues:a}){if(oD(t))return t;if(t instanceof TypeError&&oU.includes(t.message.toLowerCase())){let n=t.cause;if(null!=n)return new ey({message:`Cannot connect to API: ${n.message}`,cause:n,url:r,requestBodyValues:a,isRetryable:!0})}let n=function(t){let r=new Set,a=t;for(;a instanceof Error&&!r.has(a);){r.add(a);let t=a;if("string"==typeof t.code&&oL.has(t.code))return t;a=a.cause}}(t);return null!=n?new ey(ey.isInstance(t)?{message:t.message,cause:t.cause,url:t.url,requestBodyValues:t.requestBodyValues,statusCode:t.statusCode,responseHeaders:t.responseHeaders,responseBody:t.responseBody,data:t.data,isRetryable:!0}:{message:`Cannot connect to API: ${t instanceof Error?t.message:n.message}`,cause:t,url:r,requestBodyValues:a,isRetryable:!0}):t}var oZ="5.0.49";function oB(t){if(null==t)return{};let r={};if(t instanceof Headers)t.forEach((t,a)=>{r[a.toLowerCase()]=t});else for(let[a,n]of(Array.isArray(t)||(t=Object.entries(t)),t))null!=n&&(r[a.toLowerCase()]=n);return r}function oq(t,...r){let a=new Headers(oB(t)),n=a.get("user-agent")||"";return a.set("user-agent",[n,...r].filter(Boolean).join(" ")),Object.fromEntries(a.entries())}async function oV(t){try{await t.body?.cancel()}catch{}}var oJ="AI_DownloadError",oW=`vercel.ai.error.${oJ}`,oG=Symbol.for(oW),oH=class extends(R=eh,M=oG,R){constructor({url:t,statusCode:r,statusText:a,cause:n,message:i=null==n?`Failed to download ${t}: ${r} ${a}`:`Failed to download ${t}: ${n}`}){super({name:oJ,message:i,cause:n}),this[M]=!0,this.url=t,this.statusCode=r,this.statusText=a}static isInstance(t){return eh.hasMarker(t,oW)}};function oK(t,r){try{return new URL(t).origin===new URL(r).origin}catch{return!1}}function oY(t){let r=t.split(".");return 4===r.length&&r.every(t=>{let r=Number(t);return Number.isInteger(r)&&r>=0&&r<=255&&String(r)===t})}function oX(t){let[r,a,n]=t.split(".").map(Number);return 0===r||10===r||100===r&&a>=64&&a<=127||127===r||169===r&&254===a||172===r&&a>=16&&a<=31||192===r&&0===a&&0===n||192===r&&0===a&&2===n||192===r&&168===a||198===r&&(18===a||19===a)||198===r&&51===a&&100===n||203===r&&0===a&&113===n||r>=224||!1}function oQ(t){let r=function(t){let r=t.toLowerCase(),a=r.indexOf("%");-1!==a&&(r=r.slice(0,a));let n=r.split("::");if(n.length>2)return null;let i=t=>{if(""===t)return[];let r=[],a=t.split(":");for(let t=0;t<a.length;t++){let n=a[t];if(n.includes(".")){if(t!==a.length-1||!oY(n))return null;let[i,o,s,l]=n.split(".").map(Number);r.push(i<<8|o,s<<8|l);continue}if(!/^[0-9a-f]{1,4}$/.test(n))return null;r.push(parseInt(n,16))}return r},o=i(n[0]);if(null===o)return null;if(2===n.length){let t=i(n[1]);if(null===t)return null;let r=8-o.length-t.length;return r<0?null:[...o,...Array(r).fill(0),...t]}return 8===o.length?o:null}(t);if(null===r)return!0;let a=t=>r.slice(0,t).every(t=>0===t);
66if(a(7)&&(0===r[7]||1===r[7])||(65024&r[0])==64512||(65472&r[0])==65152||(65472&r[0])==65216||(65280&r[0])==65280||8193===r[0]&&3512===r[1]||16383===r[0]&&(61440&r[1])==0)return!0;if(a(6)||a(5)&&65535===r[5]||a(4)&&65535===r[4]&&0===r[5]||100===r[0]&&65435===r[1]&&0===r[2]&&0===r[3]&&0===r[4]&&0===r[5]||100===r[0]&&65435===r[1]&&1===r[2]){let t=r[6]>>8&255,a=255&r[6],n=r[7]>>8&255,i=255&r[7];return oX(`${t}.${a}.${n}.${i}`)}return!1}async function o0(){let t;return(t=globalThis.process,t?.release?.name!=="node"||t.versions?.bun!=null||t.versions?.deno!=null||"workerd"===t.title||null!=globalThis.EdgeRuntime)?globalThis.fetch:P??=Promise.resolve().then(o1)}function o1(){let t=o2("node:module"),{lookup:r}=o2("node:dns"),{Agent:a,fetch:n}=t.createRequire(function t(){let r=Error.prepareStackTrace;try{Error.prepareStackTrace=(t,r)=>r;let r=Error("Capture current module path");Error.captureStackTrace(r,t);let[a]=r.stack,n=a?.getFileName();if(null==n)throw Error("Unable to determine the current module path");return n}finally{Error.prepareStackTrace=r}}())("undici"),i=new a({connect:{lookup:(t,a,n)=>{r(t,{...a,all:!0},(r,i)=>{if(r)return void n(r);try{let[r]=i;if(null==r)throw Error(`Hostname ${t} did not resolve to an address`);for(let{address:r,family:a}of i)!function({address:t,family:r,hostname:a}){if(4===r?!oY(t)||oX(t):6!==r||oQ(t))throw new oH({url:a,message:`Hostname ${a} resolved to disallowed IP address ${t}`})}({address:r,family:a,hostname:t});!0===a.all?n(null,i):n(null,r.address,r.family)}catch(t){n(t instanceof Error?t:Error(String(t)))}})}}});return(t,r)=>n(t,{...r,dispatcher:i})}function o2(t){let r=globalThis.process,a=r?.getBuiltinModule?.(t);if(null==a)throw Error(`Node.js built-in module ${t} is unavailable`);return a}var o4=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function o6(t){let r=new Headers(t);for(let t of o4)r.delete(t);return r}var o5=new Set([301,302,303,307,308]);async function o9(t){return null==t||t===globalThis.fetch?await o0():t}async function o3({url:t,headers:r,abortSignal:a,maxRedirects:n=10,fetch:i,trustedOrigin:o}){let s=void 0===r?void 0:o6(r),l=t=>{let r={signal:a,redirect:t};return void 0!==s&&(r.headers=new Headers(s)),r},u=t;for(let r=0;r<=n;r++){let r=void 0!==o&&oK(u,o);r||function(t){let r;try{r=new URL(t)}catch{throw new oH({url:t,message:`Invalid URL: ${t}`})}if("data:"===r.protocol)return;if("http:"!==r.protocol&&"https:"!==r.protocol)throw new oH({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});let a=r.hostname.toLowerCase().replace(/\.+$/,"");if(!a)throw new oH({url:t,message:"URL must have a hostname"});if("localhost"===a||a.endsWith(".local")||a.endsWith(".localhost"))throw new oH({url:t,message:`URL with hostname ${a} is not allowed`});if(a.startsWith("[")&&a.endsWith("]")){if(oQ(a.slice(1,-1)))throw new oH({url:t,message:`URL with IPv6 address ${a} is not allowed`});return}if(oY(a)&&oX(a))throw new oH({url:t,message:`URL with IP address ${a} is not allowed`})}(u);let a=r&&null!=i?i:r?globalThis.fetch:await o9(i),n=await a(u,l("manual"));if("opaqueredirect"===n.type){if(!function(t=globalThis){return null!=t.window}())throw new oH({url:t,message:`Redirect from ${u} could not be validated and was blocked`});return await a(u,l("follow"))}let c=n.headers?.get("location");if(o5.has(n.status)&&c){oV(n);let t=new URL(c,u).toString();if(void 0!==s&&!oK(t,u)){let t=s.get("user-agent");s=new Headers(null==t?void 0:{"user-agent":t})}u=t;continue}return n}throw new oH({url:t,message:`Too many redirects (max ${n})`})}var o8=new Set(["accept","accept-language","baggage","cache-control","idempotency-key","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","pragma","range","traceparent","tracestate","user-agent","x-correlation-id","x-request-id"]);async function o7({headers:t,credentialedOrigin:r,untrustedFirstHopHeaders:a,...n}){let i;if(void 0!==t){i=o6(t);let o=r??n.trustedOrigin;if(void 0===o||!oK(n.url,o)){let t=new Set([...o8,...(a??[]).map(t=>t.toLowerCase())]);i=new Headers([...i].filter(([r])=>t.has(r)))}}return o3({...n,headers:i})}async function se({response:t,url:r,maxBytes:a=0x80000000}){let n=t.headers.get("content-length");if(null!=n){let i=parseInt(n,10);if(!isNaN(i)&&i>a)throw await oV(t),new oH({url:r,message:`Download of ${r} exceeded maximum size of ${a} bytes (Content-Length: ${i}).`})}let i=t.body;if(null==i)return new Uint8Array(0);let o=i.getReader(),s=[],l=0;try{for(;;){let{done:t,value:n}=await o.read();if(t)break;
66if((l+=n.length)>a)throw new oH({url:r,message:`Download of ${r} exceeded maximum size of ${a} bytes.`});s.push(n)}}finally{try{await o.cancel()}catch{}finally{o.releaseLock()}}let u=new Uint8Array(l),c=0;for(let t of s)u.set(t,c),c+=t.length;return u}var st=({prefix:t,size:r=16,alphabet:a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let i=()=>{let t=a.length,n=Array(r);for(let i=0;i<r;i++)n[i]=a[Math.random()*t|0];return n.join("")};if(null==t)return i;if(a.includes(n))throw new eT({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${a}".`});return()=>`${t}${n}${i()}`},sr=st(),sa=async({url:t,headers:r={},successfulResponseHandler:a,failedResponseHandler:n,abortSignal:i,fetch:o,validateUrl:s,credentialedOrigin:l,trustedOrigin:u})=>{try{let c=o??globalThis.fetch,d=void 0===l||oK(t,l)?r:{},p=oq(d,`ai-sdk/provider-utils/${oZ}`,oj()),h=s?await o3({url:t,headers:p,abortSignal:i,fetch:o,trustedOrigin:u}):await c(t,{method:"GET",headers:p,signal:i}),f=oN(h);if(!h.ok){let r;try{r=await n({response:h,url:t,requestBodyValues:{}})}catch(r){if(oD(r)||ey.isInstance(r))throw r;throw new ey({message:"Failed to process error response",cause:r,statusCode:h.status,url:t,responseHeaders:f,requestBodyValues:{}})}throw r.value}try{return await a({response:h,url:t,requestBodyValues:{}})}catch(r){if(r instanceof Error&&(oD(r)||ey.isInstance(r)))throw r;throw new ey({message:"Failed to process successful response",cause:r,statusCode:h.status,url:t,responseHeaders:f,requestBodyValues:{}})}}catch(r){throw oF({error:r,url:t,requestBodyValues:{}})}};function sn(t){return null!=t&&"object"==typeof t&&!Array.isArray(t)}function si({settingValue:t,environmentVariableName:r}){return"string"==typeof t?t:null!=t||void 0===ec.default?void 0:null!=(t=ec.default.env[r])&&"string"==typeof t?t:void 0}function so(t){return null!=t&&Number.isSafeInteger(t)&&t>=0}var ss=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,sl=/"(?: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 su(t){let r=JSON.parse(t);return null===r||"object"!=typeof r||!1===ss.test(t)&&!1===sl.test(t)?r:function(t){let r=[t];for(;r.length;){let t=r;for(let a of(r=[],t)){if(Object.prototype.hasOwnProperty.call(a,"__proto__")||Object.prototype.hasOwnProperty.call(a,"constructor")&&null!==a.constructor&&"object"==typeof a.constructor&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let t in a){let n=a[t];n&&"object"==typeof n&&r.push(n)}}}return t}(r)}function sc(t){let{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return su(t)}try{return su(t)}finally{Error.stackTraceLimit=r}}function sd(t){if("object"===t.type||Array.isArray(t.type)&&t.type.includes("object")){let{additionalProperties:r}=t;t.additionalProperties=null!=r&&"boolean"!=typeof r&&sp(r);let{properties:a}=t;if(null!=a)for(let t of Object.keys(a))a[t]=sp(a[t])}null!=t.items&&(t.items=Array.isArray(t.items)?t.items.map(sp):sp(t.items)),null!=t.anyOf&&(t.anyOf=t.anyOf.map(sp)),null!=t.allOf&&(t.allOf=t.allOf.map(sp)),null!=t.oneOf&&(t.oneOf=t.oneOf.map(sp));let{definitions:r}=t;if(null!=r)for(let t of Object.keys(r))r[t]=sp(r[t]);return t}function sp(t){return"boolean"==typeof t?t:sd(t)}var sh=Symbol("Let zodToJsonSchema decide on which parser to use"),sf={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"};function sm(t,r){return sN(t.type._def,r)}var sg=void 0,sy=/^[cC][^\s-]{8,}
66$/,sv=/^[0-9a-z]+$/,sb=/^[0-9A-HJKMNP-TV-Z]{26}$/,sw=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,s_=()=>(void 0===sg&&(sg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),sg),sk=/^(?:(?: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])$/,sE=/^(([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])$/,sS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sx=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sI=/^[a-zA-Z0-9_-]{21}$/,sT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function sA(t,r){let a={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":a.minLength="number"==typeof a.minLength?Math.max(a.minLength,n.value):n.value;break;case"max":a.maxLength="number"==typeof a.maxLength?Math.min(a.maxLength,n.value):n.value;break;case"email":switch(r.emailStrategy){case"format:email":sM(a,"email",n.message,r);break;case"format:idn-email":sM(a,"idn-email",n.message,r);break;case"pattern:zod":sR(a,sw,n.message,r)}break;case"url":sM(a,"uri",n.message,r);break;case"uuid":sM(a,"uuid",n.message,r);break;case"regex":sR(a,n.regex,n.message,r);break;case"cuid":sR(a,sy,n.message,r);break;case"cuid2":sR(a,sv,n.message,r);break;case"startsWith":sR(a,RegExp(`^${sC(n.value,r)}`),n.message,r);break;case"endsWith":sR(a,RegExp(`${sC(n.value,r)}$`),n.message,r);break;case"datetime":sM(a,"date-time",n.message,r);break;case"date":sM(a,"date",n.message,r);break;case"time":sM(a,"time",n.message,r);break;case"duration":sM(a,"duration",n.message,r);break;case"length":a.minLength="number"==typeof a.minLength?Math.max(a.minLength,n.value):n.value,a.maxLength="number"==typeof a.maxLength?Math.min(a.maxLength,n.value):n.value;break;case"includes":sR(a,RegExp(sC(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&sM(a,"ipv4",n.message,r),"v4"!==n.version&&sM(a,"ipv6",n.message,r);break;case"base64url":sR(a,sx,n.message,r);break;case"jwt":sR(a,sT,n.message,r);break;case"cidr":"v6"!==n.version&&sR(a,sk,n.message,r),"v4"!==n.version&&sR(a,sE,n.message,r);break;case"emoji":sR(a,s_(),n.message,r);break;case"ulid":sR(a,sb,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":sM(a,"binary",n.message,r);break;case"contentEncoding:base64":a.contentEncoding="base64";break;case"pattern:zod":sR(a,sS,n.message,r)}break;case"nanoid":sR(a,sI,n.message,r)}return a}function sC(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let a=0;a<t.length;a++)sO.has(t[a])||(r+="\\"),r+=t[a];return r}(t):t}var sO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sM(t,r,a,n){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...a&&n.errorMessages&&{errorMessage:{format:a}}})):t.format=r}function sR(t,r,a,n){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:sP(r,n),...a&&n.errorMessages&&{errorMessage:{pattern:a}}})):t.pattern=sP(r,n)}function sP(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source,i="",o=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(o){i+=n[t],o=!1;continue}if(a.i){if(s){if(n[t].match(/[a-z]/)){l?(i+=n[t],i+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(i+=n[t],l=!0):i+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){i+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(a.m){if("^"===n[t]){i+=`(^|(?<=[\r 67]))`;continue}else if("$"===n[t]){i+=`($|(?=[\r 68]))`;continue}}if(a.s&&"."===n[t]){i+=s?`${n[t]}\r 69`:`[${n[t]}\r 70]`;continue}i+=n[t],"\\"===n[t]?o=!0:s&&"]"===n[t]?s=!1:s||"["!==n[t]||(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function sz(t,r){let a={type:"object",additionalProperties:sN(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if(t.keyType?._def.typeName==="ZodString"&&t.keyType._def.checks?.length){let{type:n,...i}=sA(t.keyType._def,r);return{...a,propertyNames:i}}if(t.keyType?._def.typeName==="ZodEnum")return{...a,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName==="ZodBranded"&&"ZodString"===t.keyType._def.type._def.typeName&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=sm(t.keyType._def,r);return{...a,propertyNames:i}}return a}var s$={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sN(t,r,a=!1){let n=r.seen.get(t);if(r.override){let i=r.override?.(t,r,n,a);if(i!==sh)return i}if(n&&!a){let t=sj(n,r);if(void 0!==t)return t}let i={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,i);let o=((t,r,a)=>{switch(r){case"ZodString":return sA(t,a);case"ZodNumber":let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer";break;case"min":r.inclusive?n.minimum=r.value:n.exclusiveMinimum=r.value;break;case"max":r.inclusive?n.maximum=r.value:n.exclusiveMaximum=r.value;break;case"multipleOf":n.multipleOf=r.value}return n;case"ZodObject":return function(t,r){let a={type:"object",properties:{}},n=[],i=t.shape();for(let t in i){let o=i[t];if(void 0===o||void 0===o._def)continue;let s=function(t){try{return t.isOptional()}catch{return!0}}(o),l=sN(o._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==l&&(a.properties[t]=l,s||n.push(t))}n.length&&(a.required=n);let o=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return sN(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(t,r);return void 0!==o&&(a.additionalProperties=o),a}(t,a);case"ZodBigInt":let i={type:"integer",format:"int64"};if(!t.checks)return i;for(let r of t.checks)switch(r.kind){case"min":r.inclusive?i.minimum=r.value:i.exclusiveMinimum=r.value;break;case"max":r.inclusive?i.maximum=r.value:i.exclusiveMaximum=r.value;break;case"multipleOf":i.multipleOf=r.value}return i;
70case"ZodBoolean":return{type:"boolean"};case"ZodDate":return function t(r,a,n){let i=n??a.dateStrategy;if(Array.isArray(i))return{anyOf:i.map(n=>t(r,a,n))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var o=r;let s={type:"integer",format:"unix-time"};for(let t of o.checks)switch(t.kind){case"min":s.minimum=t.value;break;case"max":s.maximum=t.value}return s}}(t,a);case"ZodUndefined":case"ZodNaN":case"ZodNever":return{not:{}};case"ZodNull":return{type:"null"};case"ZodArray":let o;return o={type:"array"},t.type?._def&&t.type?._def?.typeName!=="ZodAny"&&(o.items=sN(t.type._def,{...a,currentPath:[...a.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o;case"ZodUnion":case"ZodDiscriminatedUnion":var s,l;let u,c=t.options instanceof Map?Array.from(t.options.values()):t.options;if(c.every(t=>t._def.typeName in s$&&(!t._def.checks||!t._def.checks.length))){let t=c.reduce((t,r)=>{let a=s$[r._def.typeName];return a&&!t.includes(a)?[...t,a]:t},[]);return{type:t.length>1?t:t[0]}}if(c.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){let t=c.reduce((t,r)=>{let a=typeof r._def.value;switch(a){case"string":case"number":case"boolean":return[...t,a];case"bigint":return[...t,"integer"];case"object":if(null===r._def.value)return[...t,"null"];default:return t}},[]);if(t.length===c.length){let r=t.filter((t,r,a)=>a.indexOf(t)===r);return{type:r.length>1?r:r[0],enum:c.reduce((t,r)=>t.includes(r._def.value)?t:[...t,r._def.value],[])}}}else if(c.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:c.reduce((t,r)=>[...t,...r._def.values.filter(r=>!t.includes(r))],[])};return s=t,l=a,(u=(s.options instanceof Map?Array.from(s.options.values()):s.options).map((t,r)=>sN(t._def,{...l,currentPath:[...l.currentPath,"anyOf",`${r}`]})).filter(t=>!!t&&(!l.strictUnions||"object"==typeof t&&Object.keys(t).length>0))).length?{anyOf:u}:void 0;case"ZodIntersection":let d,p;return d=[sN(t.left._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),sN(t.right._def,{...a,currentPath:[...a.currentPath,"allOf","1"]})].filter(t=>!!t),p=[],d.forEach(t=>{if((!("type"in t)||"string"!==t.type)&&"allOf"in t)p.push(...t.allOf);else{let r=t;if("additionalProperties"in t&&!1===t.additionalProperties){let{additionalProperties:a,...n}=t;r=n}p.push(r)}}),p.length?{allOf:p}:void 0;case"ZodTuple":return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>sN(t._def,{...a,currentPath:[...a.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:sN(t.rest._def,{...a,currentPath:[...a.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>sN(t._def,{...a,currentPath:[...a.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case"ZodRecord":return sz(t,a);case"ZodLiteral":let h;return"bigint"!=(h=typeof t.value)&&"number"!==h&&"boolean"!==h&&"string"!==h?{type:Array.isArray(t.value)?"array":"object"}:{type:"bigint"===h?"integer":h,const:t.value};case"ZodEnum":return{type:"string",enum:Array.from(t.values)};case"ZodNativeEnum":let f,m,g;return f=t.values,{type:1===(g=Array.from(new Set((m=Object.keys(t.values).filter(t=>"number"!=typeof f[f[t]]).map(t=>f[t])).map(t=>typeof t)))).length?"string"===g[0]?"string":"number":["string","number"],enum:m};case"ZodNullable":if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[s$[t.innerType._def.typeName],"null"]};let y=sN(t.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","0"]});return y&&{anyOf:[y,{type:"null"}]};case"ZodOptional":if(a.currentPath.toString()===a.propertyPath?.toString())return sN(t.innerType._def,a);let v=sN(t.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","1"]});return v?{anyOf:[{not:{}},v]}:{};case"ZodMap":if("record"===a.mapStrategy)return sz(t,a);return{type:"array",maxItems:125,items:{type:"array",items:[sN(t.keyType._def,{...a,currentPath:[...a.currentPath,"items","items","0"]})||{},sN(t.valueType._def,{...a,currentPath:[...a.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}};case"ZodSet":let b;return b={type:"array",uniqueItems:!0,items:sN(t.valueType._def,{...a,currentPath:[...a.currentPath,"items"]})},t.minSize&&(b.minItems=t.minSize.value),t.maxSize&&(b.maxItems=t.maxSize.value),b;case"ZodLazy":return()=>t.getter()._def;case"ZodPromise":return sN(t.type._def,a);case"ZodEffects":return"input"===a.effectStrategy?sN(t.schema._def,a):{};case"ZodAny":case"ZodUnknown":return{};case"ZodDefault":return{...sN(t.innerType._def,a),default:t.defaultValue()};case"ZodBranded":return sm(t,a);case"ZodReadonly":case"ZodCatch":return sN(t.innerType._def,a);case"ZodPipeline":if("input"===a.pipeStrategy)return sN(t.in._def,a);if("output"===a.pipeStrategy)return sN(t.out._def,a);let w=sN(t.in._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),_=sN(t.out._def,{...a,currentPath:[...a.currentPath,"allOf",w?"1":"0"]});return{allOf:[w,_].filter(t=>void 0!==t)};default:return}})(t,t.typeName,r),s="function"==typeof o?sN(o(),r):o;if(s&&sD(t,r,s),r.postProcess){let a=r.postProcess(s,t,r);return i.jsonSchema=s,a}return i.jsonSchema=s,s}var sj=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:((t,r)=>{let a=0;for(;a<t.length&&a<r.length&&t[a]===r[a];a++);return[(t.length-a).toString(),...r.slice(a)].join("/")})(r.currentPath,t.path)};case"none":case"seen":if(t.path.length<r.currentPath.length&&t.path.every((t,a)=>r.currentPath[a]===t))return console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),{};return"seen"===r.$refStrategy?{}:void 0}},sD=(t,r,a)=>(t.description&&(a.description=t.description),a),sU=Symbol.for("vercel.ai.schema");function sL(t){let r;return()=>(null==r&&(r=t()),r)}function sF(t,{validate:r}={}){return{[sU]:!0,_type:void 0,get jsonSchema(){return"function"==typeof t&&(t=t()),t},validate:r}}function sZ(t){var r;return null==t?sF({type:"object",properties:{},additionalProperties:!1}):"object"==typeof t&&null!==t&&sU in t&&!0===t[sU]&&"jsonSchema"in t&&"validate"in t?t:"~standard"in t?"zod"===t["~standard"].vendor?sB(t):(r=t,sF(()=>
70{if(null==r["~standard"].jsonSchema)throw Error(`Standard schema vendor '${r["~standard"].vendor}' does not support JSON Schema conversion.`);return sd(r["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async t=>{let a=await r["~standard"].validate(t);return"value"in a?{success:!0,value:a.value}:{success:!1,error:new eZ({value:t,cause:a.issues})}}})):t()}function sB(t,r){let a;if("_zod"in t){let a;return a=r?.useReferences??!1,sF(()=>sd(function(t,r){if("_idmap"in t){let a=iT({...r,processors:ob}),n={};for(let r of t._idmap.entries()){let[t,n]=r;iC(n,a)}let i={};for(let o of(a.external={registry:t,uri:r?.uri,defs:n},t._idmap.entries())){let[t,r]=o;iM(a,r),te(i,t,iN(a,r))}return Object.keys(n).length>0&&(i.__shared={["draft-2020-12"===a.target?"$defs":"definitions"]:n}),{schemas:i}}let a=iT({...r,processors:ob});return iC(t,a),iM(a,t),iN(a,t)}(t,{target:"draft-7",io:"input",reused:a?"ref":"inline"})),{validate:async r=>{let a=await r$(t,r);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}return a=r?.useReferences??!1,sF(()=>((t,r)=>{let a,n,i=(n=void 0!==(a="string"==typeof r?{...sf,name:r}:{...sf,...r}).name?[...a.basePath,a.definitionPath,a.name]:a.basePath,{...a,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(a.definitions).map(([t,r])=>[r._def,{def:r._def,path:[...a.basePath,a.definitionPath,t],jsonSchema:void 0}]))}),o="object"==typeof r&&r.definitions?Object.entries(r.definitions).reduce((t,[r,a])=>({...t,[r]:sN(a._def,{...i,currentPath:[...i.basePath,i.definitionPath,r]},!0)??{}}),{}):void 0,s="string"==typeof r?r:r?.nameStrategy==="title"?void 0:r?.name,l=sN(t._def,void 0===s?i:{...i,currentPath:[...i.basePath,i.definitionPath,s]},!1)??{},u="object"==typeof r&&void 0!==r.name&&"title"===r.nameStrategy?r.name:void 0;void 0!==u&&(l.title=u);let c=void 0===s?o?{...l,[i.definitionPath]:o}:l:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,s].join("/"),[i.definitionPath]:{...o,[s]:l}};return c.$schema="http://json-schema.org/draft-07/schema#",c})(t,{$refStrategy:a?"root":"none"}),{validate:async r=>{let a=await t.safeParseAsync(r);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}async function sq({value:t,schema:r,context:a}){let n=await sV({value:t,schema:r,context:a});if(!n.success)throw eZ.wrap({value:t,cause:n.error,context:a});return n.value}async function sV({value:t,schema:r,context:a}){let n=sZ(r);try{if(null==n.validate)return{success:!0,value:t,rawValue:t};let r=await n.validate(t);if(r.success)return{success:!0,value:r.value,rawValue:t};return{success:!1,error:eZ.wrap({value:t,cause:r.error,context:a}),rawValue:t}}catch(r){return{success:!1,error:eZ.wrap({value:t,cause:r,context:a}),rawValue:t}}}async function sJ({text:t,schema:r}){try{let a=sc(t);if(null==r)return a;return await sq({value:a,schema:r})}catch(r){if(eR.isInstance(r)||eZ.isInstance(r))throw r;throw new eR({text:t,cause:r})}}async function sW({text:t,schema:r}){try{let a=sc(t);if(null==r)return{success:!0,value:a,rawValue:a};return await sV({value:a,schema:r})}catch(r){return{success:!1,error:eR.isInstance(r)?r:new eR({text:t,cause:r}),rawValue:void 0}}}function sG({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new oS).pipeThrough(new TransformStream({async transform({data:t},a){"[DONE]"!==t&&a.enqueue(await sW({text:t,schema:r}))}}))}async function sH({provider:t,providerOptions:r,schema:a}){if(r?.[t]==null)return;let n=await sV({value:r[t],schema:a});if(!n.success)throw new eT({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var sK=()=>globalThis.fetch,sY=async({url:t,headers:r,body:a,failedResponseHandler:n,successfulResponseHandler:i,abortSignal:o,fetch:s})=>await sX({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(a),values:a},failedResponseHandler:n,successfulResponseHandler:i,abortSignal:o,fetch:s}),sX=async({url:t,headers:r={},body:a,successfulResponseHandler:n,failedResponseHandler:i,abortSignal:o,fetch:s=sK()})=>{try{let l=await s(t,{method:"POST",headers:oq(r,`ai-sdk/provider-utils/${oZ}`,oj()),body:a.content,signal:o}),u=oN(l);if(!l.ok){let r;try{r=await i({response:l,url:t,requestBodyValues:a.values})}catch(r){if(oD(r)||ey.isInstance(r))throw r;throw new ey({message:"Failed to process error response",cause:r,statusCode:l.status,url:t,responseHeaders:u,requestBodyValues:a.values})}throw r.value}try{return await n({response:l,url:t,requestBodyValues:a.values})}catch(r){if(r instanceof Error&&(oD(r)||ey.isInstance(r)))throw r;throw new ey({message:"Failed to process successful response",cause:r,statusCode:l.status,url:t,responseHeaders:u,requestBodyValues:a.values})}}catch(r){throw oF({error:r,url:t,requestBodyValues:a.values})}};
70function sQ({id:t,inputSchema:r,outputSchema:a,supportsDeferredResults:n}){return({onInputStart:i,onInputDelta:o,onInputAvailable:s,...l})=>({type:"provider",isProviderExecuted:!0,id:t,args:l,inputSchema:r,outputSchema:a,onInputStart:i,onInputDelta:o,onInputAvailable:s,supportsDeferredResults:n})}async function s0(t){return"function"==typeof t&&(t=t()),t}var s1=new TextDecoder;async function s2({response:t,url:r}){return s1.decode(await se({response:t,url:r}))}var s4=({errorSchema:t,errorToMessage:r,isRetryable:a})=>async({response:n,url:i,requestBodyValues:o})=>{let s=await s2({response:n,url:i}),l=oN(n);if(""===s.trim())return{responseHeaders:l,value:new ey({message:n.statusText,url:i,requestBodyValues:o,statusCode:n.status,responseHeaders:l,responseBody:s,isRetryable:a?.(n)})};try{let u=await sJ({text:s,schema:t});return{responseHeaders:l,value:new ey({message:r(u),url:i,requestBodyValues:o,statusCode:n.status,responseHeaders:l,responseBody:s,data:u,isRetryable:a?.(n,u)})}}catch{return{responseHeaders:l,value:new ey({message:n.statusText,url:i,requestBodyValues:o,statusCode:n.status,responseHeaders:l,responseBody:s,isRetryable:a?.(n)})}}},s6=t=>async({response:r,url:a,requestBodyValues:n})=>{let i=await s2({response:r,url:a}),o=await sW({text:i,schema:t}),s=oN(r);if(!o.success)throw new ey({message:"Invalid JSON response",cause:o.error,statusCode:r.status,responseHeaders:s,responseBody:i,url:a,requestBodyValues:n});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}};async function*s5({stream:t,schema:r}){let a=t.getReader(),n=new TextDecoder,i="",o=!1;try{for(;;){let{done:t,value:s}=await a.read();if(t){o=!0,i+=n.decode();break}let l=(i+=n.decode(s,{stream:!0})).indexOf("\n");for(;-1!==l;){let t=i.slice(0,l).replace(/\r$/,"");i=i.slice(l+1),t.trim().length>0&&(yield await sJ({text:t,schema:r})),l=i.indexOf("\n")}}let t=i.replace(/\r$/,"");t.trim().length>0&&(yield await sJ({text:t,schema:r}))}finally{o||await a.cancel().catch(()=>{}),a.releaseLock()}}function s9(t){if(null==t)return!0;let r=typeof t;return"string"===r||"number"===r||"boolean"===r||"function"!==r&&"symbol"!==r&&"bigint"!==r&&(Array.isArray(t)?t.every(s9):Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(s9))}var s3="AI_SerializationError",s8=`vercel.ai.error.${s3}`,s7=Symbol.for(s8),le=class extends($=eh,z=s7,$){constructor({message:t="Failed to serialize value.",cause:r}={}){super({name:s3,message:t,cause:r}),this[z]=!0}static isInstance(t){return eh.hasMarker(t,s8)}};function lt(t){let r={};for(let[a,n]of Object.entries(t.config))if("headers"===a){let t=function(t){let r=t;if("function"==typeof t&&(r=t()),r instanceof Promise)throw new le({message:"Cannot serialize asynchronous model options."});return r}(n);s9(t)&&(r[a]=t)}else s9(n)&&(r[a]=n);return{modelId:t.modelId,config:r}}function lr(t){return"string"==typeof t}function la(t){return"number"==typeof t}function ln(t,r){return void 0===t||r(t)}function li(t){return sn(t)&&lr(t.type)}function lo(t){return sn(t)&&lr(t.text)&&la(t.startSecond)&&la(t.endSecond)}var ls=t.i(64699);class ll extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let lu="~memo",lc=[];function ld(t){return null!==t&&"object"==typeof t}function lp(t){return t.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}let lh=new WeakMap,lf=[],lm={alloc(t,r,n){let i=a;if(!i)return n;a=void 0;let o={value:n,issues:null};return i.set(r.value,o),lf.push(o),n},guard(t){var r;(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred.push(()=>{let r=t._zod.parse,a=(t,a)=>{var n,i;let o;if("backward"!==a.direction&&(n=a,i=t.value,void 0!==(o=n[lu]?.backEdges)&&ld(i)&&o.has(i)))throw new ll;return r(t,a)};t._zod.parse=a,t._zod.run===r&&(t._zod.run=a)})},attach(t){var r;let n,i,o,s=!1;(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred.push(()=>{let r=t._zod.parse,l=(u,c)=>{let d;if(void 0===n){let a=function t(r,a,n){var i,o;let s=lh.get(r);if(void 0!==s)return 2*!!s;if(a.has(r))return 2;a.add(r);let l=0,u=r=>{if(2!==l&&r?._zod){let i=t(r,a,n);i>l&&(l=i)}},c=t=>{t>l&&(l=t)},d=r._zod.def;switch(d.type){case"object":{let r=tt(d);c(r?((r,i)=>{let o=0;for(let s of Reflect.ownKeys(r)){let l=Object.getOwnPropertyDescriptor(r,s);if(i&&!l.enumerable)continue;let u=l.get?1:l.value?._zod?t(l.value,a,n):0;u>o&&(o=u)}return o}
70)(r,!0):1),u(d.catchall);break}case"array":u(d.element);break;case"tuple":for(let t of d.items)u(t);u(d.rest);break;case"record":case"map":u(d.keyType),u(d.valueType);break;case"set":u(d.valueType);break;case"union":for(let t of d.options)u(t);break;case"intersection":u(d.left),u(d.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":u(d.innerType);break;case"pipe":u(d.in),u(d.out);break;case"function":u(d.input),u(d.output);break;case"lazy":{let i=d._cachedInner??(n?r._zod.innerType:void 0);c(i?t(i,a,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let t in d){let r=Object.getOwnPropertyDescriptor(d,t);if(!r||r.get)continue;let a=r.value;if(a&&"object"==typeof a){if(a._zod)u(a);else if(Array.isArray(a))for(let t of a)u(t)}}}return a.delete(r),i=r,1!==(o=l)&&lh.set(i,2===o),o}(t,new Set,!1);if(0===a)return t._zod.parse=r,t._zod.run===l&&(t._zod.run=r),r(u,c);2===a||s?n=!0:s=!0}let p=u.value;if(!ld(p))return r(u,c);let h=c[lu];if(h||(h={buckets:new WeakMap,backEdges:void 0},c[lu]=h),i===c)d=o;else{var f;let r;(r=(f=h).buckets.get(t))||(r=new WeakMap,f.buckets.set(t,r)),d=r,i=c,o=d}let m=d.get(p);if(m)return u.value=m.value,m.issues?m.issues.length&&u.issues.push(...lp(m.issues)):(u.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(m.value)),u;a=d;let g=lf.length,y=r(u,c);a=void 0;let v=lf.length>g?lf.pop():void 0;return y instanceof Promise?y.then(t=>(v&&(v.issues=t.issues.length?lp(t.issues):lc),t)):(v&&(v.issues=y.issues.length?lp(y.issues):lc),y)};t._zod.parse=l,t._zod.run===r&&(t._zod.run=l)})}};function lg(t){return t.checks&&(t.checks=[...t.checks]),t}function ly(t,r){return new aD({check:"less_than",...tS(r),value:t,inclusive:!1})}function lv(t,r){return new aD({check:"less_than",...tS(r),value:t,inclusive:!0})}function lb(t,r){return new aU({check:"greater_than",...tS(r),value:t,inclusive:!1})}function lw(t,r){return new aU({check:"greater_than",...tS(r),value:t,inclusive:!0})}function l_(t,r){return new aL({check:"multiple_of",...tS(r),value:t})}function lk(t,r){return new aJ({check:"max_length",...tS(r),maximum:t})}function lE(t,r){return new aW({check:"min_length",...tS(r),minimum:t})}function lS(t,r){return new aG({check:"length_equals",...tS(r),length:t})}function lx(t){return new a6({check:"overwrite",tx:t})}t.i(15417);var lI=t.i(99918),lI=lI;function lT(){rc.memoizer||rd({memoizer:lm})}let lA=rs("ZodType",(t,r)=>(rc.localeError||rd({localeError:(()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}},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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},a={nan:"NaN"};function n(t,r){return"number"!==t||"number"!=typeof r||Number.isFinite(r)?a[t]??t:String(r)}return a=>{switch(a.code){case"invalid_type":{let t=n(a.expected),r=n(tH(a.input),a.input);return`Invalid input: expected ${t}, received ${r}`}case"invalid_value":if(1===a.values.length)return`Invalid input: expected ${tI(a.values[0])}`;return`Invalid option: expected one of ${e0(a.values,"|")}`;case"too_big":{let r=a.exact?"exactly ":a.inclusive?"<=":"<",n=t[a.origin]??null;if(n)return`Too big: expected ${a.origin??"value"} to have ${r}${a.maximum.toString()} ${n.unit??"elements"}`;return`Too big: expected ${a.origin??"value"} to be ${r}${a.maximum.toString()}`}case"too_small":{let r=a.exact?"exactly ":a.inclusive?">=":">",n=t[a.origin]??null;if(n)return`Too small: expected ${a.origin} to have ${r}${a.minimum.toString()} ${n.unit}`;return`Too small: expected ${a.origin} to be ${r}${a.minimum.toString()}`}
70case"invalid_format":if("starts_with"===a.format)return`Invalid string: must start with "${a.prefix}"`;if("ends_with"===a.format)return`Invalid string: must end with "${a.suffix}"`;if("includes"===a.format)return`Invalid string: must include "${a.includes}"`;if("regex"===a.format)return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${r[a.format]??a.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${a.divisor}`;case"unrecognized_keys":return`Unrecognized key${a.keys.length>1?"s":""}: ${e0(a.keys,", ")}`;case"invalid_key":return`Invalid key in ${a.origin}`;case"invalid_union":if(a.options&&Array.isArray(a.options)&&a.options.length>0){let t=a.options.map(t=>`'${t}'`).join(" | ");return`Invalid discriminator value. Expected ${t}`}if(!1===a.inclusive)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${a.origin}`;default:return"Invalid input"}}})()}),a3.init(t,r),t.def=r,t.type=r.type,t),{check(...t){let r=this.def;return this.clone(lI.mergeDefs(r,{checks:[...r.checks??[],...t.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,r){return tE(this,t,r)},brand(){return this},register(t,r){return t.add(this,r),this},refine(t,r){return this.check(function(t,r={}){return new uP({type:"custom",check:"custom",fn:t,...tS(r)})}(t,r))},superRefine(t,r){return this.check(function(t,r){var a;let n,i;return a=r=>(r.addIssue=t=>{"string"==typeof t?r.issues.push(tK(t,r.value,n._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=r.value),t.inst??(t.inst=n),t.continue??(t.continue=!n._zod.def.abort),r.issues.push(tK(t)))},t(r.value,r)),(i=new az({check:"custom",...tS(r)}))._zod.check=a,n=i}(t,r))},overwrite(t){return this.check(lx(t))},optional(){return u_(this)},exactOptional(){var t;return t=this,new uk({type:"optional",innerType:t})},nullable(){return uS(this)},nullish(){return u_(uS(this))},nonoptional(t){var r,a;return r=this,a=t,new uT({type:"nonoptional",innerType:r,...lI.normalizeParams(a)})},array(){return ui(this)},or(t){return uu([this,t])},and(t){var r;return r=this,new up({type:"intersection",left:r,right:t})},transform(t){return uO(this,new ub({type:"transform",transform:t}))},default(t){var r,a;return r=this,a=t,new ux({type:"default",innerType:r,get defaultValue(){return"function"==typeof a?a():lI.shallowClone(a)}})},prefault(t){var r,a;return r=this,a=t,new uI({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof a?a():lI.shallowClone(a)}})},catch(t){var r,a;return r=this,new uA({type:"catch",innerType:r,catchValue:"function"==typeof(a=t)?a:lI.constantCatch(a)})},pipe(t){return uO(this,t)},readonly(){var t;return t=this,new uM({type:"readonly",innerType:t})},describe(t){let r=this.clone();return ix.add(r,{description:t}),r},meta(...t){if(0===t.length)return ix.get(this);let r=this.clone();return ix.add(r,t[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...r){return 0===r.length?t(this):t(this,...r)},get"~standard"(){return lI.hide(this,"~standard",{...ne(this),jsonSchema:{input:ij(this,"input"),output:ij(this,"output")}})},set"~standard"(value){lI.own(this,"~standard",value)},parse:function t(r,a){return rR(this,r,a,{callee:t})},parseAsync:async function t(r,a){return await rP(this,r,a,{callee:t})},safeParse(t,r){return rz(this,t,r)},async safeParseAsync(t,r){return r$(this,t,r)},get spa(){return this?.safeParseAsync},set spa(value){lI.own(this,"spa",value)},validate(t,r){let a=this._zod.bag.validator;if(void 0!==a){if(a(t)!==rI)return!0;if(!0===a.definite&&void 0===r)return!1}return function(t,r,a){let n,i=a?{...a,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=t._zod.bag.fallbackRun;if(o?(i[rT]=!0,n=o({value:r,issues:[]},i)):n=t._zod.run({value:r,issues:[]},i),n instanceof Promise)throw new rl;return 0===n.issues.length}(this,t,r)},validateAsync(t,r){return rA(this,t,r)},encode:function t(r,a){return rN(this,r,a,{callee:t})},decode:function t(r,a){return rj(this,r,a,{callee:t})},encodeAsync:async function t(r,a){return await rD(this,r,a,{callee:t})},decodeAsync:async function t(r,a){return await rU(this,r,a,{callee:t})},safeEncode(t,r){return rL(this,t,r)},safeDecode(t,r){return rF(this,t,r)},async safeEncodeAsync(t,r){return rZ(this,t,r)},async safeDecodeAsync(t,r){return rB(this,t,r)},toJSONSchema(t){return((t,r={})=>a=>{let n=iT({...a,processors:r});return iC(t,n),iM(n,t),iN(n,t)})(this,{})(t)},get description(){return ix.get(this)?.description},get _def(){return this._zod.def}}),lC=rs("_ZodString",(t,r)=>{nt.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>iQ(t,r,a,n)},lI.derived({format:t=>iH(t).format??null,minLength:t=>iH(t).minimum??null,maxLength:t=>iH(t).maximum??null},{regex(...t){return this.check(function(t,r){return new aK({check:"string_format",format:"regex",...tS(r),pattern:t})}(...t))},includes(...t){return this.check(function(t,r){return new aQ({check:"string_format",format:"includes",...tS(r),includes:t})}(...t))},startsWith(...t){return this.check(function(t,r){return new a0({check:"string_format",format:"starts_with",...tS(r),prefix:t})}(...t))},endsWith(...t){return this.check(function(t,r){return new a1({check:"string_format",format:"ends_with",...tS(r),suffix:t})}(...t))},min(...t){return this.check(lE(...t))},max(...t){return this.check(lk(...t))},length(...t){return this.check(lS(...t))},nonempty(...t){return this.check(lE(1,...t))},lowercase(t){return this.check(new aY({check:"string_format",format:"lowercase",...tS(t)}))},uppercase(t){return this.check(new aX({check:"string_format",format:"up
70percase",...tS(t)}))},trim(){return this.check(lx(t=>t.trim()))},normalize(...t){return this.check(function(t){return lx(r=>r.normalize(t))}(...t))},toLowerCase(){return this.check(lx(t=>t.toLowerCase()))},toUpperCase(){return this.check(lx(t=>t.toUpperCase()))},slugify(){return this.check(lx(t=>tp(t)))}})),lO=rs("ZodString",(t,r)=>{nt.init(t,r),lC.init(t,r)},{email(t){return this.check(new lj({type:"string",format:"email",check:"string_format",abort:!1,...tS(t)}))},url(t){return this.check(new lL({type:"string",format:"url",check:"string_format",abort:!1,...tS(t)}))},jwt(t){return this.check(new l1({type:"string",format:"jwt",check:"string_format",abort:!1,...tS(t)}))},emoji(t){return this.check(new lF({type:"string",format:"emoji",check:"string_format",abort:!1,...tS(t)}))},guid(t){return this.check(new lD({type:"string",format:"guid",check:"string_format",abort:!1,...tS(t)}))},uuid(t){return this.check(new lU({type:"string",format:"uuid",check:"string_format",abort:!1,...tS(t)}))},uuidv4(t){return this.check(new lU({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...tS(t)}))},uuidv6(t){return this.check(new lU({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...tS(t)}))},uuidv7(t){return this.check(new lU({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...tS(t)}))},nanoid(t){return this.check(new lZ({type:"string",format:"nanoid",check:"string_format",abort:!1,...tS(t)}))},cuid(t){return this.check(new lB({type:"string",format:"cuid",check:"string_format",abort:!1,...tS(t)}))},cuid2(t){return this.check(new lq({type:"string",format:"cuid2",check:"string_format",abort:!1,...tS(t)}))},ulid(t){return this.check(new lV({type:"string",format:"ulid",check:"string_format",abort:!1,...tS(t)}))},base64(t){return this.check(new lX({type:"string",format:"base64",check:"string_format",abort:!1,...tS(t)}))},base64url(t){return this.check(new lQ({type:"string",format:"base64url",check:"string_format",abort:!1,...tS(t)}))},xid(t){return this.check(new lJ({type:"string",format:"xid",check:"string_format",abort:!1,...tS(t)}))},ksuid(t){return this.check(new lW({type:"string",format:"ksuid",check:"string_format",abort:!1,...tS(t)}))},ipv4(t){return this.check(new lG({type:"string",format:"ipv4",check:"string_format",abort:!1,...tS(t)}))},ipv6(t){return this.check(new lH({type:"string",format:"ipv6",check:"string_format",abort:!1,...tS(t)}))},cidrv4(t){return this.check(new lK({type:"string",format:"cidrv4",check:"string_format",abort:!1,...tS(t)}))},cidrv6(t){return this.check(new lY({type:"string",format:"cidrv6",check:"string_format",abort:!1,...tS(t)}))},e164(t){return this.check(new l0({type:"string",format:"e164",check:"string_format",abort:!1,...tS(t)}))},datetime(t){return this.check(new lP({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...tS(t)}))},date(t){return this.check(new lz({type:"string",format:"date",check:"string_format",...tS(t)}))},time(t){return this.check(new l$({type:"string",format:"time",check:"string_format",precision:null,...tS(t)}))},duration(t){return this.check(new lN({type:"string",format:"duration",check:"string_format",...tS(t)}))}});function lM(t){return new lO(lg({type:"string",...tS(t)}))}let lR=rs("ZodStringFormat",(t,r)=>{nr.init(t,r),lC.init(t,r)}),lP=rs("ZodISODateTime",(t,r)=>{ny.init(t,r),lR.init(t,r)}),lz=rs("ZodISODate",(t,r)=>{nv.init(t,r),lR.init(t,r)}),l$=rs("ZodISOTime",(t,r)=>{nb.init(t,r),lR.init(t,r)}),lN=rs("ZodISODuration",(t,r)=>{nw.init(t,r),lR.init(t,r)}),lj=rs("ZodEmail",(t,r)=>{ni.init(t,r),lR.init(t,r)}),lD=rs("ZodGUID",(t,r)=>{na.init(t,r),lR.init(t,r)}),lU=rs("ZodUUID",(t,r)=>{nn.init(t,r),lR.init(t,r)}),lL=rs("ZodURL",(t,r)=>{nu.init(t,r),lR.init(t,r)}),lF=rs("ZodEmoji",(t,r)=>{nc.init(t,r),lR.init(t,r)}),lZ=rs("ZodNanoID",(t,r)=>{nd.init(t,r),lR.init(t,r)}),lB=rs("ZodCUID",(t,r)=>{np.init(t,r),lR.init(t,r)}),lq=rs("ZodCUID2",(t,r)=>{nh.init(t,r),lR.init(t,r)}),lV=rs("ZodULID",(t,r)=>{nf.init(t,r),lR.init(t,r)}),lJ=rs("ZodXID",(t,r)=>{nm.init(t,r),lR.init(t,r)}),lW=rs("ZodKSUID",(t,r)=>{ng.init(t,r),lR.init(t,r)}),lG=rs("ZodIPv4",(t,r)=>{n_.init(t,r),lR.init(t,r)}),lH=rs("ZodIPv6",(t,r)=>{nS.init(t,r),lR.init(t,r)}),lK=rs("ZodCIDRv4",(t,r)=>{nx.init(t,r),lR.init(t,r)}),lY=rs("ZodCIDRv6",(t,r)=>{nI.init(t,r),lR.init(t,r)}),lX=rs("ZodBase64",(t,r)=>{nC.init(t,r),lR.init(t,r)}),lQ=rs("ZodBase64URL",(t,r)=>{nM.init(t,r),lR.init(t,r)}),l0=rs("ZodE164",(t,r)=>{nR.init(t,r),lR.init(t,r)}),l1=rs("ZodJWT",(t,r)=>{nz.init(t,r),lR.init(t,r)}),l2=rs("ZodNumber",(t,r)=>{n$.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i0(t,r,a,n),t.isFinite=!0},lI.derived({minValue:t=>{let{minimum:r,exclusiveMinimum:a}=iH(t);return Math.max(r??-1/0,a??-1/0)},maxValue:t=>{let{maximum:r,exclusiveMaximum:a}=iH(t);return Math.min(r??1/0,a??1/0)},isInt:t=>{let{isInt:r,multipleOf:a}=iH(t);return!!r||!!a?.some(Number.isSafeInteger)},format:t=>iH(t).format??null},{gt(t,r){return this.check(lb(t,r))},gte(t,r){return this.check(lw(t,r))},min(t,r){return this.check(lw(t,r))},lt(t,r){return this.check(ly(t,r))},lte(t,r){return this.check(lv(t,r))},max(t,r){return this.check(lv(t,r))},int(t){return this.check(l5(t))},safe(t){return this.check(l5(t))},positive(t){return this.check(lb(0,t))},nonnegative(t){return this.check(lw(0,t))},negative(t){return this.check(ly(0,t))},nonpositive(t){return this.check(lv(0,t))},multipleOf(t,r){return this.check(l_(t,r))},step(t,r){return this.check(l_(t,r))},finite(){return this}}));function l4(t){return new l2(lg({type:"number",checks:[],...tS(t)}))}let l6=rs("ZodNumberFormat",(t,r)=>{nN.init(t,r),l2.init(t,r)});function l5(t){return new l6({type:"number",check:"number_format",abort:!1,format:"safeint",...tS(t)})}let l9=rs("ZodBoolean",(t,r)=>{nj.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i1(t,r,a,n)});function l3(t){return new l9({type:"boolean",...tS(t)})}(t,r)=>{nD.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i2(t,r,a,n)};let l8=rs("ZodNull",(t,r)=>{nU.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i4(t,r,a,n)}),l7=rs("ZodAny",(t,r)=>{nL.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i5(t,r,a,n)}),ue=rs("ZodUnknown",(t,r)=>{nF.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i9(t,r,a,n)});function ut(){return new ue({type:"unknown"})}let ur=rs("ZodNever",(t,r)=>{nZ.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i6(t,r,a,n)});function ua(t){return new ur({type:"never",...tS(t)})}let un=rs("ZodArray",(t,r)=>{lT(),nq.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>ot(t,r,a,n),t.element=r.element},{min(t,r){return this.check(lE(t,r))},nonempty(t){return this.check(lE(1,t))},max(t,r){return this.check(lk(t,r))},length(t,r){return this.check(lS(t,r))},unwrap(){return this.element}});function ui(t,r){return new un({type:"array",element:t,...tS(r)})}let uo=rs("ZodObject",(t,r)=>{lT(),nK.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>
70oa(t,r,a,n),lI.installLazyProp(t,"shape",t=>t._zod.def.shape,!1)},{keyof(){return ug(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(lI.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(lI.mergeDefs(this._zod.def,{catchall:ut()}))},loose(){return this.clone(lI.mergeDefs(this._zod.def,{catchall:ut()}))},strict(){return this.clone(lI.mergeDefs(this._zod.def,{catchall:ua()}))},strip(){return this.clone(lI.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return lI.extend(this,t)},safeExtend(t){return lI.safeExtend(this,t)},merge(t){return lI.merge(this,t)},pick(t){return lI.pick(this,t)},omit(t){return lI.omit(this,t)},partial(...t){return lI.partial(uw,this,t[0])},exactPartial(...t){return lI.partial(uk,this,t[0],"exactPartial")},required(...t){return lI.required(uT,this,t[0])}});function us(t,r){return new uo({type:"object",shape:t??{},...lI.normalizeParams(r)})}let ul=rs("ZodUnion",(t,r)=>{nX.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>on(t,r,a,n),t.options=r.options});function uu(t,r){return new ul({type:"union",options:t,...lI.normalizeParams(r)})}let uc=rs("ZodDiscriminatedUnion",(t,r)=>{ul.init(t,r),n0.init(t,r)});function ud(t,r,a){return new uc({type:"union",options:r,discriminator:t,...lI.normalizeParams(a)})}let up=rs("ZodIntersection",(t,r)=>{n1.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>oi(t,r,a,n)}),uh=rs("ZodRecord",(t,r)=>{lT(),n3.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>os(t,r,a,n),t.keyType=r.keyType,t.valueType=r.valueType});function uf(t,r,a){return new uh(r&&r._zod?{type:"record",keyType:t,valueType:r,...lI.normalizeParams(a)}:{type:"record",keyType:lM(),valueType:t,...lI.normalizeParams(r)})}let um=rs("ZodEnum",(t,r)=>{ie.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i3(t,r,a,n),t.enum=r.entries,t.options=[...t._zod.values];let a=new Set(Object.keys(r.entries));t.extract=(t,n)=>{let i={};for(let n of t)if(a.has(n))i[n]=r.entries[n];else throw Error(`Key ${n} not found in enum`);return new um({...r,checks:[],...lI.normalizeParams(n),entries:i})},t.exclude=(t,n)=>{let i={...r.entries};for(let r of t)if(a.has(r))delete i[r];else throw Error(`Key ${r} not found in enum`);return new um({...r,checks:[],...lI.normalizeParams(n),entries:i})}});function ug(t,r){return new um({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...lI.normalizeParams(r)})}let uy=rs("ZodLiteral",(t,r)=>{it.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i8(t,r,a,n),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if
70(r.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function uv(t,r){return new uy({type:"literal",values:Array.isArray(t)?t:[t],...lI.normalizeParams(r)})}let ub=rs("ZodTransform",(t,r)=>{lT(),ir.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>oe(t,r,a,n),t._zod.parse=(a,n)=>{if("backward"===n.direction)throw new ru(t.constructor.name);a.addIssue=n=>{"string"==typeof n?a.issues.push(lI.issue(n,a.value,r)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),"input"in n||(n.input=a.value),n.inst??(n.inst=t),a.issues.push(lI.issue(n)))};let i=r.transform(a.value,a);return i instanceof Promise?i.then(t=>(a.value=t,a)):(a.value=i,a)}}),uw=rs("ZodOptional",(t,r)=>{ii.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>oy(t,r,a,n),t.unwrap=()=>t._zod.def.innerType});function u_(t){return new uw({type:"optional",innerType:t})}let uk=rs("ZodExactOptional",(t,r)=>{io.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>oy(t,r,a,n),t.unwrap=()=>t._zod.def.innerType}),uE=rs("ZodNullable",(t,r)=>{is.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>ol(t,r,a,n),t.unwrap=()=>t._zod.def.innerType});function uS(t){return new uE({type:"nullable",innerType:t})}let ux=rs("ZodDefault",(t,r)=>{il.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>op(t,r,a,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),uI=rs("ZodPrefault",(t,r)=>{ic.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>oh(t,r,a,n),t.unwrap=()=>t._zod.def.innerType}),uT=rs("ZodNonOptional",(t,r)=>{id.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>ou(t,r,a,n),t.unwrap=()=>t._zod.def.innerType}),uA=rs("ZodCatch",(t,r)=>{im.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>of(t,r,a,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),uC=rs("ZodPipe",(t,r)=>{ig.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>om(t,r,a,n),t.in=r.in,t.out=r.out});function uO(t,r){return new uC({type:"pipe",in:t,out:r})}let uM=rs("ZodReadonly",(t,r)=>{iw.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>og(t,r,a,n),t.unwrap=()=>t._zod.def.innerType}),uR=rs("ZodLazy",(t,r)=>{ik.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>ov(t,r,a,n),t.unwrap=()=>t._zod.def.getter()}),uP=rs("ZodCustom",(t,r)=>{iE.init(t,r),lA.init(t,r),t._zod.processJSONSchema=(r,a,n)=>i7(t,r,a,n)}),uz=rs("ZodInstanceOf",(t,r)=>{uP.init(t,r)},{properties(t,r){return this.check(new a4({check:"properties",shape:t,...tS(r)}))}});var u$=t.i(24154),uN="ai-gateway-transcription.v1";function uj(t,r,a){let n=[t,`ai-gateway-auth.${r}`];return a?.teamIdOrSlug&&n.push(`ai-gateway-team.${function(t){let r=new TextEncoder().encode(t),a="";for(let t of r)a+=String.fromCharCode(t);return btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}(a.teamIdOrSlug)}`),n}var uD=function(){return new l7({type:"any"})},uU=ui,uL=ug,uF=uu,uZ=Symbol.for("vercel.ai.gateway.error"),uB=class t extends(j=Error,N=uZ,j){constructor({message:t,statusCode:r=500,cause:a,generationId:n,isRetryable:i=null!=r&&(408===r||409===r||429===r||r>=500)}){super(n?`${t} [${n}]`:t),this[N]=!0,this.statusCode=r,this.cause=a,this.generationId=n,this.isRetryable=i}static isInstance(r){return t.hasMarker(r)}static hasMarker(t){return"object"==typeof t&&null!==t&&uZ in t&&!0===t[uZ]}},uq="GatewayAuthenticationError",uV=Symbol.for(`vercel.ai.gateway.error.${uq}`),uJ=class t extends(U=uB,D=uV,U){constructor({message:t="Authentication failed",statusCode:r=401,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[D]=!0,this.name=uq,this.type="authentication_error"}static isInstance(t){return uB.hasMarker(t)&&uV in t}static createContextualError({apiKeyProvided:r,oidcTokenProvided:a,statusCode:n=401,cause:i,generationId:o}){return new t({message:r?`AI Gateway authentication failed: Invalid API key or token. 71 72Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys 73 74Provide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:a?`AI Gateway authentication failed: Invalid OIDC token. 75 76Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token. 77 78Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys 79or pass a Vercel access token via the 'apiKey' option.`:`AI Gateway authentication failed: No authentication provided. 80 81Option 1 - API key: 82Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys 83Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. 84 85Option 2 - Vercel access token: 86Pass a Vercel personal access token or Vercel app access token via the 'apiKey' option. 87 88Option 3 - OIDC token: 89Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,statusCode:n,cause:i,generationId:o})}},uW="GatewayInvalidRequestError",uG=Symbol.for(`vercel.ai.gateway.error.${uW}`),uH=class extends(F=uB,L=uG,F){constructor({message:t="Invalid request",statusCode:r=400,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[L]=!0,this.name=uW,this.type="invalid_request_error"}static isInstance(t){return uB.hasMarker(t)&&uG in t}},uK="GatewayRateLimitError",uY=Symbol.for(`vercel.ai.gateway.error.${uK}`),uX=class extends(B=uB,Z=uY,B){constructor({message:t="Rate limit exceeded",statusCode:r=429,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[Z]=!0,this.name=uK,this.type="rate_limit_exceeded"}static isInstance(t){return uB.hasMarker(t)&&uY in t}},uQ="GatewayModelNotFoundError",u0=Symbol.for(`vercel.ai.gateway.error.${uQ}`),u1=sL(()=>sB(us({modelId:lM()}))),u2=class extends(V=uB,q=u0,V){constructor({message:t="Model not found",statusCode:r=404,modelId:a,cause:n,generationId:i}={}){super({message:t,statusCode:r,cause:n,generationId:i}),this[q]=!0,this.name=uQ,this.type="model_not_found",this.modelId=a}static isInstance(t){return uB.hasMarker(t)&&u0 in t}},u4="GatewayNotFoundError",u6=Symbol.for(`vercel.ai.gateway.error.${u4}`),u5=class extends(W=uB,J=u6,W){constructor({message:t="Resource not found",statusCode:r=404,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[J]=!0,this.name=u4,this.type="not_found"}static isInstance(t){return uB.hasMarker(t)&&u6 in t}},u9="GatewayInternalServerError",u3=Symbol.for(`vercel.ai.gateway.error.${u9}`),u8=class extends(H=uB,G=u3,H){constructor({message:t="Internal server error",statusCode:r=500,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[G]=!0,this.name=u9,this.type="internal_server_error"}static isInstance(t){return uB.hasMarker(t)&&u3 in t}},u7="GatewayFailedDependencyError",ce=Symbol.for(`vercel.ai.gateway.error.${u7}`),ct=class extends(Y=uB,K=ce,Y){constructor({message:t="Failed dependency",statusCode:r=424,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[K]=!0,this.name=u7,this.type="failed_dependency"}static isInstance(t){return uB.hasMarker(t)&&ce in t}},cr="GatewayForbiddenError",ca=Symbol.for(`vercel.ai.gateway.error.${cr}`),cn=sL(()=>sB(us({ruleId:lM()}))),ci=class extends(Q=uB,X=ca,Q){constructor({message:t="Forbidden",statusCode:r=403,cause:a,generationId:n,ruleId:i}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[X]=!0,this.name=cr,this.type="forbidden",this.ruleId=i}static isInstance(t){return uB.hasMarker(t)&&ca in t}},co="GatewayResponseError",cs=Symbol.for(`vercel.ai.gateway.error.${co}`),cl=class extends(et=uB,ee=cs,et){constructor({message:t="Invalid response from Gateway",statusCode:r=502,response:a,validationError:n,cause:i,generationId:o,isRetryable:s}={}){super({message:t,statusCode:r,cause:i,generationId:o,isRetryable:s}),this[ee]=!0,this.name=co,this.type="response_error",this.response=a,this.validationError=n}static isInstance(t){return uB.hasMarker(t)&&cs in t}};async function cu({response:t,statusCode:r,defaultMessage:a="Gateway request failed",cause:n,authMethod:i,isRetryable:o}){let s=await sV({value:t,schema:cc});if(!s.success){let i="object"==typeof t&&null!==t&&"generationId"in t?t.generationId:void 0;return new cl({message:`Invalid error response format: ${a}`,statusCode:r,response:t,validationError:s.error,cause:n,generationId:i,isRetryable:o})}let l=s.value,u=l.error.type,c=l.error.message,d=l.generationId??void 0;switch(u){case"authentication_error":return uJ.createContextualError({apiKeyProvided:"api-key"===i,oidcTokenProvided:"oidc"===i,statusCode:r,cause:n,generationId:d});
89case"invalid_request_error":return new uH({message:c,statusCode:r,cause:n,generationId:d});case"rate_limit_exceeded":return new uX({message:c,statusCode:r,cause:n,generationId:d});case"model_not_found":{let t=await sV({value:l.error.param,schema:u1});return new u2({message:c,statusCode:r,modelId:t.success?t.value.modelId:void 0,cause:n,generationId:d})}case"not_found":return new u5({message:c,statusCode:r,cause:n,generationId:d});case"internal_server_error":default:return new u8({message:c,statusCode:r,cause:n,generationId:d});case"failed_dependency":return new ct({message:c,statusCode:r,cause:n,generationId:d});case"forbidden":{let t=await sV({value:l.error.param,schema:cn});return new ci({message:c,statusCode:r,cause:n,generationId:d,ruleId:t.success?t.value.ruleId:void 0})}}}var cc=sL(()=>sB(us({error:us({message:lM(),type:lM().nullish(),param:ut().nullish(),code:uF([lM(),l4()]).nullish()}),generationId:lM().nullish()}))),cd="GatewayTimeoutError",cp=Symbol.for(`vercel.ai.gateway.error.${cd}`),ch=class t extends(ea=uB,er=cp,ea){constructor({message:t="Request timed out",statusCode:r=408,cause:a,generationId:n}={}){super({message:t,statusCode:r,cause:a,generationId:n}),this[er]=!0,this.name=cd,this.type="timeout_error"}static isInstance(t){return uB.hasMarker(t)&&cp in t}static createTimeoutError({originalMessage:r,statusCode:a=408,cause:n,generationId:i}){return new t({message:`Gateway request timed out: ${r} 90 91 This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`,statusCode:a,cause:n,generationId:i})}};function cf(t){if(!(t instanceof Error))return!1;let r=t.code;return"string"==typeof r&&["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(r)}async function cm(t,r){return uB.isInstance(t)?t:cf(t)?ch.createTimeoutError({originalMessage:t instanceof Error?t.message:"Unknown error",cause:t}):ey.isInstance(t)?t.cause&&cf(t.cause)?ch.createTimeoutError({originalMessage:t.message,cause:t}):await cu({response:function(t){if(void 0!==t.data)return t.data;if(null!=t.responseBody)try{return sc(t.responseBody)}catch{return t.responseBody}return{}}(t),statusCode:t.statusCode??500,defaultMessage:"Gateway request failed",cause:t,authMethod:r,isRetryable:!!t.isRetryable&&(null==t.statusCode||t.statusCode<400)||void 0}):await cu({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:r})}var cg="ai-gateway-auth-method",cy="x-vercel-ai-gateway-team";async function cv(t){let r=await sV({value:t[cg],schema:cb});return r.success?r.value:void 0}var cb=sL(()=>sB(uF([uv("api-key"),uv("oidc")]))),cw=["embedding","evaluation","image","language","realtime","reranking","speech","transcription","video"],c_=class{constructor(t){this.config=t}async getAvailableModels(){try{let{value:t}=await sa({url:`${this.config.baseURL}/config`,validateUrl:!1,headers:this.config.headers?await s0(this.config.headers):void 0,successfulResponseHandler:s6(ck),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),fetch:this.config.fetch});return t}catch(t){throw await cm(t)}}async getCredits(){try{let t=new URL(this.config.baseURL),{value:r}=await sa({url:`${t.origin}/v1/credits`,validateUrl:!1,headers:this.config.headers?await s0(this.config.headers):void 0,successfulResponseHandler:s6(cE),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),fetch:this.config.fetch});return r}catch(t){throw await cm(t)}}},ck=sL(()=>sB(us({models:uU(us({id:lM(),name:lM(),description:lM().nullish(),pricing:us({input:lM(),output:lM(),input_cache_read:lM().nullish(),input_cache_write:lM().nullish()}).transform(({input:t,output:r,input_cache_read:a,input_cache_write:n})=>
91({input:t,output:r,...a?{cachedInputTokens:a}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:us({specificationVersion:uv("v4"),provider:lM(),modelId:lM()}),modelType:lM().nullish()})).transform(t=>t.filter(t=>null==t.modelType||cw.includes(t.modelType)))}))),cE=sL(()=>sB(us({balance:lM(),total_used:lM()}).transform(({balance:t,total_used:r})=>({balance:t,totalUsed:r})))),cS=class{constructor(t){this.config=t}async getSpendReport(t){try{let r=new URL(this.config.baseURL),a=new URLSearchParams;a.set("start_date",t.startDate),a.set("end_date",t.endDate),t.groupBy&&a.set("group_by",t.groupBy),t.datePart&&a.set("date_part",t.datePart),t.userId&&a.set("user_id",t.userId),t.model&&a.set("model",t.model),t.provider&&a.set("provider",t.provider),t.credentialType&&a.set("credential_type",t.credentialType),t.tags&&t.tags.length>0&&a.set("tags",t.tags.join(","));let{value:n}=await sa({url:`${r.origin}/v1/report?${a.toString()}`,validateUrl:!1,headers:this.config.headers?await s0(this.config.headers):void 0,successfulResponseHandler:s6(cx),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),fetch:this.config.fetch});return n}catch(t){throw await cm(t)}}},cx=sL(()=>sB(us({results:uU(us({day:lM().optional(),hour:lM().optional(),user:lM().optional(),model:lM().optional(),tag:lM().optional(),provider:lM().optional(),credential_type:uL(["byok","system"]).optional(),total_cost:l4(),market_cost:l4().optional(),input_tokens:l4().optional(),output_tokens:l4().optional(),cached_input_tokens:l4().optional(),cache_creation_input_tokens:l4().optional(),reasoning_tokens:l4().optional(),request_count:l4().optional()}).transform(({credential_type:t,total_cost:r,market_cost:a,input_tokens:n,output_tokens:i,cached_input_tokens:o,cache_creation_input_tokens:s,reasoning_tokens:l,request_count:u,...c})=>({...c,...void 0!==t?{credentialType:t}:{},totalCost:r,...void 0!==a?{marketCost:a}:{},...void 0!==n?{inputTokens:n}:{},...void 0!==i?{outputTokens:i}:{},...void 0!==o?{cachedInputTokens:o}:{},...void 0!==s?{cacheCreationInputTokens:s}:{},...void 0!==l?{reasoningTokens:l}:{},...void 0!==u?{requestCount:u}:{}})))}))),cI=class{constructor(t){this.config=t}async getGenerationInfo(t){try{let r=new URL(this.config.baseURL),{value:a}=await sa({url:`${r.origin}/v1/generation?id=${encodeURIComponent(t.id)}`,validateUrl:!1,headers:this.config.headers?await s0(this.config.headers):void 0,successfulResponseHandler:s6(cT),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),fetch:this.config.fetch});return a}catch(t){throw await cm(t)}}},cT=sL(()=>sB(us({data:us({id:lM(),total_cost:l4(),upstream_inference_cost:l4(),usage:l4(),created_at:lM(),model:lM(),is_byok:l3(),provider_name:lM(),streamed:l3(),finish_reason:lM(),latency:l4(),generation_time:l4(),native_tokens_prompt:l4(),native_tokens_completion:l4(),native_tokens_reasoning:l4(),native_tokens_cached:l4(),native_tokens_cache_creation:l4(),billable_web_search_calls:l4()}).transform(({total_cost:t,upstream_inference_cost:r,created_at:a,is_byok:n,provider_name:i,finish_reason:o,generation_time:s,native_tokens_prompt:l,native_tokens_completion:u,native_tokens_reasoning:c,native_tokens_cached:d,native_tokens_cache_creation:p,billable_web_search_calls:h,...f})=>({...f,totalCost:t,upstreamInferenceCost:r,createdAt:a,isByok:n,providerName:i,finishReason:o,generationTime:s,promptTokens:l,completionTokens:u,reasoningTokens:c,cachedTokens:d,cacheCreationTokens:p,billableWebSearchCalls:h}))}).transform(({data:t})=>t))),cA=class{constructor(t){this.config=t,this.specificationVersion="v4",this.supportedUrls={"*/*":[/.*/]},this.provider=`${t.provider}.batch`}async doStartBatch({requests:t,providerOptions:r,headers:a,abortSignal:n,webhookUrl:i}){var o=t;for(let t of o){let r=t.type;if("text"!==r)throw new eJ({functionality:`batch request type: ${r}`,message:`The AI Gateway Batch API does not support batch requests with type "${r}".`})}let s=function(t){let r=t[0]?.modelId;if(null==r)throw new eT({argument:"requests",message:"The AI Gateway Batch API requires at least one request."});for(let a of t)if(a.modelId!==r)throw new eT({argument:"requests",message:`The AI Gateway Batch API requires all requests in a batch to use the same model. Found "${r}" and "${a.modelId}".`});return r}(t),l=this.config.headers?await s0(this.config.headers):void 0,u=function(t){let r=t?.gateway;if(null==r||"object"!=typeof r||Array.isArray(r))return;
91let a=r.idempotencyKey;return"string"==typeof a&&a.length>0?a:void 0}(r),c=function(t){let r=t?.gateway;if(null==r||"object"!=typeof r||Array.isArray(r)||!("idempotencyKey"in r))return t;let{idempotencyKey:a,...n}=r,i={...t};if(0===Object.keys(n).length?delete i.gateway:i.gateway=n,0!==Object.keys(i).length)return i}(r);try{let{value:r}=await sY({url:this.getBatchUrl("start"),headers:oT(l,a,{"ai-model-id":s},await s0(this.config.o11yHeaders),null!=u?{"idempotency-key":u}:void 0),body:{...null!=i&&{callbackUrl:i},requests:t.map(t=>({id:t.id,type:t.type,modelId:t.modelId,options:function(t){for(let r of t.prompt)if(Array.isArray(r.content)){for(let t of r.content)if("file"===t.type||"reasoning-file"===t.type)t.data=cC(t.data);else if("tool-result"===t.type&&"content"===t.output.type)for(let r of t.output.value)"file"===r.type&&(r.data=cC(r.data))}return t}(t.options)})),...null!=c&&{providerOptions:c}},successfulResponseHandler:s6(cD),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...n&&{abortSignal:n},fetch:this.config.fetch});return{batchId:r.batchId,...cM(r),warnings:r.warnings??[]}}catch(t){if(cO(t))throw t;throw await cm(t,await cv(l??{}))}}async doGetBatchStatus({batchId:t,headers:r,abortSignal:a}){let n=this.config.headers?await s0(this.config.headers):void 0;try{let{value:i}=await sY({url:this.getBatchUrl("status"),headers:oT(n,r,await s0(this.config.o11yHeaders)),body:{batchId:t},successfulResponseHandler:s6(cU),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return cM(i)}catch(t){if(cO(t))throw t;throw await cm(t,await cv(n??{}))}}async doGetBatchResults({batchId:t,headers:r,abortSignal:a}){let n=this.config.headers?await s0(this.config.headers):void 0;try{var i;let o,{value:s}=await sY({url:this.getBatchUrl("results"),headers:oT(n,r,await s0(this.config.o11yHeaders)),body:{batchId:t},successfulResponseHandler:async({response:t})=>{let r=oN(t);if(null==t.body)throw new e_({});return{responseHeaders:r,value:s5({stream:t.body,schema:cP})}},failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return i=cR(s),o=!1,new ReadableStream({async pull(t){if(!o)try{let{value:r,done:a}=await i.next();a?t.close():t.enqueue(r)}catch(r){t.error(r)}},async cancel(t){if(o=!0,i.return)try{await i.return(t)}catch{}}})}catch(t){if(cO(t))throw t;throw await cm(t,await cv(n??{}))}}async doCancelBatch({batchId:t,headers:r,abortSignal:a}){let n=this.config.headers?await s0(this.config.headers):void 0;try{let{value:i}=await sY({url:this.getBatchUrl("cancel"),headers:oT(n,r,await s0(this.config.o11yHeaders)),body:{batchId:t},successfulResponseHandler:s6(cU),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...null!=i.providerMetadata&&{providerMetadata:i.providerMetadata}}}catch(t){if(cO(t))throw t;throw await cm(t,await cv(n??{}))}}getBatchUrl(t){return`${this.config.baseURL}/batch/${t}`}};function cC(t){if("data"===t.type){let r=t.data;if(r instanceof Uint8Array)return{...t,data:ls.Buffer.from(r).toString("base64")}}return t}function cO(t){return!!(t instanceof Error||t instanceof DOMException)&&("AbortError"===t.name||"TimeoutError"===t.name)}function cM(t){let r=function({total:t,pending:r,completed:a,failed:n}){if(so(t)&&so(r)&&so(a)&&so(n)&&r+a+n===t)return{total:t,pending:r,completed:a,failed:n}}({total:t.requestCounts?.total,pending:t.requestCounts?.pending,completed:t.requestCounts?.completed,failed:t.requestCounts?.failed});return{status:t.status,...null!=t.rawStatus&&{rawStatus:t.rawStatus},...null!=r&&{requestCounts:r},...null!=t.error&&{error:{message:t.error.message,...null!=t.error.type&&{type:t.error.type},...null!=t.error.code&&{code:t.error.code},...null!=t.error.statusCode&&{statusCode:t.error.statusCode}}},...null!=t.createdAt&&{createdAt:t.createdAt},...null!=t.expiresAt&&{expiresAt:t.expiresAt},...null!=t.providerMetadata&&{providerMetadata:t.providerMetadata}}}async function*cR(t){for await(let r of t){if("succeeded"===r.status){let t=r.result?.response;void 0!==t&&"string"==typeof t.timestamp&&(t.timestamp=new Date(t.timestamp))}yield r}}var cP=us({type:uv("text"),id:lM(),status:uL(["cancelled","expired","failed","
91succeeded"])}).catchall(ut()),cz=us({message:lM(),type:lM().nullish(),code:lM().nullish(),statusCode:l4().nullish()}),c$=us({total:l4().nullish(),pending:l4().nullish(),completed:l4().nullish(),failed:l4().nullish()}),cN=uf(lM(),uf(lM(),ut())),cj=us({status:uL(["completed","failed","pending"]),rawStatus:lM().nullish(),requestCounts:c$.nullish(),error:cz.nullish(),createdAt:lM().nullish(),expiresAt:lM().nullish(),providerMetadata:cN.nullish()}),cD=cj.extend({batchId:lM(),warnings:uU(us({requestId:lM().nullish(),warning:ut()}).catchall(ut())).nullish()}),cU=cj,cL=class t{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4",this.supportedUrls={"*/*":[/.*/]}}static[ox](t){return lt({modelId:t.modelId,config:t.config})}static[oI](r){return new t(r.modelId,r.config)}get provider(){return this.config.provider}async getArgs(t){let{abortSignal:r,...a}=t;return{args:this.maybeEncodeFileParts(a),warnings:[]}}async doGenerate(t){let{args:r,warnings:a}=await this.getArgs(t),{abortSignal:n}=t,i=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:o,value:s,rawValue:l}=await sY({url:this.getUrl(),headers:oT(i,t.headers,this.getModelConfigHeaders(this.modelId,!1),await s0(this.config.o11yHeaders)),body:r,successfulResponseHandler:s6(uD()),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...s,request:{body:r},response:{headers:o,body:l},warnings:[...s.warnings??[],...a]}}catch(t){throw await cm(t,await cv(i??{}))}}async doStream(t){let{args:r,warnings:a}=await this.getArgs(t),{abortSignal:n}=t,i=this.config.headers?await s0(this.config.headers):void 0;try{let o,{value:s,responseHeaders:l}=await sY({url:this.getUrl(),headers:oT(i,t.headers,this.getModelConfigHeaders(this.modelId,!0),await s0(this.config.o11yHeaders)),body:r,successfulResponseHandler:(o=uD(),async({response:t,url:r,requestBodyValues:a})=>{let n=oN(t);if(null==t.body)throw new e_({});return{responseHeaders:n,value:sG({stream:function({stream:t,url:r,requestBodyValues:a,statusCode:n,responseHeaders:i}){let o=t.getReader(),s=!1,l=()=>{s||(o.releaseLock(),s=!0)};return new ReadableStream({async pull(t){try{let{done:r,value:a}=await o.read();r?(l(),t.close()):t.enqueue(a)}catch(o){if(l(),oD(o))return void t.error(o);t.error(oF({error:new ey({message:"Failed to process successful response",cause:o,statusCode:n,url:r,responseHeaders:i,requestBodyValues:a}),url:r,requestBodyValues:a}))}},async cancel(t){try{await o.cancel(t)}finally{l()}}})}({stream:t.body,url:r,requestBodyValues:a,statusCode:t.status,responseHeaders:n}),schema:o})}}),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(t){a.length>0&&t.enqueue({type:"stream-start",warnings:a})},transform(r,a){if(r.success){let n=r.value;("raw"!==n.type||t.includeRawChunks)&&("response-metadata"===n.type&&n.timestamp&&"string"==typeof n.timestamp&&(n.timestamp=new Date(n.timestamp)),a.enqueue(n))}else a.error(r.error)}})),request:{body:r},response:{headers:l}}}catch(t){throw await cm(t,await cv(i??{}))}}maybeEncodeFileParts(t){for(let r of t.prompt)if(Array.isArray(r.content)){for(let t of r.content)if("file"===t.type||"reasoning-file"===t.type)t.data=cF(t.data);else if("tool-result"===t.type&&"content"===t.output.type)for(let r of t.output.value)"file"===r.type&&(r.data=cF(r.data))}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,r){return{"ai-language-model-specification-version":"4","ai-language-model-id":t,"ai-language-model-streaming":String(r)}}};function cF(t){if("data"===t.type){let r=t.data;if(r instanceof Uint8Array)return{...t,data:ls.Buffer.from(r).toString("base64")}}return t}var cZ=class t{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}static[ox](t){return lt({modelId:t.modelId,config:t.config})}static[oI](r){return new t(r.modelId,r.config)}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:a,providerOptions:n}){let i=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:o,value:s,rawValue:l}=await sY({url:this.getUrl(),headers:oT(i,r??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{values:t,...n?{providerOptions:n}:{}},successfulResponseHandler:s6(cq),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:s.usage??void 0,providerMetadata:s.providerMetadata,response:{headers:o,body:l},warnings:s.warnings??[]}}catch(t){throw await cm(t,await cv(i??{}))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"4","ai-model-id":this.modelId}}},cB=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),cq=sL(()=>sB(us({embeddings:uU(uU(l4())),usage:us({tokens:l4()}).nullish(),warnings:uU(cB).optional(),providerMetadata:uf(lM(),uf(lM(),ut())).optional()}))),cV=class t{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}static[ox](t){return lt({modelId:t.modelId,config:t.config})}static[oI](r){return new t(r.modelId,r.config)}get provider(){return this.config.provider}async doGenerate({prompt:t,n:r,size:a,aspectRatio:n,seed:i,files:o,mask:s,providerOptions:l,headers:u,abortSignal:c}){let d=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:p,value:h}=await sY({url:this.getUrl(),headers:oT(d,u??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{prompt:t,n:r,...a&&{size:a},...n&&{aspectRatio:n},...i&&{seed:i},...l&&{providerOptions:l},...o&&{files:o.map(t=>cJ(t))},...s&&{mask:cJ(s)}},successfulResponseHandler:s6(cK),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:h.images,...null!=h.isRetryable&&{isRetryable:h.isRetryable},warnings:h.warnings??[],providerMetadata:h.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:p},...null!=h.usage&&{usage:{inputTokens:h.usage.inputTokens??void 0,outputTokens:h.usage.outputTokens??void 0,totalTokens:h.usage.totalTokens??void 0}}}}catch(t){throw await cm(t,await cv(d??{}))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"4","ai-model-id":this.modelId}}};function cJ(t){return"file"===t.type&&t.data instanceof Uint8Array?{...t,data:o$
91(t.data)}:t}var cW=us({images:uU(ut()).optional()}).catchall(ut()),cG=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),cH=us({inputTokens:l4().nullish(),outputTokens:l4().nullish(),totalTokens:l4().nullish()}),cK=us({images:uU(lM()),isRetryable:l3().optional(),warnings:uU(cG).optional(),providerMetadata:uf(lM(),cW).optional(),usage:cH.optional()}),cY=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate(t){let{headers:r,abortSignal:a}=t,n=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:i,value:o}=await sY({url:this.getUrl(),headers:oT(n,r??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders),{accept:"text/event-stream"}),body:this.buildRequestBody(t),successfulResponseHandler:async({response:t,url:r,requestBodyValues:a})=>{if(null==t.body)throw new ey({message:"SSE response body is empty",url:r,requestBodyValues:a,statusCode:t.status});let n=sG({stream:t.body,schema:c2}).getReader(),{done:i,value:o}=await n.read();if(n.releaseLock(),i||!o)throw new ey({message:"SSE stream ended without a data event",url:r,requestBodyValues:a,statusCode:t.status});if(!o.success)throw new ey({message:"Failed to parse video SSE event",cause:o.error,url:r,requestBodyValues:a,statusCode:t.status});let s=o.value;if("error"===s.type)throw new ey({message:s.message,statusCode:s.statusCode,url:r,requestBodyValues:a,responseHeaders:Object.fromEntries([...t.headers]),responseBody:JSON.stringify(s),data:{error:{message:s.message,type:s.errorType,param:s.param}}});return{value:{videos:s.videos,warnings:s.warnings,providerMetadata:s.providerMetadata},responseHeaders:Object.fromEntries([...t.headers])}},failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return{videos:o.videos,warnings:o.warnings??[],providerMetadata:o.providerMetadata??void 0,response:{timestamp:new Date,modelId:this.modelId,headers:i}}}catch(t){throw await cm(t,await cv(n??{}))}}async handleWebhookOption({webhook:t}){let{url:r,received:a}=await t();return{webhookUrl:r,received:a}}async doStart(t){let{headers:r,abortSignal:a,webhookUrl:n}=t,i=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:o,value:s}=await sY({url:this.getStartUrl(),headers:oT(i,r??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{...this.buildRequestBody(t),...n&&{callbackUrl:n}},successfulResponseHandler:s6(c4),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...a&&{abortSignal:a},fetch:this.config.fetch});return{operation:s.operation,warnings:s.warnings??[],providerMetadata:s.providerMetadata??void 0,response:{timestamp:new Date,modelId:this.modelId,headers:o}}}catch(t){throw await cm(t,await cv(i??{}))}}async doStatus({operation:t,abortSignal:r,headers:a}){let n=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:i,value:o}=await sY({url:this.getStatusUrl(),headers:oT(n,a??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{operation:t},successfulResponseHandler:s6(c6),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...r&&{abortSignal:r},fetch:this.config.fetch}),s={timestamp:new Date,modelId:this.modelId,headers:i};if("completed"===o.status)return{status:"completed",videos:o.videos,warnings:o.warnings??[],providerMetadata:o.providerMetadata??void 0,response:s};if("error"===o.status)return{status:"error",error:o.error,providerMetadata:o.providerMetadata??void 0,response:s};if("cancelled"===o.status)return{status:"error",error:"Video generation was cancelled.",providerMetadata:o.providerMetadata??void 0,response:s};return{status:"pending",warnings:o.warnings??[],providerMetadata:o.providerMetadata??void 0,response:s}}catch(t){throw await cm(t,await cv(n??{}))}}buildRequestBody({prompt:t,n:r,aspectRatio:a,resolution:n,duration:i,fps:o,seed:s,generateAudio:l,image:u,frameImages:c,inputReferences:d,providerOptions:p}){return{prompt:t,n:r,...a&&{aspectRatio:a},...n&&{resolution:n},...i&&{duration:i},...o&&{fps:o},...s&&{seed:s},...void 0!==l&&{generateAudio:l},...p&&{providerOptions:p},...u&&{image:cX(u)},...c&&{frameImages:c.map(t=>({...t,image:cX(t.image)}))},...d&&{inputReferences:d.map(t=>cX(t))}}}getUrl(){return`${this.config.baseURL}/video-model`}getStartUrl(){return`${this.config.baseURL}/video-model/start`}getStatusUrl(){return`${this.config.baseURL}/video-model/status`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"4","ai-model-id":this.modelId}}};function cX(t){return"file"===t.type&&t.data instanceof Uint8Array?{...t,data:o$
91(t.data)}:t}var cQ=us({videos:uU(ut()).optional()}).catchall(ut()),c0=uF([us({type:uv("url"),url:lM(),mediaType:lM()}),us({type:uv("base64"),data:lM(),mediaType:lM()})]),c1=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),c2=ud("type",[us({type:uv("result"),videos:uU(c0),warnings:uU(c1).optional(),providerMetadata:uf(lM(),cQ).optional()}),us({type:uv("error"),message:lM(),errorType:lM(),statusCode:l4(),param:ut().nullable()})]),c4=us({operation:ut(),warnings:uU(c1).nullish(),providerMetadata:uf(lM(),cQ).nullish()}),c6=ud("status",[us({status:uv("pending"),warnings:uU(c1).nullish(),providerMetadata:uf(lM(),cQ).nullish()}),us({status:uv("completed"),videos:uU(c0),warnings:uU(c1).nullish(),providerMetadata:uf(lM(),cQ).nullish()}),us({status:uv("error"),error:lM(),providerMetadata:uf(lM(),cQ).nullish()}),us({status:uv("cancelled"),providerMetadata:uf(lM(),cQ).nullish()})]),c5=sL(()=>sB(us({models:dt.optional()}).catchall(ut()))),c9=l4().finite().min(0).max(1),c3=lM().min(1).max(256),c8=uF([us({question:c3,confidenceBelow:c9}).strict(),us({question:c3,probabilityBetween:uU(c9).length(2).refine(([t,r])=>t<=r,{message:"probabilityBetween minimum must be less than or equal to maximum"})}).strict()]),c7=uF([us({any:ut()}),us({all:ut()}),us({atLeast:ut()})]).superRefine((t,r)=>{r.addIssue({code:"custom",message:"conditions can be nested at most 5 levels deep"})}),de=us({model:lM().min(1),when:function t(r){if(5===r)return uF([c8,c7]);let a=uU(t(r+1)).min(1).max(20);return uF([c8,us({any:a}).strict(),us({all:a}).strict(),us({atLeast:us({count:l4().int().min(1),conditions:a}).strict().refine(({count:t,conditions:r})=>t<=r.length,{message:"atLeast count cannot exceed the number of conditions",path:["count"]})}).strict()])}(1)}).strict(),dt=uU(uF([lM(),de])).superRefine((t,r)=>{let a=t.flatMap((t,r)=>"string"==typeof t?[]:[r]);a.length>1&&r.addIssue({code:"custom",message:"models supports at most one conditional evaluation fallback"}),void 0!==a[0]&&0!==a[0]&&r.addIssue({code:"custom",message:"a conditional evaluation fallback must be the first models entry",path:[a[0]]})}),dr=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4",this.supportedQuestionTypes=["choice","score","boolean"]}get provider(){return this.config.provider}async doEvaluate({state:t,questions:r,headers:a,abortSignal:n,providerOptions:i}){let o=await sH({provider:"gateway",providerOptions:i,schema:c5}),s=null==o?i:{...i,gateway:o},l=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:i,value:o,rawValue:u}=await sY({url:this.getUrl(),headers:oT(l,a??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{state:t,questions:r,...s?{providerOptions:s}:{}},successfulResponseHandler:s6(di),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...n&&{abortSignal:n},fetch:this.config.fetch});return{answers:o.answers,...o.rounding?{rounding:o.rounding}:{},...o.usage?{usage:o.usage}:{},warnings:o.warnings??[],providerMetadata:o.providerMetadata,response:{modelId:o.model??this.modelId,headers:i,body:u}}}catch(t){throw await cm(t,await cv(l??{}))}}getUrl(){return`${this.config.baseURL}/evaluation-model`}getModelConfigHeaders(){return{"ai-evaluation-model-specification-version":"4","ai-model-id":this.modelId}}},da=ud("type",[us({type:uv("choice"),choice:lM(),probabilities:uf(lM(),l4()).optional()}),us({type:uv("score"),score:l4(),probabilities:uf(lM(),l4()).optional()}),us({type:uv("boolean"),probability:l4()})]),dn=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),di=sL(()=>sB(us({answers:uf(lM(),da),model:lM().optional(),rounding:us({probabilityDecimals:l4().optional(),scoreDecimals:l4().optional()}).optional(),usage:us({inputTokens:l4().optional(),outputTokens:l4().optional()}).optional(),warnings:uU(dn).optional(),providerMetadata:uf(lM(),uf(lM(),ut())).optional()}))),ds=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4"}get provider(){return this.config.provider}async doRerank({documents:t,query:r,topN:a,headers:n,abortSignal:i,providerOptions:o}){let s=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:l,value:u,rawValue:c}=await sY({url:this.getUrl(),headers:oT(s,n??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{documents:t,query:r,...null!=a?{topN:a}:{},...o?{providerOptions:o}:{}},successfulResponseHandler:s6(du),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...i&&{abortSignal:i},fetch:this.config.fetch});return{ranking:u.ranking,providerMetadata:u.providerMetadata,response:{headers:l,body:c},warnings:u.warnings??[]}}catch(t){throw await cm(t,await cv(s??{}))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"4","ai-model-id":this.modelId}}},dl=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),du=sL(()=>sB(us({ranking:uU(us({index:l4(),relevanceScore:l4()})),warnings:uU(dl).optional(),providerMetadata:uf(lM(),uf(lM(),ut())).optional()}))),dc=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4"}get provider(){return this.config.provider}async doGenerate({text:t,voice:r,outputFormat:a,instructions:n,speed:i,language:o,providerOptions:s,headers:l,abortSignal:u}){let c=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:d,value:p,rawValue:h}=await sY({url:this.getUrl(),headers:oT(c,l??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{text:t,...r&&{voice:r},...a&&{outputFormat:a},...n&&{instructions:n},...null!=i&&{speed:i},...o&&{language:o},...s&&{providerOptions:s}},successfulResponseHandler:s6(dh),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}
91),...u&&{abortSignal:u},fetch:this.config.fetch});return{audio:p.audio,warnings:p.warnings??[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:d,body:h}}}catch(t){throw await cm(t,await cv(c??{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"4","ai-model-id":this.modelId}}},dd=us({}).catchall(ut()),dp=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),dh=us({audio:lM(),warnings:uU(dp).optional(),providerMetadata:uf(lM(),dd).optional()}),df=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v4"}get provider(){return this.config.provider}async doGenerate({audio:t,mediaType:r,providerOptions:a,headers:n,abortSignal:i}){let o=this.config.headers?await s0(this.config.headers):void 0;try{let{responseHeaders:s,value:l,rawValue:u}=await sY({url:this.getUrl(),headers:oT(o,n??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),body:{audio:t instanceof Uint8Array?o$(t):t,mediaType:r,...a&&{providerOptions:a}},successfulResponseHandler:s6(dv),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),...i&&{abortSignal:i},fetch:this.config.fetch});return{text:l.text,segments:l.segments??[],language:l.language??void 0,durationInSeconds:l.durationInSeconds??void 0,warnings:l.warnings??[],providerMetadata:l.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:s,body:u}}}catch(t){throw await cm(t,await cv(o??{}))}}async doStream(t){let r,a,n,i=this.config._internal?.currentDate?.()??new Date,o=oT(await s0(this.config.headers??{}),t.headers??{},this.getModelConfigHeaders(),await s0(this.config.o11yHeaders)),s=await cv(o),l={type:"transcription-stream.start",inputAudioFormat:t.inputAudioFormat,...null!=t.providerOptions&&{providerOptions:t.providerOptions},...null!=t.includeRawChunks&&{includeRawChunks:t.includeRawChunks}};return{stream:function({webSocket:t,url:r,protocols:a,headers:n,startFrame:i,audio:o,abortSignal:s,authMethod:l}){let u=!1,c=()=>{};return new ReadableStream({start:d=>{let p,h,f,m=!1,g=!1;c=t=>{null!=p?p.cancel().catch(()=>{}):o.cancel().catch(()=>{}),f?.close(t)};let y=t=>{u||(u=!0,c(),db(d,t,l))},v=async t=>{let r=o.getReader();p=r;try{for(;;){let{done:a,value:n}=await r.read();if(a||u)break;let i="string"==typeof n?function(t){let r=oz(t.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(r,t=>t.codePointAt(0))}(n):n;for(let r=0;r<i.length&&!u;r+=65536)t.send(i.subarray(r,r+65536)),await oR(t)}}finally{r.releaseLock(),p===r&&(p=void 0)}u||g||t.send(JSON.stringify({type:"transcription-stream.audio-done"}))};f=function({url:t,protocols:r,headers:a,webSocket:n,abortSignal:i,onOpen:o,onMessageText:s,onProcessingError:l,onSocketError:u,onClose:c,onAbort:d}){let p,h,f=t=>{null!=h&&(i?.removeEventListener("abort",h),h=void 0);try{p?.close(t)}catch{}};if(i?.aborted)return d?.(i.reason??Error("Aborted")),{socket:void 0,close:f};try{var m;p=new(function(t){let r=t??globalThis.WebSocket;if(null==r)throw Error("No WebSocket implementation available.");return r}(n))(t,r,{headers:(m=a??{},Object.fromEntries(Object.entries(m).filter(([t,r])=>null!=r)))})}catch(t){return l(t),{socket:void 0,close:f}}null!=i&&null!=d&&(h=()=>d(i.reason??Error("Aborted")),i.addEventListener("abort",h,{once:!0}));let g=p;p.onopen=()=>{try{o?.(g)}catch(t){l(t)}};let y=Promise.resolve();return p.onmessage=t=>{y=y.then(()=>oM(t.data)).then(t=>s(t)).catch(l)},p.onerror=()=>{y=y.then(()=>u?.()).catch(l)},p.onclose=t=>{let r="number"==typeof t?.code?t.code:void 0,a="string"==typeof t?.reason?t.reason:void 0;y=y.then(()=>c?.({code:r,reason:a})).catch(l)},{socket:p,close:f}}({url:r,protocols:a,headers:n,webSocket:t,abortSignal:s,onAbort:t=>{u||(u=!0,c(),d.error(t))},onProcessingError:y,onOpen:t=>{t.send(JSON.stringify(i)),v(t).catch(y)},onMessageText:t=>{if(u)return;let r=function(t){let r;try{r=sc(t)}catch{return}if(null==r||"object"!=typeof r||Array.isArray(r))return;let a=r;switch(a.type){case"stream-start":return Array.isArray(a.warnings)&&a.warnings.every(li)?a:void 0;case"transcript-delta":return lr(a.delta)&&ln(a.id,lr)&&ln(a.providerMetadata,sn)?a:void 0;case"transcript-partial":return lr(a.text)&&ln(a.id,lr)&&ln(a.startSecond,la)&&ln(a.durationInSeconds,la)&&ln(a.channelIndex,la)&&ln(a.providerMetadata,sn)?a:void 0;case"transcript-final":return lr(a.text)&&ln(a.id,lr)&&ln(a.startSecond,la)&&ln(a.endSecond,la)&&ln(a.channelIndex,la)&&ln(a.providerMetadata,sn)?a:void 0;case"finish":return lr(a.text)&&Array.isArray(a.segments)&&a.segments.every(lo)&&ln(a.language,lr)&&ln(a.durationInSeconds,la)&&ln(a.providerMetadata,sn)?a:void 0;case"response-metadata":{if(!(ln(a.modelId,lr)&&ln(a.headers,sn)))return;let t=a.timestamp;if(null==t)return{...a,timestamp:void 0};if("string"!=typeof t)return;let r=new Date(t);return Number.isNaN(r.getTime())?void 0:{...a,timestamp:r}}case"raw":return"rawValue"in a?a:void 0;case"error":return"error"in a?a:void 0;default:return}}(t);if(null!=r){if("finish"===r.type){u=!0,d.enqueue(r),d.close(),c(1e3);return}"error"===r.type&&(m=!0,h=r.error,g=!0,null!=p?(p.cancel().catch(()=>{}),p=void 0):o.cancel().catch(()=>{})),d.enqueue(r)}},onSocketError:()=>{y(Error("Connection error on AI Gateway transcription stream"))},onClose:()=>{if(m){if(u)return;d_(h,l).then(y);return}y(Error("AI Gateway transcription stream closed before a finish part was received"))}})},cancel:()=>{u||(u=!0,c())}})}({webSocket:this.config.webSocket,url:dm(this.config.baseURL,this.modelId),protocols:(a=(r=oB(o)).authorization,null==(n=a?.startsWith("Bearer ")?a.slice(7):void 0)?[uN]:u
91j(uN,n,{teamIdOrSlug:r[cy]})),headers:o,startFrame:l,audio:t.audio,abortSignal:t.abortSignal,authMethod:s}),request:{body:l},response:{timestamp:i,modelId:this.modelId}}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"4","ai-model-id":this.modelId}}};function dm(t,r){let a=new URL(`${t.replace(/^http/,"ws")}/transcription-model`);return a.searchParams.set("ai-model-id",r),a.toString()}var dg=us({}).catchall(ut()),dy=ud("type",[us({type:uv("unsupported"),feature:lM(),details:lM().optional()}),us({type:uv("compatibility"),feature:lM(),details:lM().optional()}),us({type:uv("deprecated"),setting:lM(),message:lM()}),us({type:uv("other"),message:lM()})]),dv=us({text:lM(),segments:uU(us({text:lM(),startSecond:l4(),endSecond:l4()})).optional(),language:lM().nullish(),durationInSeconds:l4().nullish(),warnings:uU(dy).optional(),providerMetadata:uf(lM(),dg).optional()});async function db(t,r,a){t.error(await cm(r,a))}var dw={authentication_error:401,failed_dependency:424,forbidden:403,internal_server_error:500,invalid_request_error:400,model_not_found:404,rate_limit_exceeded:429};async function d_(t,r){return"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&"type"in t&&"string"==typeof t.type&&t.type in dw?cu({response:{error:{message:t.message,type:t.type}},statusCode:dw[t.type],authMethod:r}):Error(`AI Gateway transcription stream failed: ${null!=t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message?t.message:eE(t)}`)}var dk=class{constructor(t,r){this.specificationVersion="v4",this.modelId=t,this.provider=r.provider,this.config=r}async doCreateClientSecret(t){var r,a;let n,i=await this.config.createClientSecret({modelId:this.modelId,...t?.expiresAfterSeconds!=null&&{expiresAfterSeconds:t.expiresAfterSeconds}});return{token:i.token,url:(r=this.config.baseURL,a=this.modelId,(n=new URL(`${r.replace(/^http/,"ws")}/realtime-model`)).searchParams.set("ai-model-id",a),n.toString()),...null!=i.expiresAt&&{expiresAt:i.expiresAt}}}getWebSocketConfig(t){return{url:t.url,protocols:uj("ai-gateway-realtime.v1",t.token,{teamIdOrSlug:this.config.teamIdOrSlug})}}parseServerEvent(t){return t}serializeClientEvent(t){return t}buildSessionConfig(t){return t}},dE=uf(lM(),ut()),dS=sQ({id:"gateway.browserbase_fetch",inputSchema:sL(()=>sB(us({url:lM().url().describe("URL of the page to fetch."),allow_redirects:l3().optional().describe("Whether to follow HTTP redirects (default: false)."),allow_insecure_ssl:l3().optional().describe("Whether to bypass TLS certificate verification (default: false). Only use for trusted hosts."),proxies:l3().optional().describe("Whether to route the request through Browserbase proxies (default: false)."),format:uL(["raw","json","markdown"]).optional().describe("Output format. raw returns the response body unchanged, markdown returns page content as Markdown, and json returns structured content using schema."),schema:dE.optional().describe("JSON Schema for structured extraction. Only use with format set to json.")}
vendor: 7,775 bytes, line 91
91))),outputSchema:sL(()=>sB(uF([us({id:lM(),content:uF([lM(),dE]),contentType:lM(),encoding:lM(),headers:uf(lM(),lM()),statusCode:l4()}),us({error:uL(["api_error","configuration_error","execution_error","invalid_input","rate_limit","timeout","unknown"]),statusCode:l4().optional(),message:lM()})])))}),dx=sQ({id:"gateway.browserbase_search",inputSchema:sL(()=>sB(us({query:lM().min(1).max(200).describe("Web search query. Must be between 1 and 200 characters."),num_results:l4().int().min(1).max(25).optional().describe("Maximum number of results to return (1-25, default: 10).")}))),outputSchema:sL(()=>sB(uF([us({query:lM(),requestId:lM(),results:uU(us({id:lM(),title:lM(),url:lM(),author:lM().optional(),favicon:lM().optional(),image:lM().optional(),publishedDate:lM().optional()}))}),us({error:uL(["api_error","configuration_error","execution_error","invalid_input","rate_limit","timeout","unknown"]),statusCode:l4().optional(),message:lM()})])))}),dI=sQ({id:"gateway.exa_search",inputSchema:sL(()=>sB(us({query:lM().describe("Natural-language web search query. This is required."),type:uL(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:l4().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:uL(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:lM().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:uU(lM()).optional().describe("Only return results from these domains."),exclude_domains:uU(lM()).optional().describe("Exclude results from these domains."),start_published_date:lM().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:lM().optional().describe("Only return links published before this ISO 8601 date."),contents:us({text:uF([l3(),us({max_characters:l4().optional(),include_html_tags:l3().optional(),verbosity:uL(["compact","standard","full"]).optional(),include_sections:uU(uL(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:uU(uL(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:uF([l3(),us({query:lM().optional(),max_characters:l4().optional()})]).optional(),max_age_hours:l4().optional(),livecrawl_timeout:l4().optional(),subpages:l4().optional(),subpage_target:uF([lM(),uU(lM())]).optional(),extras:us({links:l4().optional(),image_links:l4().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}))),outputSchema:sL(()=>sB(uF([us({requestId:lM(),searchType:lM().optional(),resolvedSearchType:lM().optional(),results:uU(us({title:lM(),url:lM(),id:lM(),publishedDate:lM().nullable().optional(),author:lM().nullable().optional(),image:lM().nullable().optional(),favicon:lM().nullable().optional(),text:lM().optional(),highlights:uU(lM()).optional(),highlightScores:uU(l4()).optional(),summary:lM().optional(),subpages:uU(uD()).optional(),extras:us({links:uU(lM()).optional(),imageLinks:uU(lM()).optional()}).optional()})),costDollars:us({total:l4().optional(),search:uf(lM(),l4()).optional()}).optional()}),us({error:uL(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:l4().optional(),message:lM()})])))}),dT=sQ({id:"gateway.parallel_search",inputSchema:sL(()=>sB(us({objective:lM().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:uU(lM()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:uL(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:l4().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:us({include_domains:uU(lM()).optional().describe("Limit results to these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),exclude_domains:uU(lM()).optional().describe("Exclude results from these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),after_date:lM().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:us({max_chars_per_result:l4().optional().describe("Maximum characters per result."),max_chars_total:l4().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:us({max_age_seconds:l4().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),outputSchema:sL(()=>sB(uF([us({searchId:lM(),results:uU(us({url:lM(),title:lM(),excerpt:lM(),publishDate:lM().nullable().optional(),relevanceScore:l4().optional()}))}),us({error:uL(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:l4().optional(),message:lM()})])))}),dA=sQ({id:"gateway.perplexity_search",inputSchema:sL(()=>sB(us({query:uF([lM(),uU(lM())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:l4().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:l4().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:l4().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:lM().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:uU(lM()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:uU(lM()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:lM().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:lM().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:lM().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:lM().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:uL(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}
91))),outputSchema:sL(()=>sB(uF([us({results:uU(us({title:lM(),url:lM(),snippet:lM(),date:lM().optional(),lastUpdated:lM().optional()})),id:lM()}),us({error:uL(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:l4().optional(),message:lM()})])))}),dC=us({count:l4().optional().describe("Maximum number of data results to return (1-20). When include_contents is true, each additional result adds its own data surcharge."),include_contents:l3().optional().describe("Inline rows for each data result. This adds a data surcharge based on row count and dataset source. To estimate cost, search with include_contents disabled and inspect cards.content.export_pricing. This applies to every returned card; limit sources.data.count and sources.data.max_rows to control cost."),mode:uL(["inline","url"]).optional().describe("Requested data delivery mode. Search card data is always inline."),content_format:uL(["card_json","csv","json_compact","json_records"]).optional().describe("Serialization for inlined card data."),max_rows:l4().optional().describe("Maximum rows to inline per result. Omit to use the allowance in cards.content.export_pricing. A data surcharge applies per 1,000 exported rows; lower values reduce cost."),node_ids:uU(lM()).optional().describe("Data Graph node IDs to prioritize. Maximum 20."),strict:l3().optional().describe("Only return cards matching node_ids. Requires a non-empty node_ids.")}),dO=us({count:l4().optional().describe("Maximum number of web results to return (1-20)."),include_contents:l3().optional().describe("Inline extracted web page text. This can add a data charge."),category:uL(["finance","news","sports"]).optional().describe("Optional web-result category filter."),include_domains:uU(lM()).optional().describe("Only return results from these bare domains."),exclude_domains:uU(lM()).optional().describe("Exclude results from these bare domains."),snippet_max_chars:l4().optional().describe("Maximum characters in each web-result snippet."),highlights:l3().optional().describe("Include highlighted passages in web results. Defaults to true in AI Gateway."),article_content_max_chars:l4().optional().describe("Maximum extracted characters per web page when including contents."),published_after:lM().optional().describe("Keep results published on or after this ISO date (YYYY-MM-DD)."),published_before:lM().optional().describe("Keep results published on or before this ISO date (YYYY-MM-DD).")}),dM=sL(()=>sB(us({query:lM().describe('Natural-language search query. Include the entity, metric, and time period. Quote a phrase to force it to one entity, for example "Tesla":PRODUCT price.'),effort:uL(["deep","fast","instant"]).optional().describe("Search effort. fast is the balanced default, instant favors cached results and low latency, and deep broadens retrieval with reranking at higher cost and latency."),sources:us({data:dC.optional(),web:dO.optional()}).optional().describe("Sources to search. Omit to search both curated data and the web. When provided, only keys present are searched."),location:us({latitude:l4().describe("Latitude between -90 and 90."),longitude:l4().describe("Longitude between -180 and 180.")}).optional().describe("End-user coordinates for localized results."),country_code:lM().optional().describe("Two-letter ISO 3166-1 country code, such as 'US'."),locale:lM().optional().describe("BCP-47 locale, such as 'en-US'."),timezone:lM().optional().describe("IANA timezone, such as 'America/New_York'."),output_settings:us({image_dark_mode:l3().optional().describe("Render card preview images in dark mode."),force_refresh:l3().optional().describe("Instant-effort only. Request a refreshed instant result.")}).optional().describe("Controls card rendering in the search response."),include_related:l4().optional().describe("Maximum related search suggestions to include (1-20).")}))),dR=uF([l3(),l4(),lM()]).nullable(),dP=us({content_format:uL(["card_json","csv","json_compact","json_records"]).nullish(),cost:l4().optional(),data:lM().nullish(),records:uU(uf(lM(),dR)).nullish(),dataset:us({columns:uU(us({name:lM(),type:uL(["boolean","date","datetime","number","string"]),unit:lM().nullish()})),rows:uU(uU(dR)),total_rows:l4(),truncated:l3(),ref:lM(),sources:uU(us({name:lM(),index:uL(["data","web"]).optional()})),provenance:uL(["query","web_extraction"]).optional()}).nullish(),card_data:us({}).passthrough().nullish(),card_data_schema:us({}).passthrough().nullish(),url:lM().nullish(),expires_at:lM().nullish(),total_rows:l4().nullish(),truncated:l3().optional(),export_pricing:us({baseline_usd:l4(),free_rows:l4(),max_rows_ceiling:l4(),row_cpm_usd:l4()}).nullish(),manifest:uU(us({dtype:uL(["boolean","date","datetime","number","string"]).nullish(),entity:lM().nullish(),metric:lM().nullish(),name:lM().nullish(),unit:lM().nullish()})).nullish()}).passthrough(),dz=us({card_id:lM().nullish(),title:lM().nullish(),description:lM().nullish(),semantic_description:lM().nullish(),webpage_url:lM().nullish(),image_url:lM().nullish(),embed_url:lM().nullish(),sources:uU(us({s
91ource_name:lM().nullish(),source_description:lM().nullish(),source_index:uL(["data","web"]),source_text:lM().nullish(),url:lM().nullish()})).nullish(),methodologies:uU(us({methodology_name:lM().nullable(),methodology_description:lM().nullable()})).nullish(),source_indexes:uU(uL(["data","web"])).nullish(),card_type:lM().nullish(),relevance:uL(["High","Low","Medium"]).nullish(),content:dP.nullish(),exportable:l3().optional(),nodes:uU(us({id:lM(),type:uL(["entity","metric"]),name:lM(),description:lM().nullish()})).nullish(),metric_definitions:uU(us({name:lM(),definition:lM()})).nullish(),data_freshness:us({coverage_end:lM().nullish(),data_as_of:lM().nullish(),last_updated:lM().nullish()}).nullish()}).passthrough(),d$=us({title:lM(),url:lM(),snippet:lM().nullish(),source_name:lM().nullish(),publish_date:lM().nullish(),content:dP.nullish()}).passthrough(),dN=sQ({id:"gateway.tako_search",inputSchema:dM,outputSchema:sL(()=>sB(uF([us({request_id:lM(),cards:uU(dz).optional(),web_results:uU(d$).optional(),usage:us({total_cost_usd:l4(),compute:us({cost_usd:l4()}).nullish(),data:us({cost_usd:l4(),datasets:l4()}).nullish()}).nullish(),related:uU(us({}).passthrough()).nullish()}).passthrough(),us({error:uL(["api_error","configuration_error","execution_error","invalid_input","rate_limit","timeout","unknown_tool"]),statusCode:l4().optional(),message:lM()})])))}),dj={browserbaseFetch:(t={})=>dS(t),browserbaseSearch:(t={})=>dx(t),exaSearch:(t={})=>dI(t),parallelSearch:(t={})=>dT(t),perplexitySearch:(t={})=>dA(t),takoSearch:(t={})=>dN(t)};async function dD(){return(0,u$.getContext)().headers?.["x-vercel-id"]}var dU=us({token:lM(),expiresAt:l4().nullish()});async function dL(t){let r=si({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return r?{token:r,authMethod:"api-key"}:{token:await (0,u$.getVercelOidcToken)(),authMethod:"oidc"}}!function(t={}){var r;let a=null,n=null,i=t.metadataCacheRefreshMillis??3e5,o=0,s=(r=t.baseURL,r?.replace(/\/$/,"")??"https://ai-gateway.vercel.sh/v4/ai"),l=r=>oq({Authorization:`Bearer ${r.token}`,"ai-gateway-protocol-version":"0.0.1",[cg]:r.authMethod,...null!=t.teamIdOrSlug?{[cy]:t.teamIdOrSlug}:{},...t.headers},"ai-sdk/gateway/4.0.96"),u=async()=>{try{return l(await dL(t))}catch(t){throw uJ.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:t})}},c=async()=>{try{return await dL(t)}catch(t){throw uJ.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:t})}},d=async r=>{if(void 0!==globalThis.window)throw Error("AI Gateway client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() or gateway.experimental_transcription.getToken() from your server and pass the returned token to the client.");let a=l(await c()),n=new URL("/v1/realtime/client-secrets",s).toString();try{let{value:i}=await sY({url:n,headers:a,body:{model:r.modelId,...null!=r.routeKind&&{routeKind:r.routeKind},...null!=r.expiresAfterSeconds&&{expiresIn:r.expiresAfterSeconds}},successfulResponseHandler:s6(dU),failedResponseHandler:s4({errorSchema:uD(),errorToMessage:t=>eE(t)??"unknown error"}),fetch:t.fetch});return{token:i.token,...null!=i.expiresAt&&{expiresAt:i.expiresAt}}}catch(t){throw await cm(t,await cv(a))}},p=()=>{let t=si({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),r=si({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),a=si({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),n=si({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let i=await dD();return{...t&&{"ai-o11y-deployment-id":t},...r&&{"ai-o11y-environment":r},...a&&{"ai-o11y-region":a},...i&&{"ai-o11y-request-id":i},...n&&{"ai-o11y-project-id":n}}}},h=r=>new cL(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()}),f=async()=>{let r=t._internal?.currentDate?.().getTime()??Date.now();return(!a||r-o>i)&&(o=r,a=new c_({baseURL:s,headers:u,fetch:t.fetch}).getAvailableModels().then(t=>(n=t,t)).catch(async t=>{throw await cm(t,await cv(await u()))}
91)),n?Promise.resolve(n):a},m=async()=>new c_({baseURL:s,headers:u,fetch:t.fetch}).getCredits().catch(async t=>{throw await cm(t,await cv(await u()))}),g=async r=>new cS({baseURL:s,headers:u,fetch:t.fetch}).getSpendReport(r).catch(async t=>{throw await cm(t,await cv(await u()))}),y=async r=>new cI({baseURL:s,headers:u,fetch:t.fetch}).getGenerationInfo(r).catch(async t=>{throw await cm(t,await cv(await u()))}),v=function(t){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return h(t)};v.specificationVersion="v4",v.getAvailableModels=f,v.getCredits=m,v.getSpendReport=g,v.getGenerationInfo=y,v.imageModel=r=>new cV(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()}),v.languageModel=h,v.experimental_batch=()=>new cA({provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});let b=r=>new cZ(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});v.embeddingModel=b,v.textEmbeddingModel=b,v.videoModel=r=>new cY(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});let w=r=>new ds(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});v.rerankingModel=w,v.reranking=w;let _=r=>new dr(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});v.evaluationModel=_,v.evaluation=_;let k=r=>new dc(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p()});v.speechModel=k,v.speech=k;let E=r=>new df(r,{provider:"gateway",baseURL:s,headers:u,fetch:t.fetch,o11yHeaders:p(),webSocket:t.webSocket});v.transcriptionModel=E,v.transcription=E,v.experimental_transcription=Object.assign(t=>E(t),{getToken:async t=>{let r=await d({modelId:t.model,routeKind:"transcription",...null!=t.expiresAfterSeconds&&{expiresAfterSeconds:t.expiresAfterSeconds}});return{token:r.token,url:dm(s,t.model),...null!=r.expiresAt&&{expiresAt:r.expiresAt}}}});let S=r=>new dk(r,{provider:"gateway.realtime",baseURL:s,teamIdOrSlug:t.teamIdOrSlug,createClientSecret:d});v.experimental_realtime=Object.assign(t=>S(t),{getToken:async t=>{let{model:r,...a}=t,n=S(r),i=await n.doCreateClientSecret(a);return{token:i.token,url:i.url,...null!=i.expiresAt&&{expiresAt:i.expiresAt}}}}),v.chat=v.languageModel,v.embedding=v.embeddingModel,v.image=v.imageModel,v.video=v.videoModel,v.tools=dj}();var dF=Object.defineProperty,dZ="AI_InvalidArgumentError",dB=`vercel.ai.error.${dZ}`,dq=Symbol.for(dB),dV=class extends(ei=eh,en=dq,ei){constructor({parameter:t,value:r,message:a}){super({name:dZ,message:`Invalid argument for parameter ${t}: ${a}`}),this[en]=!0,this.parameter=t,this.value=r}static isInstance(t){return eh.hasMarker(t,dB)}},dJ=Symbol.for("vercel.ai.error.AI_InvalidStreamPartError");Symbol.for("vercel.ai.error.AI_InvalidToolApprovalError");Symbol.for("vercel.ai.error.AI_InvalidToolApprovalSignatureError");Symbol.for("vercel.ai.error.AI_InvalidToolInputError");Symbol.for("vercel.ai.error.AI_ToolCallNotFoundForApprovalError");Symbol.for("vercel.ai.error.AI_MissingToolResultsError");Symbol.for("vercel.ai.error.AI_NoImageGeneratedError");var dW="AI_NoObjectGeneratedError",dG=`vercel.ai.error.${dW}`,dH=Symbol.for(dG),dK=class extends(es=eh,eo=dH,es){constructor({message:t="No object generated.",cause:r,text:a,response:n,usage:i,finishReason:o}){super({name:dW,message:t,cause:r}),this[eo]=!0,this.text=a,this.response=n,this.usage=i,this.finishReason=o}static isInstance(t){return eh.hasMarker(t,dG)}},dY=Symbol.for("vercel.ai.error.AI_NoOutputGeneratedError");Symbol.for("vercel.ai.error.AI_NoSpeechGeneratedError");Symbol.for("vercel.ai.error.AI_NoTranscriptGeneratedError");Symbol.for("vercel.ai.error.AI_NoTranslationGeneratedError");Symbol.for("vercel.ai.error.AI_NoVideoGeneratedError");Symbol.for("vercel.ai.error.AI_NoSuchToolError");Symbol.for("vercel.ai.error.AI_StreamProviderError");Symbol.for("vercel.ai.error.AI_ToolCallRepairError");Symbol.for("vercel.ai.error.AI_ToolChoiceViolationError");var dX="AI_UIMessageStreamError",dQ=`vercel.ai.error.${dX}`,d0=Symbol.for(dQ),d1=class extends(eu=eh,el=d0,eu){constructor({chunkType:t,chunkId:r,message:a}){super({name:dX,message:a}),this[el]=!0,this.chunkType=t,this.chunkId=r}static isInstance(t){return eh.hasMarker(t,dQ)}},d2=Symbol.for("vercel.ai.error.AI_InvalidDataContentError");Symbol.for("vercel.ai.error.AI_InvalidMessageRoleError");Symbol.for("vercel.ai.error.AI_MessageConversionError");Symbol.for("vercel.ai.error.AI_RetryError");var d4=!1;function d6({message:t,type:r}){void 0!==ec.default&&"function"==typeof ec.default.emitWarning?ec.default.emitWarning(t,{type:r}):console.warn(t)}var d5="7.0.118",d9=async({url:t,maxBytes:r,abortSignal:a})=>{let n=t.toString();
91try{let t=oq({},`ai-sdk/${d5}`,oj()),i=await o7({url:n,headers:t,abortSignal:a});if(!i.ok)throw await oV(i),new oH({url:n,statusCode:i.status,statusText:i.statusText});return{data:await se({response:i,url:n,maxBytes:r??0x80000000}),mediaType:i.headers.get("content-type")??void 0}}catch(t){if(oH.isInstance(t))throw t;throw new oH({url:n,cause:t})}},d3=ui,d8=function(t,r){var a;let n;return a=t??(()=>!0),(n=tS(r)).abort??(n.abort=!0),new uP({type:"custom",check:"custom",fn:a,...n})},d7=ug,pe=function(t,r={}){let a=new uz({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...lI.normalizeParams(r)});return a._zod.bag.Class=t,a._zod.check=r=>{r.value instanceof t||r.issues.push({code:"invalid_type",expected:t.name,input:r.value,inst:a,path:[...a._zod.def.path??[]]})},a},pt=function(t,r){return new uo({type:"object",shape:t,catchall:ut(),...lI.normalizeParams(r)})},pr=uu,pa=new uR({type:"lazy",getter:()=>pr([new l8({type:"null",...tS(void 0)}),lM(),l4(),l3(),uf(lM(),pa.optional()),d3(pa)])}),pn=uf(lM(),uf(lM(),pa.optional())),pi=pr([lM(),pe(Uint8Array),pe(ArrayBuffer),d8(function(t){return globalThis.Buffer?.isBuffer(t)??!1},{message:"Must be a Buffer"})]),po=uf(lM(),lM()),ps=us({type:uv("text"),text:lM(),providerOptions:pn.optional()}),pl=us({type:uv("image"),image:pr([pi,pe(URL),po]),mediaType:lM().optional(),providerOptions:pn.optional()}),pu=ud("type",[us({type:uv("data"),data:pi}),us({type:uv("url"),url:pe(URL)}),us({type:uv("reference"),reference:po}),us({type:uv("text"),text:lM()})]),pc=ud("type",[us({type:uv("data"),data:pi}),us({type:uv("url"),url:pe(URL)})]),pd=us({type:uv("file"),data:pr([pu,pi,pe(URL),po]),filename:lM().optional(),mediaType:lM(),providerOptions:pn.optional()}),pp=us({type:uv("reasoning"),text:lM(),providerOptions:pn.optional()}),ph=us({type:uv("custom"),kind:lM().transform(t=>t),providerOptions:pn.optional()}),pf=us({type:uv("reasoning-file"),data:pr([pc,pi,pe(URL)]),mediaType:lM(),providerOptions:pn.optional()}),pm=us({type:uv("tool-call"),toolCallId:lM(),toolName:lM(),input:ut(),providerOptions:pn.optional(),providerExecuted:l3().optional()}),pg=ud("type",[us({type:uv("text"),value:lM(),providerOptions:pn.optional()}),us({type:uv("json"),value:pa,providerOptions:pn.optional()}),us({type:uv("execution-denied"),reason:lM().optional(),providerOptions:pn.optional()}),us({type:uv("error-text"),value:lM(),providerOptions:pn.optional()}),us({type:uv("error-json"),value:pa,providerOptions:pn.optional()}),us({type:uv("content"),value:d3(pr([us({type:uv("text"),text:lM(),providerOptions:pn.optional()}),us({type:uv("file"),data:pu,mediaType:lM(),filename:lM().optional(),providerOptions:pn.optional()}),us({type:uv("file-data"),data:lM(),mediaType:lM(),filename:lM().optional(),providerOptions:pn.optional()}),us({type:uv("file-url"),url:lM(),mediaType:lM().optional(),providerOptions:pn.optional()}),us({type:uv("file-id"),fileId:pr([lM(),uf(lM(),lM())]),providerOptions:pn.optional()}),us({type:uv("file-reference"),providerReference:uf(lM(),lM()),providerOptions:pn.optional()}),us({type:uv("image-data"),data:lM(),mediaType:lM(),providerOptions:pn.optional()}),us({type:uv("image-url"),url:lM(),providerOptions:pn.optional()}),us({type:uv("image-file-id"),fileId:pr([lM(),uf(lM(),lM())]),providerOptions:pn.optional()}),us({type:uv("image-file-reference"),providerReference:uf(lM(),lM()),providerOptions:pn.optional()}),us({type:uv("custom"),providerOptions:pn.optional()})]))})]),py=us({type:uv("tool-result"),toolCallId:lM(),toolName:lM(),output:pg,providerOptions:pn.optional()}),pv=us({type:uv("tool-approval-request"),approvalId:lM(),toolCallId:lM(),reason:lM().optional(),isAutomatic:l3().optional(),signature:lM().optional(),inputSchemaInput:ut().optional()}),pb=us({type:uv("tool-approval-response"),approvalId:lM(),approved:l3(),reason:lM().optional()}),pw=us({role:uv("system"),content:lM(),providerOptions:pn.optional()}),p_=us({role:uv("user"),content:pr([lM(),d3(pr([ps,pl,pd]))]),providerOptions:pn.optional()}),pk=us({role:uv("assistant"),content:pr([lM(),d3(pr([ps,ph,pd,pp,pf,pm,py,pv]))]),providerOptions:pn.optional()}),pE=us({role:uv("tool"),content:d3(pr([py,pb])),providerOptions:pn.optional()});pr([pw,p_,pk,pE]);var pS={},px={array:()=>pO,choice:()=>pP,json:()=>pz,object:()=>pC,text:()=>pA};for(var pI in px)dF(pS,pI,{get:px[pI],enumerable:!0});async function pT(t){if(void 0===t)return{value:void 0,state:"undefined-input"};let r=await sW({text:t});return r.success?{value:r.value,state:"successful-parse"}:(r=await sW({text:function(t){let r=["ROOT"],a=-1,n=null,i=0;function o(t,i,o){switch(t){case'"':a=i,r.pop(),r.push(o),r.push("INSIDE_STRING");break;case"f":case"t":case"n":a=i,n=i,r.pop(),r.push(o),r.push("INSIDE_LITERAL");break;case"-":r.pop(),r.push(o),r.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":a=i,r.pop(),r.push(o),r.push("INSIDE_NUMBER");break;case"{":a=i,r.pop(),r.push(o),r.push("INSIDE_OBJECT_START");break;case"[":a=i,r.pop(),r.push(o),r.push("INSIDE_ARRAY_START")}}function s(t,n){switch(t){case",":r.pop(),r.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":a=n,r.pop()}}function l(t,n){switch(t){case",":r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":a=n,r.pop()}}for(let u=0;u<t.length;u++){let c=t[u];switch(r[r.length-1]){case"ROOT":o(c,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(c){case'"':r.pop(),r.push("INSIDE_OBJECT_KEY");break;case"}":a=u,r.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":'"'===c&&(r.pop(),r.push("INSIDE_OBJECT_KEY"));break;case"INSIDE_OBJECT_KEY":'"'===c&&(r.pop(),r.push("INSIDE_OBJECT_AFTER_KEY"));break;case"INSIDE_OBJECT_AFTER_KEY":":"===c&&(r.pop(),r.push("INSIDE_OBJECT_BEFORE_VALUE"));break;case"INSIDE_OBJECT_BEFORE_VALUE":o(c,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":s(c,u);break;case"INSIDE_STRING":switch(c){case'"':r.pop(),a=u;break;case"\\":r.push("INSIDE_STRING_ESCAPE");break;default:a=u}break;case"INSIDE_ARRAY_START":"]"===c?(a=u,r.pop()):(a=u,o(c,u,"INSIDE_ARRAY_AFTER_VALUE"));break;case"INSIDE_ARRAY_AFTER_VALUE":switch(c){case",":r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":a=u,r.pop();break;default:a=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(c,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":r.pop(),"u"===c?(i=0,r.push("INSIDE_STRING_UNICODE_ESCAPE")):a=u;break;case"INSIDE_STRING_UNICODE_ESCAPE":(c>="0"&&c<="9"||c>="A"&&c<="F"||c>="a"&&c<="f")&&4==++i&&(r.pop(),a=u);break;case"INSIDE_NUMBER":switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":a=u;break;case"e":case"E":case"-":case".":break;case",":r.pop(),"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&l(c,u),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]&&s(c,u);break;case"}":r.pop(),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]&&s(c,u);break;case"]":r.pop(),"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&l(c,u);break;default:r.pop()}break;case"INSIDE_LITERAL":{let i=t.substring(n,u+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?a=u:(r.pop(),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]?s(c,u):"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&l(c,u))}}}let u=t.slice(0,a+1);for(let a=r.length-1;a>=0;a--)switch(r[a]){case"INSIDE_STRING":u+='"';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":u+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":u+="]";break;case"INSIDE_LITERAL":{let r=t.substring(n,t.length);"true".startsWith(r)?u+="true".slice(r.length):"false".startsWith(r)?u+="false".slice(r.length):"null".startsWith(r)&&(u+="null".slice(r.length))}}return u}(t)})).success?{value:r.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"}}var pA=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),parseCompleteOutput:async({text:t})=>t,parsePartialOutput:async({text:t})=>({partial:t}),createElementStreamTransform(){}}),pC=({schema:t,name:r,description:a})=>{let n=sZ(t);return{name:"object",responseFormat:s0(n.jsonSchema).then(t=>({type:"json",schema:t,...null!=r&&{name:r},...null!=a&&{description:a}})),async parseCompleteOutput({text:t},r){let a=await sW({text:t});if(!a.success)throw new dK({message:"No object generated: could not parse the response.",cause:a.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});let i=await sV({value:a.value,schema:n});if(!i.success)throw new dK({message:"No object generated: response did not match sc
91hema.",cause:i.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});return i.value},async parsePartialOutput({text:t}){let r=await pT(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value}}},createElementStreamTransform(){}}},pO=({element:t,minItems:r,maxItems:a,name:n,description:i})=>{if(pM({name:"minItems",value:r}),pM({name:"maxItems",value:a}),null!=r&&null!=a&&r>a)throw new dV({parameter:"minItems",value:r,message:"minItems must be less than or equal to maxItems"});let o=sZ(t);return{name:"array",responseFormat:s0(o.jsonSchema).then(t=>{let{$schema:o,definitions:s,$defs:l,...u}=t;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...null!=s&&{definitions:s},...null!=l&&{$defs:l},type:"object",properties:{elements:{type:"array",items:u,...null!=r&&{minItems:r},...null!=a&&{maxItems:a}}},required:["elements"],additionalProperties:!1},...null!=n&&{name:n},...null!=i&&{description:i}}}),async parseCompleteOutput({text:t},n){let i=await sW({text:t});if(!i.success)throw new dK({message:"No object generated: could not parse the response.",cause:i.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let s=i.value;if(null==s||"object"!=typeof s||!("elements"in s)||!Array.isArray(s.elements))throw new dK({message:"No object generated: response did not match schema.",cause:new eZ({value:s,cause:"response must be an object with an elements array"}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let l=pR({value:s.elements,minItems:r,maxItems:a});if(null!=l)throw new dK({message:"No object generated: response did not match schema.",cause:l,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let u=[];for(let r of s.elements){let a=await sV({value:r,schema:o});if(!a.success)throw new dK({message:"No object generated: response did not match schema.",cause:a.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});u.push(a.value)}return u},async parsePartialOutput({text:t}){let r=await pT(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let t=r.value;if(null==t||"object"!=typeof t||!("elements"in t)||!Array.isArray(t.elements))return;let a="repaired-parse"===r.state&&t.elements.length>0?t.elements.slice(0,-1):t.elements,n=[];for(let t of a){let r=await sV({value:t,schema:o});r.success&&n.push(r.value)}return{partial:n}}}},createElementStreamTransform(){let t=0;return new TransformStream({transform({partialOutput:r},n){if(null!=r)for(;t<r.length;t++){if(null!=a&&t>=a)return void n.error(pR({value:r,maxItems:a}));n.enqueue(r[t])}}})}}};function pM({name:t,value:r}){if(null!=r){if(!Number.isInteger(r))throw new dV({parameter:t,value:r,message:`${t} must be an integer`});if(r<0)throw new dV({parameter:t,value:r,message:`${t} must be greater than or equal to 0`})}}function pR({value:t,minItems:r,maxItems:a}){return null!=r&&t.length<r?new eZ({value:t,cause:`elements array must contain at least ${r} items`}):null!=a&&t.length>a?new eZ({value:t,cause:`elements array must contain at most ${a} items`}):void 0}var pP=({options:t,name:r,description:a})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...null!=r&&{name:r},...null!=a&&{description:a}}),async parseCompleteOutput({text:r},a){let n=await sW({text:r});if(!n.success)throw new dK({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});let i=n.value;if(null==i||"object"!=typeof i||!("result"in i)||"string"!=typeof i.result||!t.includes(i.result))throw new dK({message:"No object generated: response did not match schema.",cause:new eZ({value:i,cause:"response must be an object that contains a choice value."}),text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return i.result},async parsePartialOutput({text:r}){let a=await pT(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let r=a.value;if(null==r||"object"!=typeof r||!("result"in r)||"string"!=typeof r.result)return;let n=t.filter(t=>t.startsWith(r.result));if("successful-parse"===a.state)return n.includes(r.result)?{partial:r.result}:void 0;return 1===n.length?{partial:n[0]}:void 0}}},createElementStreamTransform(){}}),pz=({name:t,description:r}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...null!=t&&{name:t},...null!=r&&{description:r}}),async parseCompleteOutput({text:t},r){let a=await sW({text:t});if(!a.success)throw new dK({message:"No object generated: could not parse the response.",cause:a.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});return a.value},async parsePartialOutput({text:t}){let r=await pT(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return void 0===r.value?void 0:{partial:r.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,st({prefix:"aitxt",size:24}),st({prefix:"call",size:24}),TransformStream;var p$=uf(lM(),pa.optional()),pN=sL(()=>sB(pr([pt({type:uv("text-start"),id:lM(),providerMetadata:pn.optional()}),pt({type:uv("text-delta"),id:lM(),delta:lM(),providerMetadata:pn.optional()}),pt({type:uv("text-end"),id:lM(),providerMetadata:pn.optional()}),pt({type:uv("error"),errorText:lM()}),pt({type:uv("tool-input-start"),toolCallId:lM(),toolName:lM(),providerExecuted:l3().optional(),providerMetadata:pn.optional(),toolMetadata:p$.optional(),dynamic:l3().optional(),title:lM().optional()}),pt({type:uv("tool-input-delta"),toolCallId:lM(),inputTextDelta:lM()}),pt({type:uv("tool-input-available"),toolCallId:lM(),toolName:lM(),input:ut(),providerExecuted:l3().optional(),providerMetadata:pn.optional(),toolMetadata:p$.optional(),dynamic:l3().optional(),title:lM().optional()}),pt({type:uv("tool-input-error"),toolCallId:lM(),toolName:lM(),input:ut(),providerExecuted:l3().optional(),providerMetadata:pn.optional(),toolMetadata:p$.optional(),dynamic:l3().optional(),errorText:lM(),title:lM().optional()}),pt({type:uv("tool-approval-request"),approvalId:lM(),toolCallId:lM(),approvalDescriptor:ut().optional(),inputSchemaInput:ut().optional(),reason:lM().optional(),isAutomatic:l3().optional(),signature:lM().optional()}),pt({type:uv("tool-approval-response"),approvalId:lM(),approved:l3(),reason:lM().optional(),providerExecuted:l3().optional(),providerMetadata:pn.optional()}),pt({type:uv("tool-output-available"),toolCallId:lM(),output:ut(),providerExecuted:l3().optional(),providerMetadata:pn.optional(),toolMetadata:p$.optional(),dynamic:l3().optional(),preliminary:l3().optional()}),pt({type:uv("tool-output-error"),toolCallId:lM(),errorText:lM(),providerExecuted:l3().optional(),providerMetadata:pn.optional(),toolMetadata:p$.optional(),dynamic:l3().optional()}),pt({type:uv("tool-output-denied"),toolCallId:lM()}),pt({type:uv("reasoning-start"),id:lM(),providerMetadata:pn.optional()}),pt({type:uv("reasoning-delta"),id:lM(),delta:lM(),providerMetadata:pn.optional()}),pt({type:uv("reasoning-end"),id:lM(),providerMetadata:pn.optional()}),pt({type:uv("custom"),kind:lM().transform(t=>t),providerMetadata:pn.optional()}),pt({type:uv("source-url"),sourceId:lM(),url:lM(),title:lM().optional(),providerMetadata:pn.optional()}),pt({type:uv("source-document"),sourceId:lM(),mediaType:lM(),title:lM(),filename:lM().optional(),providerMetadata:pn.optional()}),pt({type:uv("file"),url:lM(),mediaType:lM(),providerMetadata:pn.optional()}),pt({type:uv("reasoning-file"),url:lM(),mediaType:lM(),providerMetadata:pn.optional()}),pt({type:d8(t=>"string"==typeof t&&t.startsWith("data-"),{message:'Type must start with "data-"'}),id:lM().optional(),data:ut(),transient:l3().optional()}),pt({type:uv("start-step")}),pt({type:uv("finish-step")}),pt({type:uv("reset-step")}),pt({type:uv("start"),messageId:lM().optional(),messageMetadata:ut().optional()}),pt({type:uv("finish"),finishReason:d7(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:ut().optional()}),pt({type:uv("abort"),reason:lM().optional()}),pt({type:uv("message-metadata"),messageMetadata:ut()})])));function pj(){return Object.create(null)}function pD(t){return t.type.startsWith("tool-")}function pU(t){return pD(t)||"dynamic-tool"===t.type}function pL(t){return t.type.split("-").slice(1).join("-")}var pF={type:"deprecated",setting:"rawInput in output-error UI message parts",message:'Use the "input" field instead. The "rawInput" field will be removed in the next major version.'};async function pZ({stream:t,onError:r,abortSignal:a}){let n=t.getReader(),i=()=>{n.cancel().catch(()=>{})};a?.aborted?i():a?.addEventListener("abort",i,{once:!0});try{for(;;){let{done:t}=await n.read();if(t)break}}catch(t){r?.(t)}finally{a?.removeEventListener("abort",i),n.releaseLock()}}st({prefix:"aitxt",size:24}),st({prefix:"call",size:24}),st({prefix:"aitxt",size:24}),st({prefix:"call",size:24});var pB=uf(lM(),pa.optional()),pq=uf(lM(),lM());function pV(t){return({url:r,abortSignal:a})=>d9({url:r,maxBytes:t?.maxBytes,abortSignal:a})}sL(()=>{let t=us({id:lM(),approved:ua().optional(),descriptor:ut().optional(),requestReason:lM().optional(),reason:ua().optional(),isAutomatic:l3().optional(),signature:lM().optional(),inputSchemaInput:ut().optional()}),r=t.extend({approved:l3(),reason:lM().optional()}),a=r.extend({approved:uv(!0)}),n=r.extend({approved:uv(!1)});return sB(d3(us({id:lM(),role:d7(["system","user","assistant"]),metadata:ut().optional(),parts:d3(pr([us({type:uv("text"),text:lM(),state:d7(["streaming","done"]).optional(),providerMetadata:pn.optional()}),us({type:uv("reasoning"),id:lM().optional(),text:lM(),state:d7(["streaming","done"]).optional(),providerMetadata:pn.optional()}),us({type:uv("custom"),kind:lM(),providerMetadata:pn.optional()}),us({type:uv("source-url"),sourceId:lM(),url:lM(),title:lM().optional(),providerMetadata:pn.optional()}),us({type:uv("source-document"),sourceId:lM(),mediaType:lM(),title:lM(),filename:lM().optional(),providerMetadata:pn.optional()}),us({type:uv("file"),mediaType:lM(),filename:lM().optional(),url:lM(),providerReference:pq.optional(),providerMetadata:pn.optional()}),us({type:uv("reasoning-file"),mediaType:lM(),url:lM(),providerMetadata:pn.optional()}),us({type:uv("step-start")}),us({type:lM().startsWith("data-"),id:lM().optional(),data:ut()}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("input-streaming"),input:ut().optional(),providerExecuted:l3().optional(),callProviderMetadata:pn.optional(),output:ua().optional(),errorText:ua().optional(),approval:ua().optional()}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("input-available"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:ua().optional()}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("approval-requested"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:t}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("approval-responded"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:r}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-available"),input:ut(),providerExecuted:l3().optional(),output:ut(),errorText:ua().optional(),callProviderMetadata:pn.optional(),resultProviderMetadata:pn.optional(),preliminary:l3().optional(),approval:a.optional()}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-error"),input:ut().optional(),rawInput:ut().optional(),providerExecuted:l3().optional(),output:ua().optional(),errorText:lM(),c
91allProviderMetadata:pn.optional(),resultProviderMetadata:pn.optional(),approval:a.optional()}),us({type:uv("dynamic-tool"),toolName:lM(),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-denied"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:n}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("input-streaming"),providerExecuted:l3().optional(),callProviderMetadata:pn.optional(),input:ut().optional(),output:ua().optional(),errorText:ua().optional(),approval:ua().optional()}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("input-available"),providerExecuted:l3().optional(),input:ut(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:ua().optional()}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("approval-requested"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:t}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("approval-responded"),input:ut(),providerExecuted:l3().optional(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:r}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-available"),providerExecuted:l3().optional(),input:ut(),output:ut(),errorText:ua().optional(),callProviderMetadata:pn.optional(),resultProviderMetadata:pn.optional(),preliminary:l3().optional(),approval:a.optional()}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-error"),providerExecuted:l3().optional(),input:ut().optional(),rawInput:ut().optional(),output:ua().optional(),errorText:lM(),callProviderMetadata:pn.optional(),resultProviderMetadata:pn.optional(),approval:a.optional()}),us({type:lM().startsWith("tool-"),toolCallId:lM(),title:lM().optional(),toolMetadata:pB.optional(),state:uv("output-denied"),providerExecuted:l3().optional(),input:ut(),output:ua().optional(),errorText:ua().optional(),callProviderMetadata:pn.optional(),approval:n})]))}).superRefine((t,r)=>{"assistant"!==t.role&&0===t.parts.length&&r.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:t.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty"))}),st({prefix:"call",size:24}),st({prefix:"call",size:24}),new TextEncoder,st({prefix:"call",size:24}),st({prefix:"aiobj",size:24});var{atob:pJ}=globalThis,pW=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(t){return new Promise((r,a)=>{this.queue.push(async()=>{try{await t(),r()}catch(t){a(t)}}),this.processQueue()})}};st({prefix:"aiobj",size:24}),pV();var pG=class{constructor(t){this.captureContext=null,this.captureProcessor=null,this.captureSource=null,this.captureStream=null,this.ownsCaptureStream=!0,this.captureCleanup=[],this.captureGeneration=0,this.playbackContext=null,this.playbackQueue=[],this.playbackTime=0,this.playbackStartTime=0,this.activeSources=new Set,this.isPlaying=!1,this.playbackPaused=!1,this.captureSampleRate=t.captureSampleRate,this.playbackSampleRate=t.playbackSampleRate,this.onAudio=t.onAudio,this.onPlayingChange=t.onPlayingChange,this.maxPlaybackSeconds=t.maxPlaybackSeconds??1/0,this.onError=t.onError,this.onCapturingChange=t.onCapturingChange}ensurePlaybackContext(){if(null==this.playbackContext){this.playbackContext=new AudioContext({sampleRate:this.playbackSampleRate});let t=this.playbackContext;t.onstatechange=()=>{this.playbackContext===t&&this.setPlaying("running"===t.state&&this.activeSources.size>0)}}}async resumePlayback(){this.ensurePlaybackContext();let t=this.playbackContext;this.playbackPaused&&this.stopPlayback(),this.playbackContext!==t||(await t?.resume(),this.playbackContext===t&&(this.playbackPaused=!1,this.setPlaying(this.playbackContext?.state==="running"&&this.activeSources.size>0)))}startCapture(t,r){let a=this.captureGeneration+1;if(this.stopCapture(),a!==this.captureGeneration){(r?.ownsStream??!0)&&t.getTracks().forEac
91h(t=>t.stop());return}this.captureStream=t,this.ownsCaptureStream=r?.ownsStream??!0;let n=new AudioContext({sampleRate:this.captureSampleRate});this.captureContext=n,n.resume().catch(t=>{this.captureContext===n&&this.onError?.(t)});let i=n.createMediaStreamSource(t);this.captureSource=i;let o=n.createScriptProcessor(1024,1,1);this.captureProcessor=o,o.onaudioprocess=t=>{if(this.captureContext!==n)return;let r=function(t,r,a){if(r===a)return t;let n=r/a,i=Math.round(t.length/n),o=new Float32Array(i);for(let r=0;r<i;r++){let a=r*n,i=Math.floor(a),s=Math.min(i+1,t.length-1),l=a-i;o[r]=t[i]*(1-l)+t[s]*l}return o}(new Float32Array(t.inputBuffer.getChannelData(0)),n.sampleRate,this.captureSampleRate);try{this.onAudio(function(t){let r=new ArrayBuffer(2*t.length),a=new DataView(r);for(let r=0;r<t.length;r++){let n=Math.max(-1,Math.min(1,t[r]));a.setInt16(2*r,n<0?32768*n:32767*n,!0)}let n=new Uint8Array(r),i="";for(let t=0;t<n.length;t+=32768)i+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(i)}(r))}catch(t){this.onError?.(t instanceof Error?t:Error(String(t)))}},i.connect(o),o.connect(n.destination);let s=()=>this.onCapturingChange(t.getAudioTracks().some(t=>t.enabled&&!t.muted&&"live"===t.readyState));for(let r of t.getAudioTracks())for(let t of["ended","mute","unmute"])r.addEventListener(t,s),this.captureCleanup.push(()=>r.removeEventListener(t,s));s()}stopCapture(){for(let t of(this.captureGeneration++,null!=this.captureProcessor&&(this.captureProcessor.onaudioprocess=null),this.captureCleanup))t();this.captureCleanup=[],this.captureProcessor?.disconnect(),this.captureSource?.disconnect(),this.captureContext?.close().catch(()=>{}),this.ownsCaptureStream&&this.captureStream?.getTracks().forEach(t=>t.stop()),this.captureProcessor=null,this.captureSource=null,this.captureContext=null,this.captureStream=null,this.onCapturingChange(!1)}playAudio(t){if(this.playbackPaused)return;this.ensurePlaybackContext();let r=function(t){let r=atob(t),a=new Uint8Array(r.length);for(let t=0;t<r.length;t++)a[t]=r.charCodeAt(t);let n=new Int16Array(a.buffer),i=new Float32Array(n.length);for(let t=0;t<n.length;t++)i[t]=n[t]/32768;return i}(t);if(Math.max(0,this.playbackTime-(this.playbackContext?.currentTime??0))+r.length/this.playbackSampleRate>this.maxPlaybackSeconds){this.playbackPaused=!0,this.stopPlayback(),this.onError?.(Error("Realtime audio playback buffer is full; playback paused, call resumePlayback() to resume at the live edge"));return}this.playbackQueue.push(r),this.schedulePlayback()}stopPlayback(){for(let t of(this.playbackQueue=[],this.activeSources))try{t.onended=null,t.stop(),t.disconnect()}catch{}this.activeSources.clear(),null!=this.playbackContext&&(this.playbackTime=this.playbackContext.currentTime),this.setPlaying(!1)}getPlaybackOffsetMs(){let t=this.playbackContext;return null==t?0:(t.currentTime-this.playbackStartTime)*1e3}dispose(){this.stopCapture(),this.stopPlayback(),null!=this.playbackContext&&(this.playbackContext.onstatechange=null),this.playbackContext?.close().catch(()=>{}),this.playbackContext=null,this.playbackTime=0,this.playbackPaused=!1}setPlaying(t){t&&!this.isPlaying&&(this.playbackStartTime=this.playbackContext?.currentTime??0),this.isPlaying!==t&&(this.isPlaying=t,this.onPlayingChange(t))}schedulePlayback(){let t=this.playbackContext;if(null!=t&&0!==this.playbackQueue.length)for(;this.playbackQueue.length>0;){let r=this.playbackQueue.shift(),a=t.createBuffer(1,r.length,this.playbackSampleRate);a.getChannelData(0).set(r);let n=t.createBufferSource();n.buffer=a,n.connect(t.destination);let i=Math.max(this.playbackTime,t.currentTime);if(n.start(i),this.playbackTime=i+a.duration,this.activeSources.add(n),this.setPlaying("running"===t.state),this.playbackContext!==t)return;n.onended=()=>{n.disconnect(),this.activeSources.delete(n),0===this.playbackQueue.length&&0===this.activeSources.size&&this.setPlaying(!1)}}}},pH=class{constructor(t){this.options=t,this.active=!0,this.finishing=!1,this.incoming=Promise.resolve(),this.outgoing=Promise.resolve(),this.incomingCount=0,this.incomingBytes=0,this.outgoingCount=0,this.parse=t.model.createServerEventParser?.()??t.model.parseServerEvent.bind(t.model)}get hasPendingIncoming(){return this.incomingCount>0}dispose(){this.active=!1}async finish(){this.stopWriting(),await this.incoming,this.dispose()}stopWriting(){this.finishing=!0}send(t,r){if(!this.active||this.finishing)throw Error("Realtime connection is closed");if(this.outgoingCount>=(this.options.maxPending??512))throw Error("Realtime outgoing queue is full");this.outgoingCount++;let a=this.outgoing.then(async()=>
91{if(!this.active||this.finishing)throw Error("Realtime connection is closed");if(r?.()===!1)return;if(!this.active||this.finishing)throw Error("Realtime connection is closed");let a=await this.options.model.serializeClientEvent(t);if(!this.active||this.finishing)throw Error("Realtime connection is closed");if(r?.()!==!1){if(!this.active||this.finishing)throw Error("Realtime connection is closed");null!=a&&this.options.send(a)}});return this.outgoing=a.catch(r=>{this.finishing||"input-audio-append"===t.type||"session-close"===t.type||this.report(r)}).finally(()=>{this.outgoingCount--}),a}receive(t){if(!this.active||this.finishing)return;let r="string"==typeof t?2*t.length:t instanceof Blob?t.size:t.byteLength??0;if(this.incomingCount>=(this.options.maxPending??512)||this.incomingBytes+r>(this.options.maxPendingBytes??8388608)){this.finishing=!0,this.fatal(Error("Realtime incoming queue is full; input protocol continuity was lost"));return}this.incomingCount++,this.incomingBytes+=r,this.incoming=this.incoming.then(async()=>{if(!this.active)return;let r="string"==typeof t?t:t instanceof Blob?await t.text():new TextDecoder().decode(t),a=await sW({text:r});if(!this.active)return;if(!a.success)throw Error("Invalid JSON in realtime server message",{cause:a.error});let n=this.options.model.getHealthCheckResponse?.(a.value);if(!this.active||(null==n||this.finishing||this.options.send(n),!this.active))return;let i=this.parse(a.value);for(let t of Array.isArray(i)?i:[i]){if(!this.active)return;try{await this.options.onEvent(t)}catch(t){this.report(t)}}}).catch(t=>{this.finishing=!0,this.fatal(t instanceof Error?t:Error(String(t)))}).finally(()=>{this.incomingCount--,this.incomingBytes-=r})}fatal(t){this.active&&(null!=this.options.onFatalError?this.options.onFatalError(t):this.report(t))}report(t){if(this.active)try{this.options.onError(t instanceof Error?t:Error(String(t)))}catch{}}},pK=class{constructor(t){this.options=t,this.ws=null,this.epoch=0,this.failing=!1,this.closing=!1,this.model=t.model,this.continuous=t.model.capabilities?.conversation==="continuous",this.onServerEvent=t.onServerEvent,this.onError=t.onError,this.onClose=t.onClose}get isOpen(){return!this.closing&&!this.failing&&this.ws?.readyState===WebSocket.OPEN}connect({mode:t,token:r,url:a,onOpen:n,protocols:i}){let o;this.disconnect();let s=this.epoch;if("relay"!==t&&("client-secret"!==t||"string"!=typeof r||""===r.trim()))throw Error("Realtime client-secret connection requires a nonempty token");let l="relay"===t?{url:a,protocols:i}:this.model.getWebSocketConfig?.({token:r,url:a});if(this.epoch!==s)return;if(null==l)throw Error("Model does not support client-secret WebSockets");let u=l.url,c=l.protocols;if(this.epoch!==s)return;try{if("string"!=typeof u||!/^wss?:\/\//i.test(u))throw Error("Invalid realtime WebSocket URL");let t=new URL(u);if(!["ws:","wss:"].includes(t.protocol)||""===t.hostname||u.includes("#"))throw Error("Invalid realtime WebSocket URL")}catch{throw Error("Invalid realtime WebSocket URL; expected an absolute ws:// or wss:// URL with a host and no fragment")}if(this.epoch!==s)return;let d=new WebSocket(u,c);this.ws=d;let p=!1,h=new pH({model:this.model,send:t=>{if(this.epoch!==s||this.ws!==d||!this.isOpen)throw Error("Realtime WebSocket is not open");this.sendRaw(t)},onEvent:this.onServerEvent,onError:t=>{p||this.onError(t)},onFatalError:t=>this.fail(t)});this.epoch!==s?h.dispose():(this.codec=h,d.onopen=()=>{if(this.ws===d){p=!0;try{Promise.resolve(n()).catch(t=>{this.ws===d&&this.fail(t instanceof Error?t:Error(String(t)))}).finally(()=>{p=!1})}catch(t){this.epoch===s&&this.fail(t instanceof Error?t:Error(String(t)))}}},d.onmessage=t=>{this.ws===d&&this.codec?.receive(t.data)},d.onerror=()=>{this.ws===d&&(o=Error("WebSocket connection error"),this.failing=!0)},d.onclose=t=>{if(this.ws===d){this.ws=null;let r=function(t){if(1e3!==t.code||!t.wasClean)return Error(`Realtime WebSocket closed unexpectedly (code ${t.code}${""===t.reason?"":`: ${t.reason}`})`)}(t)??o,a=null!=r&&!h.hasPendingIncoming;if(h.stopWriting(),this.notifyClosing(),this.epoch!==s)return;let n=h.finish();if(a){try{this.onError(r)}catch{}if(this.epoch!==s)return}let i=()=>
91{if(this.epoch===s){clearTimeout(this.drainTimer),this.epoch++,h.dispose();try{this.onClose(r)}catch(t){this.reportCallbackError(t)}}};this.drainTimer=setTimeout(i,1e3),this.awaitDrain(n,i)}})}disconnect(){this.epoch++,clearTimeout(this.drainTimer);let t=this.ws;this.ws=null,this.codec?.dispose(),this.codec=void 0,this.failing=!1,this.closing=!1,t?.close()}sendEvent(t,r,a=!1){if(this.failing||this.closing)throw Error("Realtime connection is closed");if(null==this.codec)return Promise.resolve();let n=this.epoch,i=t=>{a&&this.epoch===n&&this.isOpen&&this.fail(t instanceof Error?t:Error(String(t)))};try{let a=this.codec.send(t,r);return a.catch(i),a}catch(t){throw i(t),t}}finish(){return this.codec?.finish()??Promise.resolve()}fail(t){if(this.failing)return;this.failing=!0;let r=this.epoch,a=this.ws;if(this.ws=null,this.codec?.stopWriting(),a?.close(),this.notifyClosing(),this.epoch!==r)return;let n=this.finish();if(null!=this.options.onFatalError)this.options.onFatalError(t,n);else{let a=()=>{if(r===this.epoch){this.disconnect();try{this.onClose()}catch(t){this.reportCallbackError(t)}}};this.drainTimer=setTimeout(a,1e3),this.awaitDrain(n,a),this.reportCallbackError(t)}}notifyClosing(){if(!this.closing){this.closing=!0;try{this.options.onClosing?.()}catch(t){this.reportCallbackError(t)}}}async awaitDrain(t,r){try{await t}catch{}try{r()}catch(t){this.reportCallbackError(t)}}reportCallbackError(t){try{this.onError(t instanceof Error?t:Error(String(t)))}catch{}}sendRaw(t){let r=this.ws,a=this.epoch;if(null==r||!this.isOpen)return;let n=function(t){if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return{data:t,byteLength:t.byteLength};if(t instanceof Blob)return{data:t,byteLength:t.size};let r="string"==typeof t?t:JSON.stringify(t);if(void 0===r)throw Error("Realtime event could not be encoded as JSON");return{data:r,byteLength:new TextEncoder().encode(r).byteLength}}(t);if(this.epoch!==a||this.ws!==r||!this.isOpen)throw Error("Realtime connection is closed");this.continuous&&function(t,r){if(t.byteLength>131072)throw Error("Realtime frame exceeds the 131072-byte limit; reduce the event payload");if(r+t.byteLength>131072)throw Error("Realtime send buffer is full (131072-byte limit); wait before retrying")}(n,r.bufferedAmount),r.send(n.data)}dispose(){this.disconnect()}},pY=class{constructor(t){this.options=t,this.generation=0,this.ready=!1,this.capturingStarted=!1,this.pendingAudio=0,this.captureGeneration=0,this.captureEnabled=!0;const r=t.sessionConfig?.inputAudioFormat,a=t.sessionConfig?.outputAudioFormat,n=r?.rate??a?.rate??t.sampleRate??24e3,i={type:r?.type??a?.type??"audio/pcm",rate:n};this.config={...t.sessionConfig,inputAudioFormat:{...i,...r},outputAudioFormat:{...i,...a}},this.transport=new pK({model:t.model,onServerEvent:t.onEvent,onError:t.onError,onFatalError:t.onFatalError,onClosing:()=>{let r=this.generation;t.onClosing?.(),r===this.generation&&this.stopCapture()},onClose:t.onClose}),this.audio=new pG({captureSampleRate:this.config.inputAudioFormat?.rate??n,playbackSampleRate:this.config.outputAudioFormat?.rate??n,maxPlaybackSeconds:t.maxPlaybackBufferSeconds??2,onAudio:t=>this.sendAudio(t),onError:t.onError,onCapturingChange:t.onCapturing,onPlayingChange:t.onPlaying})}connect(t){let r=this.generation+1;if(this.dispose(),r===this.generation){for(let t of[this.config.inputAudioFormat,this.config.outputAudioFormat]){if(t?.type!=="audio/pcm")throw new eJ({functionality:"Continuous browser WebSocket audio supports PCM16 only"});if(null==t.rate||!Number.isFinite(t.rate)||t.rate<8e3||t.rate>96e3)throw Error("Invalid realtime PCM sample rate")}this.stream=t.stream,this.captureEnabled=!1!==t.capture,this.audio.ensurePlaybackContext(),this.audio.resumePlayback().catch(t=>{r===this.generation&&this.options.onError(t)}),this.transport.connect({mode:"relay",url:t.url,protocols:t.protocols,onOpen:()=>this.transport.sendEvent({type:this.options.model.capabilities?.startup??"session-update",config:this.config})})}}startCapture(){this.ready=!0,this.captureEnabled&&!this.capturingStarted&&this.resumeCapture().catch(t=>this.options.onError(t))}async resumeCapture(t){let r=this.captureGeneration+1;if(this.stopCapture(),r!==this.captureGeneration)return;this.ready=!0,this.capturingStarted=!0,this.captureEnabled=!0,null!=t&&(this.stream=t);let a=this.stream,n=a??await navigator.mediaDevices.getUserMedia({audio:!0});if(r!==this.captureGeneration||!this.ready){null==a&&n.getTracks().forEac
91h(t=>t.stop());return}if(!n.getAudioTracks().some(t=>"live"===t.readyState))throw null==a&&n.getTracks().forEach(t=>t.stop()),Error("Realtime requires a live audio track");this.audio.startCapture(n,{ownsStream:null==a})}sendAudio(t){let r;if(!this.ready||!this.transport.isOpen)return;if(this.pendingAudio>=8)return void this.transport.fail(Error("Realtime audio send queue is full"));let a=this.generation;try{r=this.transport.sendEvent({type:"input-audio-append",audio:t},void 0,!0)}catch(t){if(!this.ready||!this.transport.isOpen)return;throw t}this.pendingAudio++,r.then(()=>{a===this.generation&&this.pendingAudio--},t=>{a===this.generation&&this.ready&&this.transport.isOpen&&this.options.onFatalError(t)})}sendEvent(t,r){if("session-update"===t.type)for(let r of["inputAudioFormat","outputAudioFormat"]){let a=t.config[r];if(null!=a&&(a.type!==this.config[r]?.type||null!=a.rate&&a.rate!==this.config[r]?.rate))throw Error("Changing Live WebSocket audio format requires reconnecting")}return this.transport.sendEvent(t,r)}playAudio(t){try{this.audio.playAudio(t)}catch(t){this.options.onError(t instanceof Error?t:Error(String(t)))}}stopPlayback(){this.audio.stopPlayback()}resumePlayback(){return this.audio.resumePlayback()}stopCapture(){this.captureGeneration++,this.ready=!1,this.capturingStarted=!1,this.captureEnabled=!1,this.audio.stopCapture()}finish(){return this.transport.finish()}dispose(){this.generation++,this.stopCapture(),this.ready=!1,this.capturingStarted=!1,this.pendingAudio=0,this.stream=void 0,this.transport.disconnect(),this.audio.dispose()}};async function pX(t){let r=t.body?.getReader();if(null==r)throw Error("Invalid realtime session answer");let a=new TextDecoder,n=0,i="";try{if(Number(t.headers.get("content-length"))>1048576)throw Error("Realtime session answer exceeds the 1 MiB limit");for(;;){let{done:t,value:o}=await r.read();if(t)return i+a.decode();if((n+=o.byteLength)>1048576)throw Error("Realtime session answer exceeds the 1 MiB limit");i+=a.decode(o,{stream:!0})}}catch(t){throw r.cancel(t).catch(()=>{}),t}finally{r.releaseLock()}}function pQ(t){let r=t.getAudioTracks().filter(t=>"live"===t.readyState);return r.find(t=>t.enabled&&!t.muted)??r[0]}var p0=class{constructor(t){this.options=t,this.ownsStream=!1,this.generation=0,this.closingNotified=!1,this.captureGeneration=0,this.senderOperations=Promise.resolve(),this.trackCleanups=[]}async connect({api:t,sessionConfig:r,stream:a,timeoutMs:n,capture:i=!0}){let o=this.generation+1;this.dispose();let s=()=>o===this.generation;if(!s())return;let l=this.options.model.getWebRTCConfig?.();if(!s())return;if(null==l)throw Error("This model does not support WebRTC configuration");let u=new AbortController;this.abort=u;let c=setTimeout(()=>u.abort(Error("Realtime startup timed out")),n),d=new Promise((t,r)=>{u.signal.addEventListener("abort",()=>r(u.signal.reason),{once:!0})}),p=async()=>{let n=this.captureGeneration,o=i?a??await navigator.mediaDevices.getUserMedia({audio:!0}):void 0;if(!s()||u.signal.aborted)throw null==a&&o?.getTracks().forEach(t=>t.stop()),Error("Realtime connection cancelled");n!==this.captureGeneration&&(null==a&&o?.getTracks().forEach(t=>t.stop()),o=void 0),this.stream=o,this.ownsStream=null==a;let c=null==o?void 0:pQ(o);if(null!=o&&null==c)throw Error("Realtime requires a live audio track");let p=new RTCPeerConnection;this.pc=p;let h=document.createElement("audio");h.autoplay=!0,this.audio=h,h.onplaying=()=>{s()&&this.options.onPlaying(!0)};let f=()=>{s()&&this.options.onPlaying(!1)};h.onpause=f,h.onended=f,h.onwaiting=f,p.ontrack=t=>{s()&&(h.srcObject=t.streams[0]??new MediaStream([t.track]),h.play().catch(t=>{s()&&this.options.onError(t)}))},p.onconnectionstatechange=()=>{s()&&("connected"===p.connectionState?clearTimeout(this.disconnectTimer):"disconnected"===p.connectionState?(clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{s()&&"disconnected"===p.connectionState&&this.fail(Error("Realtime peer disconnected beyond recovery grace period"))},this.options.disconnectTimeoutMs??5e3)):"closed"===p.connectionState?this.drainClose(Error("Realtime peer connection closed")):"failed"===p.connectionState&&this.fail(Error(`Realtime peer connection ${p.connectionState}`)))},p.oniceconnectionstatechange=()=>{s()&&"failed"===p.iceConnectionState&&this.fail(Error("Realtime ICE connection failed"))};
91let m=p.createDataChannel(l.dataChannelLabel);this.dc=m;let g=new pH({model:this.options.model,onEvent:this.options.onEvent,onError:this.options.onError,onFatalError:t=>{s()&&this.fail(t)},send:t=>{if(!s()||this.finishing||"open"!==m.readyState)throw Error("Realtime data channel is not open");if(m.bufferedAmount>1048576)throw Error("Realtime data channel buffer is full");let r="string"==typeof t?t:JSON.stringify(t);if(!s()||this.finishing||"open"!==m.readyState)throw Error("Realtime data channel is not open");m.send(r)}});if(!s())return void g.dispose();this.codec=g,m.onmessage=t=>{s()&&this.codec?.receive(t.data)},m.onclose=()=>{s()&&this.drainClose(Error("Realtime data channel closed"))},m.onerror=()=>{s()&&this.fail(Error("Realtime data channel error"))};let y=new Promise((t,r)=>{this.rejectStartup=r,m.onopen=()=>{this.rejectStartup=void 0,t()}});y.catch(()=>{});let v=new Promise(t=>{p.onicegatheringstatechange=()=>{"complete"===p.iceGatheringState&&t()}});if(this.sender=null!=o&&null!=c?p.addTrack(c,o):p.addTransceiver("audio",{direction:"sendrecv"}).sender,this.observeCapture(),!s()||u.signal.aborted)return;let b=await p.createOffer();if(!s()||u.signal.aborted||(await p.setLocalDescription(b),"complete"!==p.iceGatheringState&&await Promise.race([v,d]),!s()||u.signal.aborted))return;let w=p.localDescription?.sdp;if(null==w)throw Error("Realtime offer has no SDP");let _=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:w,sessionConfig:r}),signal:u.signal});if(!_.ok)throw Error(`Failed to create realtime session: ${_.status}`);let k=await sW({text:await pX(_)});if(s()&&!u.signal.aborted){if(!k.success||"object"!=typeof k.value||null==k.value||!("sdp"in k.value)||"string"!=typeof k.value.sdp||0===k.value.sdp.trim().length||!("sessionId"in k.value)||"string"!=typeof k.value.sessionId||0===k.value.sessionId.trim().length)throw Error("Invalid realtime session answer");await p.setRemoteDescription({type:"answer",sdp:k.value.sdp}),await Promise.race([y,d])}};try{await Promise.race([p(),d])}catch(t){throw s()&&this.dispose(),t}finally{clearTimeout(c),this.rejectStartup=void 0}}sendEvent(t,r){if(this.finishing||this.dc?.readyState!=="open")throw Error("Realtime data channel is not open");return this.codec?.send(t,r)??Promise.resolve()}async resumePlayback(){if(null==this.audio)throw Error("Realtime playback is not connected");await this.audio.play()}stopPlayback(){this.audio?.pause()}finish(){return this.codec?.finish()??Promise.resolve()}fail(t){if("failure"===this.finishing)return;if(this.finishing="failure",clearTimeout(this.finishTimer),null!=this.rejectStartup){this.rejectStartup(t),this.abort?.abort(t);return}let r=this.generation,a=this.finish();if(this.notifyClosing(),r!==this.generation||(this.stopCaptureForShutdown(r),r!==this.generation))return;if(null!=this.options.onFatalError)return void this.options.onFatalError(t,a);let n=()=>{if(r===this.generation){this.dispose();try{this.options.onClose()}catch(t){this.reportCallbackError(t)}}};this.finishTimer=setTimeout(n,1e3),this.awaitDrain(a,n);try{this.options.onError(t)}catch{}}drainClose(t){if(this.finishing)return;if(null!=this.rejectStartup)return void this.fail(t);this.finishing="close";let r=this.generation,a=()=>{if(r===this.generation&&"close"===this.finishing){clearTimeout(this.finishTimer);try{this.options.onClose(t)}catch(t){this.reportCallbackError(t)}finally{r===this.generation&&this.dispose()}}};this.finishTimer=setTimeout(a,1e3),this.awaitDrain(this.finish(),a),this.notifyClosing(),r===this.generation&&this.stopCaptureForShutdown(r)}notifyClosing(){if(!this.closingNotified){this.closingNotified=!0;try{this.options.onClosing?.()}catch(t){this.reportCallbackError(t)}}}async stopCaptureForShutdown(t){try{await this.stopCapture()}catch(r){if(t!==this.generation||"close"!==this.finishing)return;try{this.fail(r instanceof Error?r:Error(String(r)))}catch(t){this.reportCallbackError(t)}}}async awaitDrain(t,r){try{await t}catch{}try{r()}catch(t){this.reportCallbackError(t)}}reportCallbackError(t){try{this.options.onError(t instanceof Error?t:Error(String(t)))}catch{}}async stopCapture(){let t=++this.captureGeneration;for(let t of this.trackCleanups)t();this.trackCleanups=[],this.ownsStream&&this.stream?.getTracks().forEac
91h(t=>t.stop()),this.stream=void 0;let r=this.pc,a=this.sender;await this.queueSenderOperation(async()=>{r===this.pc&&a===this.sender&&(null!=r&&null!=a&&await this.detachSender(r,a),t===this.captureGeneration&&r===this.pc&&this.options.onCapturing(!1))})}async startCapture(t){let r=this.captureGeneration+1;if(await this.stopCapture(),r!==this.captureGeneration||null==this.pc||this.finishing)return;let a=t??await navigator.mediaDevices.getUserMedia({audio:!0});if(r!==this.captureGeneration||null==this.pc||this.finishing){null==t&&a.getTracks().forEach(t=>t.stop());return}let n=pQ(a);if(null==n)throw null==t&&a.getTracks().forEach(t=>t.stop()),Error("Realtime requires a live audio track");let i=this.pc,o=this.sender;await this.queueSenderOperation(async()=>{let s=()=>r===this.captureGeneration&&i===this.pc&&o===this.sender&&"closed"!==i.connectionState&&!this.finishing,l=!1;try{if(!s()||null==o)return;if(await o.replaceTrack(n),!s()){i===this.pc&&await this.detachSender(i,o);return}this.stream=a,this.ownsStream=null==t,l=!0,this.observeCapture()}finally{l||null!=t||a.getTracks().forEach(t=>t.stop())}})}queueSenderOperation(t){let r=this.senderOperations.then(t);return this.senderOperations=r.catch(()=>{}),r}async detachSender(t,r){if("closed"!==t.connectionState)try{await r.replaceTrack(null)}catch(r){if(t!==this.pc)return;this.closePeer(t),this.fail(r instanceof Error?r:Error(String(r)))}}closePeer(t){t.ontrack=null,t.onconnectionstatechange=null,t.oniceconnectionstatechange=null,t.onicegatheringstatechange=null,"closed"!==t.connectionState&&t.close()}observeCapture(){let t=this.captureGeneration,r=this.sender,a=r?.track,n=()=>{t===this.captureGeneration&&this.sender===r&&this.options.onCapturing(r?.track!=null&&"live"===r.track.readyState&&r.track.enabled&&!r.track.muted)};if(null!=a)for(let t of["ended","mute","unmute"])a.addEventListener(t,n),this.trackCleanups.push(()=>a.removeEventListener(t,n));n()}dispose(){for(let t of(this.generation++,this.captureGeneration++,clearTimeout(this.finishTimer),clearTimeout(this.disconnectTimer),this.finishing=void 0,this.closingNotified=!1,this.senderOperations=Promise.resolve(),this.abort?.abort(Error("Realtime connection cancelled")),this.abort=void 0,this.codec?.dispose(),this.codec=void 0,null!=this.dc&&(this.dc.onopen=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.onmessage=null,this.dc.close(),this.dc=void 0),null!=this.pc&&(this.closePeer(this.pc),this.pc=void 0),this.trackCleanups))t();this.trackCleanups=[],this.ownsStream&&this.stream?.getTracks().forEach(t=>t.stop()),this.stream=void 0,this.sender=void 0,null!=this.audio&&(this.audio.onplaying=null,this.audio.onpause=null,this.audio.onended=null,this.audio.onwaiting=null,this.audio.pause(),this.audio.srcObject=null,this.audio=void 0),this.options.onCapturing(!1),this.options.onPlaying(!1)}},p1=class{constructor(){this.abort=new AbortController,this.timers=new Map,this.active=!0,this.ready=!1,this.closing=!1,this.transportClosing=!1}timer(t,r,a){this.clearTimer(t),this.timers.set(t,setTimeout(()=>{this.timers.delete(t),this.active&&a()},r))}clearTimer(t){clearTimeout(this.timers.get(t)),this.timers.delete(t)}beginClose(){return this.closing=!0,this.closePromise??=new Promise(t=>{this.settleClose=t})}retire(){if(this.active){for(let t of(this.active=!1,this.abort.abort(),this.timers.values()))clearTimeout(t);this.timers.clear(),this.settleClose?.(),this.settleClose=void 0}}},p2=class{constructor(t){this.sendCommand=t,this.pending=new Map,this.recent=new Set}validateId(t){if(this.pending.has(t)||this.recent.has(t))throw Error("Realtime command ID was already used; retry with a fresh eventId");if(this.pending.size>=512)throw Error("Too many pending realtime commands")}complete(t){let r=this.pending.get(t);if(null!=r){if(this.pending.delete(t),this.recent.add(t),this.recent.size>4096){let t=this.recent.values().next().value;null!=t&&this.recent.delete(t)}return r}}send(t){let r="input-audio-mute"===t.type||"input-audio-unmute"!==t.type&&void 0;("input-audio-mute"===t.type||"input-audio-unmute"===t.type)&&(t={...t,eventId:t.eventId??sr()});let a="eventId"in t?t.eventId:void 0;null!=a&&(this.validateId(a),this.pending.set(a,{muted:r}));let n="context-append"===t.type||"session-update"===t.type||null!=r;try{let r=this.sendCommand(t);return r.then(()=>{null==a||n||this.complete(a)},()=>{null!=a&&this.complete(a)}),r}catch(t){throw null!=a&&this.complete(a),t}}receive(t){if("command-acknowledged"===t.type&&null!=t.clientEventId)return this.complete(t.clientEventId);"error"===t.type&&null!=t.clientEventId&&this.complete(t.clientEventId)}},p4=us({token:lM().refine(t=>t.trim().length>0),url:lM().refine(t=>{try{let r=new URL(t);return("ws:"===r.protocol||"wss:"===r.protocol)&&""!==r.hostname}catch{return!1}}),expiresAt:l4().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:d3(us({type:uv("function"),name:lM().min(1),description:lM().optional(),parameters:uf(lM(),ut())})).optional()});function p6(){return{transcripts:[],delegations:[],isInputMuted:!1,finalization:"pending"}}var p5=class{constructor(t=500){this.maxEvents=t,this.currentAssistantMessageId=null,this.textAccumulators=new Map,this.toolArgAccumulators=new Map,this.toolCallIdToMessageId=new Map,this.toolCallIdToName=new Map,this.inputAudioMessageInsertIndex=new Map,this.itemIdToPartLocation=new Map}setStatus(t,r){return{...t,status:r}}setCapturing(t,r){return{...t,isCapturing:r}}setPlaying(t,r){return{...t,isPlaying:r}}addUserTextMessage(t,r){return{...t,messages:[...t.messages,{id:`user-${Date.now()}`,role:"user",parts:[{type:"text",text:r,state:"done"}]}]}}addToolOutput(t,r,a){return{state:this.updateToolPartState(t,r,a),output:{callId:r,name:this.toolCallIdToName.get(r),output:JSON.stringify(a)}}}async reduceServerEvent(t,r){let a=this.pushEvent(t,r),n=[];switch(r.type){case"session-created":case"session-updated":"connecting"===a.status&&(a=this.setStatus(a,"connected"));break;case"audio-delta":n.push({type:"play-audio",itemId:r.itemId,delta:r.delta});break;case"audio-committed":null!=r.itemId&&this.inputAudioMessageInsertIndex.set(r.itemId,a.messages.length);break;case"audio-transcript-delta":case"text-delta":a=this.appendTextDelta(a,r.itemId,r.delta);break;case"audio-transcript-done":a=this.finalizeText(a,r.itemId,r.transcript);break;case"text-done":a=this.finalizeText(a,r.itemId,r.text);break;case"input-transcription-completed":a=this.addInputTranscriptionMessage(a,r.itemId,r.transcript);break;case"response-created":case"response-done":this.currentAssistantMessageId=null;break;case"speech-started":this.currentAssistantMessageId=null,n.push({type:"speech-started"});break;case"function-call-arguments-delta":{let{state:t,messageId:n}
91=this.getOrCreateAssistantMessage(a);a=t,this.toolCallIdToMessageId.set(r.callId,n);let i=this.toolArgAccumulators.get(r.callId)??"";this.toolArgAccumulators.set(r.callId,i+r.delta),a=this.ensureToolPart(a,n,r.callId);break}case"function-call-arguments-done":{this.toolArgAccumulators.delete(r.callId),this.toolCallIdToName.set(r.callId,r.name);let t=await sW({text:r.arguments}),i=t.success?t.value:{},o=this.toolCallIdToMessageId.get(r.callId);null!=o&&(a=this.markToolInputAvailable(a,o,r.callId,r.name,i)),t.success?n.push({type:"tool-call",callId:r.callId,name:r.name,args:i,rawArguments:r.arguments}):n.push({type:"error",error:Error(`Failed to parse tool arguments: ${r.arguments}`)});break}case"error":n.push({type:"error",error:Error(r.message)})}return{state:a,effects:n}}pushEvent(t,r){let a=[...t.events,r];return{...t,events:a.length>this.maxEvents?a.slice(-this.maxEvents):a}}getOrCreateAssistantMessage(t){if(null!=this.currentAssistantMessageId)return{state:t,messageId:this.currentAssistantMessageId};let r=`assistant-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;return this.currentAssistantMessageId=r,{state:{...t,messages:[...t.messages,{id:r,role:"assistant",parts:[]}]},messageId:r}}addInputTranscriptionMessage(t,r,a){let n=`user-${r}`;if(null!=t.messages.find(t=>t.id===n))return{...t,messages:t.messages.map(t=>t.id===n?{...t,parts:[{type:"text",text:a,state:"done"}]}:t)};let i=Math.min(this.inputAudioMessageInsertIndex.get(r)??t.messages.length,t.messages.length),o=[...t.messages];return o.splice(i,0,{id:n,role:"user",parts:[{type:"text",text:a,state:"done"}]}),{...t,messages:o}}appendTextDelta(t,r,a){let{state:n,messageId:i}=this.getOrCreateAssistantMessage(t),o=(this.textAccumulators.get(r)??"")+a;this.textAccumulators.set(r,o);let s=this.itemIdToPartLocation.get(r);return null!=s?this.updateMessagePart(n,s.messageId,s.partIndex,{type:"text",text:o,state:"streaming"}):{...n,messages:n.messages.map(t=>{if(t.id!==i)return t;let a=t.parts.length;return this.itemIdToPartLocation.set(r,{messageId:i,partIndex:a}),{...t,parts:[...t.parts,{type:"text",text:o,state:"streaming"}]}})}}finalizeText(t,r,a){let n=a??this.textAccumulators.get(r)??"";this.textAccumulators.delete(r);let i=this.itemIdToPartLocation.get(r);return null==i?t:(this.itemIdToPartLocation.delete(r),this.updateMessagePart(t,i.messageId,i.partIndex,{type:"text",text:n,state:"done"}))}ensureToolPart(t,r,a){return{...t,messages:t.messages.map(t=>t.id!==r||null!=t.parts.find(t=>"dynamic-tool"===t.type&&t.toolCallId===a)?t:{...t,parts:[...t.parts,{type:"dynamic-tool",toolName:"",toolCallId:a,state:"input-streaming",input:void 0}]})}}markToolInputAvailable(t,r,a,n,i){return{...t,messages:t.messages.map(t=>t.id!==r?t:{...t,parts:t.parts.map(t=>"dynamic-tool"!==t.type||t.toolCallId!==a?t:{...t,toolName:n,state:"input-available",input:i})})}}updateToolPartState(t,r,a){let n=this.toolCallIdToMessageId.get(r);return null==n?t:{...t,messages:t.messages.map(t=>t.id!==n?t:{...t,parts:t.parts.map(t=>"dynamic-tool"!==t.type||t.toolCallId!==r?t:{...t,state:"output-available",output:a})})}}updateMessagePart(t,r,a,n){return{...t,messages:t.messages.map(t=>{if(t.id!==r)return t;let i=[...t.parts];return i[a]=n,{...t,parts:i}})}}},p9=class{constructor(t){this.options=t,this.state={status:"disconnected",messages:[],events:[],isCapturing:!1,isPlaying:!1},this.publication=0,this.captureGeneration=0,this.captureRequested=!1,this.currentResponseItemId=null,this.toolCallsInResponse=new Set,this.submittedToolOutputs=new Set,this.responseToolCallsClosed=!1;const r=t.model.capabilities;if(this.sessionLifecycle=r?.startup==="session-start"||r?.finalization==="session-close",this.continuous=r?.conversation==="continuous",this.maxEvents=t.maxEvents??500,!Number.isSafeInteger(this.maxEvents)||this.maxEvents<1)throw Error("maxEvents must be a positive integer");for(const r of[t.startupTimeoutMs??3e4,t.closeTimeoutMs??15e3,t.rtcDisconnectTimeoutMs??5e3])if(!Number.isFinite(r)||r<=0||r>0x7fffffff)throw Error("Realtime timeouts must be positive finite timer durations");const a=t.maxPlaybackBufferSeconds??2;if(!Number.isFinite(a)||a<=0)throw Error("maxPlaybackBufferSeconds must be positive and finite");this.reducer=new p5(this.maxEvents),this.onToolCall=t.onToolCall,this.onEvent=t.onEvent,this.onError=t.onError}validateConnection(){let{model:t,api:r}=this.options;if((!this.continuous||null!=r.session)&&null!=this.options.maxPlaybackBufferSeconds)throw Error("maxPlaybackBufferSeconds
91is supported only for continuous PCM sessions");let a=null!=r.session?"webrtc":null!=r.token?"client-secret-websocket":"server-websocket";if(!(t.capabilities?.connections??["client-secret-websocket"]).includes(a)||t.capabilities?.transports!=null&&!t.capabilities.transports.includes(null!=r.session?"webrtc":"websocket"))throw Error(`Realtime model does not support ${a}`);if(null!=r.session){if(null==t.getWebRTCConfig)throw Error("Realtime model does not support WebRTC configuration");return}if(this.continuous&&null==r.websocket)throw Error("Continuous PCM sessions require an application WebSocket relay");if(null!=r.token&&null==t.getWebSocketConfig)throw Error("Realtime model does not support client-secret WebSocket configuration")}async connect(t){if(this.attempt?.active)throw Error("Realtime session is already active");let r=new p1;this.attempt=r;let a=()=>this.attempt===r&&r.active;try{if(this.applyState({...this.state,status:"connecting"}),!a())return;this.validateConnection();let{model:n,api:i,sessionConfig:o}=this.options;if(t?.capture===!1&&this.stopAudioCapture(),!a()||(t?.stream!=null&&t.stream!==this.suppliedStream&&(!this.captureRequested||this.sessionLifecycle||this.continuous||null!=i.session?this.suppliedStream=t.stream:this.startAudioCapture(t.stream)),!a())||(this.reducer=new p5(this.maxEvents),this.currentResponseItemId=null,this.toolCallsInResponse.clear(),this.submittedToolOutputs.clear(),this.responseToolCallsClosed=!1,this.sessionLifecycle&&this.applyState({...this.state,session:p6()}),!a()))return;this.commands=new p2(t=>{let n=()=>a()&&!r.transportClosing&&null==r.cause&&(!r.closing||"session-close"===t.type);if(!n())throw Error("Realtime connection is closed");return this.sendTransport(t,n)}),r.timer("startup",this.options.startupTimeoutMs??3e4,()=>{a()&&this.fail(Error("Realtime session startup timed out"))});let s=new WeakSet,l={model:n,onEvent:async t=>{if(a())try{await this.handleServerEvent(t,r)}catch(t){a()&&this.fail(t,(this.rtc??this.pcm??this.transport)?.finish())}},onError:t=>{a()&&(s.add(t),this.reportError(t,r))},onFatalError:(t,r)=>{a()&&this.fail(t,r)},onClosing:()=>{!a()||(r.beginClose(),r.transportClosing=!0,r.clearTimer("startup"),r.clearTimer("close"),this.stopAudioCapture(),a()&&this.applyState({...this.state,status:null==r.cause?"closing":"error"}))},onClose:t=>{if(!a())return;let i=n.capabilities?.finalization==="session-close"&&this.state.session?.finalization==="confirmed";null==t||i?r.ready||i?this.disconnect():this.fail(Error("Realtime connection closed before becoming ready")):this.fail(t,void 0,!s.has(t))},onCapturing:t=>{a()&&this.applyState({...this.state,isCapturing:t})},onPlaying:t=>{a()&&this.applyState({...this.state,isPlaying:t})}};if(null!=i.session)this.rtc=new p0({...l,disconnectTimeoutMs:this.options.rtcDisconnectTimeoutMs}),await this.rtc.connect({api:i.session,sessionConfig:o,stream:t?.stream,capture:t?.capture,timeoutMs:this.options.startupTimeoutMs??3e4});else if(null!=i.websocket&&n.capabilities?.conversation==="continuous")this.pcm=new pY({...l,sessionConfig:o,sampleRate:this.options.sampleRate,maxPlaybackBufferSeconds:this.options.maxPlaybackBufferSeconds}),this.pcm.connect({url:i.websocket,protocols:i.protocols,stream:t?.stream,capture:t?.capture});else{let t;this.ensureAudio();let s=o??{},u=i.websocket;if(null!=i.token){let n=await fetch(i.token,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionConfig:o}),signal:r.abort.signal});if(!a())return;if(!n.ok)throw Error(`Failed to fetch realtime setup: ${n.status}`);let l=await n.json().catch(()=>{throw Error("Invalid realtime setup response")});if(!a()||r.closing)return;let c=function(t){let r=p4.safeParse(t);if(!r.success)throw Error("Invalid realtime setup: expected a nonempty token, a ws(s) URL, and valid optional expiresAt/tools");return r.data}(l);t=c.token,u=c.url,s={...o,...null==c.tools?{}:{tools:c.tools}}}if(null==u)throw Error("Realtime WebSocket URL is missing");if(null!=i.token&&null==t)throw Error("Realtime client-secret connection requires a token");if(this.ensureAudio().ensurePlaybackContext(),!a())return;this.transport=new pK({...l,onServerEvent:l.onEvent}),this.transport.connect({...null!=t?{mode:"client-secret",token:t}:{mode:"relay",protocols:i.protocols},url:u,onOpen:()=>{let t=()=>a()&&!r.closing&&null==r.cause;if(t())return this.sendTransport({type:n.capabilities?.startup??"session-update",config:s},t)}})}}catch(t){a()&&this.fail(t)}}fail(t,r,a=!0){let n=this.attempt;null==n||!n.active||null!=n.cause||(n.cause=t instanceof Error?t:Error(String(t)),null!=r&&n.beginClose(),this.applyState({...this.state,status:"error"}),this.attempt!==n||!n.active||(this.stopAudioCapture(),this.attempt===n&&n.active&&(null==r?this.disconnect():this.drainAttempt(n,r),a&&this.reportError(n.cause,n))))}async drainAttempt(t,r){this.attempt===t&&t.active&&t.timer("drain",1e3,()=>this.finishAttempt(t));try{await r}catch{}this.finishAttempt(t)}finishAttempt(t){if(this.attempt===t&&t.active)try{this.disconnect()}catch(r){this.reportError(r,t)}}closeFailed(t,r){if(this.attempt!==t||!t.active||t.transportClosing)return;t.clearTimer("close");let a=this.rtc??this.pcm??this.transport;this.drainAttempt(t,a?.finish()),this.reportError(r,t)}disconnect(){let t=this.attempt;this.captureGeneration++,this.captureRequested=!1,this.suppliedStream
91=void 0;let r=this.transport,a=this.audio,n=this.pcm,i=this.rtc;if(this.transport=void 0,this.audio=void 0,this.pcm=void 0,this.rtc=void 0,this.commands=void 0,t?.retire(),r?.dispose(),a?.dispose(),n?.dispose(),i?.dispose(),this.attempt!==t)return;let o=this.state.session;this.applyState({...this.state,status:t?.cause!=null?"error":"disconnected",isCapturing:!1,isPlaying:!1,...null!=o?{session:"confirmed"===o.finalization?o:{...o,finalization:"unconfirmed"}}:{}})}close(t){let r=this.attempt;if(r?.closePromise!=null)return r.closePromise;if("connected"!==this.state.status||this.options.model.capabilities?.finalization!=="session-close"||null==r)return this.disconnect(),Promise.resolve();t?.eventId!=null&&this.commands?.validateId(t.eventId);let a=r.beginClose();if(this.applyState({...this.state,status:"closing"}),this.attempt!==r||!r.active||r.transportClosing||(this.stopAudioCapture(),this.attempt!==r||!r.active||r.transportClosing))return a;r.timer("close",this.options.closeTimeoutMs??15e3,()=>this.finishAttempt(r));let n=t=>this.closeFailed(r,t);try{this.commands?.send({type:"session-close",eventId:t?.eventId}).catch(n)}catch(t){n(t)}return a}sendTransport(t,r,a=!1){let n=this.rtc??this.pcm??this.transport;if(null==n)throw Error("Realtime connection is not open");return n===this.transport?this.transport.sendEvent(t,r,a):n.sendEvent(t,r)}sendEvent(t){if("error"===this.state.status||"closing"===this.state.status||this.attempt?.closing||!this.attempt?.active||this.sessionLifecycle&&"connected"!==this.state.status)throw Error("Realtime session is not accepting submissions");if(null!=this.rtc&&"input-audio-append"===t.type||(this.continuous||null!=this.rtc)&&("input-audio-commit"===t.type||"input-audio-clear"===t.type))throw new eJ({functionality:"JSON audio commands unsupported for this session transport"});if("session-close"===t.type)return this.close({eventId:t.eventId});if("session-start"===t.type&&this.sessionLifecycle)throw Error("Realtime session has already started");if(!this.sessionLifecycle&&null==this.state.session){let r=this.attempt;return this.sendTransport(t,()=>this.attempt===r&&r.active&&!r.closing&&null==r.cause)}return this.commands?.send(t)??this.sendTransport(t)}sendTextMessage(t){if(this.continuous)throw new eJ({functionality:"sendTextMessage for continuous sessions; client-delegation text is application-owned, use context-append for context"});this.sendEvent({type:"conversation-item-create",item:{type:"text-message",role:"user",text:t}}),this.sendEvent({type:"response-create"}),this.applyState(this.reducer.addUserTextMessage(this.state,t))}sendAudio(t){let r=this.attempt;this.sendEvent({type:"input-audio-append",audio:t}).catch(t=>{r?.active&&this.attempt===r&&this.reportError(t,r)})}commitAudio(){this.sendEvent({type:"input-audio-commit"})}clearAudioBuffer(){this.sendEvent({type:"input-audio-clear"})}requestResponse(t){this.sendEvent({type:"response-create",...null!=t?{options:t}:{}})}cancelResponse(){this.sendEvent({type:"response-cancel"})}sendAutomaticAudio(t){if("connected"!==this.state.status||!this.attempt?.active||this.attempt.closing)return;let r=this.attempt,a=t=>{r?.active&&this.attempt===r&&!r.closing&&this.fail(t)};try{this.sendTransport({type:"input-audio-append",audio:t},()=>this.attempt===r&&r.active&&!r.closing,!0).catch(a)}catch(t){a(t)}}addToolOutput(t,r){if(this.continuous)throw new eJ({functionality:"addToolOutput for continuous sessions; client delegation is application-owned"});let a=this.attempt;if(!a?.active||a.closing||null!=a.cause)throw Error("Realtime session is not accepting submissions");let{state:n,output:i}=this.reducer.addToolOutput(this.state,t,r);this.applyState(n),this.attempt===a&&a?.active&&(this.sendEvent({type:"conversation-item-create",item:{type:"function-call-output",...i}}),this.submittedToolOutputs.add(t),this.maybeRequestToolResponse())}maybeRequestToolResponse(){"connected"!==this.state.status||this.attempt?.closing||!this.responseToolCallsClosed||0===this.toolCallsInResponse.size||[...this.toolCallsInResponse].some(t=>!this.submittedToolOutputs.has(t))||(this.sendEvent({type:"response-create"}),this.toolCallsInResponse.clear(),this.submittedToolOutputs.clear(),this.responseToolCallsClosed=!1)}startAudioCapture(t){let r=!this.sessionLifecycle&&!this.continuous&&null==this.options.api.session;if(!r&&"connected"!==this.state.status||this.attempt?.active&&(this.attempt.closing||null!=this.attempt.cause))throw Error("Realtime session is not accepting capture");
91if(this.suppliedStream=t,r){this.captureGeneration++,this.captureRequested=!0,this.ensureAudio().startCapture(t);return}let a=this.attempt;this.resumeAudioCapture().catch(t=>{a?.active&&this.reportError(t,a)})}async resumeAudioCapture(){let t=()=>!this.attempt?.closing&&this.attempt?.cause==null&&("connected"===this.state.status||!this.sessionLifecycle&&"connecting"===this.state.status);if(!t())throw Error("Realtime session is not accepting capture");if(this.captureRequested=!0,null!=this.rtc)return this.rtc.startCapture(this.suppliedStream);if(null!=this.pcm)return this.pcm.resumeCapture(this.suppliedStream);let r=this.audio;if(null==r)throw Error("Realtime capture transport is not ready");let a=++this.captureGeneration,n=this.attempt,i=this.suppliedStream,o=i??await navigator.mediaDevices.getUserMedia({audio:!0});if(!n?.active||this.attempt!==n||this.audio!==r||!t()||a!==this.captureGeneration){null==i&&o.getTracks().forEach(t=>t.stop());return}r.startCapture(o,{ownsStream:null==i||!this.sessionLifecycle||null!=this.options.api.token})}stopAudioCapture(){this.captureGeneration++,this.captureRequested=!1,null==this.audio||this.sessionLifecycle&&null==this.options.api.token||(this.suppliedStream=void 0);let t=this.pcm,r=this.audio,a=this.rtc,n=this.attempt;null!=a&&a.stopCapture().catch(t=>{n?.active&&this.attempt===n&&this.reportError(t,n)}),t?.stopCapture(),r?.stopCapture()}stopPlayback(){(this.rtc??this.pcm??this.audio)?.stopPlayback()}async resumePlayback(){await (this.rtc??this.pcm??this.audio)?.resumePlayback()}dispose(){this.disconnect()}ensureAudio(){if(null!=this.audio)return this.audio;let{sessionConfig:t,sampleRate:r}=this.options,a=new pG({captureSampleRate:t?.inputAudioFormat?.rate??r??24e3,playbackSampleRate:t?.outputAudioFormat?.rate??r??24e3,onAudio:t=>{this.audio===a&&this.sendAutomaticAudio(t)},onError:t=>{this.audio===a&&this.reportError(t,this.attempt)},onCapturingChange:t=>{this.audio===a&&this.applyState({...this.state,isCapturing:t})},onPlayingChange:t=>{this.audio===a&&this.applyState({...this.state,isPlaying:t})}});return this.audio=a,a}applyState(t){let r=++this.publication,a=this.state;this.state=t;let n=n=>{r===this.publication&&a[n]!==t[n]&&this.setState(n,t[n])};n("status"),n("messages"),n("events"),n("isCapturing"),n("isPlaying"),n("session")}async executeTool(t,r,a,n){if(!this.continuous&&this.attempt===n&&n.active&&!n.closing&&null==n.cause)try{if(null==this.onToolCall)return void this.reportError(Error(`No handler provided for tool "${r}"`),n);let i=await this.onToolCall({toolCall:{toolCallId:t,toolName:r,args:a}});void 0!==i&&this.attempt===n&&n?.active&&"connected"===this.state.status&&this.addToolOutput(t,i)}catch(t){n.active&&this.reportError(t,n)}}async handleServerEvent(t,r){let a=()=>this.attempt===r&&r.active;if(!a())return;if("session-started"===t.type&&"provider"===t.delegationMode)throw new eJ({functionality:"Provider delegation mode; this realtime runtime supports client delegation only"});if(this.continuous&&"audio-delta"===t.type)throw new eJ({functionality:"Turn-based audio-delta in a continuous PCM session; use audio-chunk"});let n=this.commands?.receive(t),i=await this.reducer.reduceServerEvent(this.state,t);if(!a())return;let o=this.state.session??("session-started"===t.type?p6():void 0);if(this.applyState({...i.state,status:this.state.status,...null==o?{}:{session:function(t,r,a,n){switch(r.type){case"session-started":return{...t,sessionId:r.sessionId,delegationMode:r.delegationMode};case"session-usage":return{...t,usage:r.usage};case"session-closed":return{...t,sessionId:r.sessionId??t.sessionId,usage:r.usage,terminationReason:r.reason,finalization:"confirmed"};case"transcript-fragment":return{...t,transcripts:[...t.transcripts,r].slice(-a)};case"delegation-created":return t.delegations.some(t=>t.delegationId===r.delegationId)?t:{...t,delegations:[...t.delegations,r].slice(-a)};case"command-acknowledged":return null==n?t:{...t,isInputMuted:n};default:return t}}(o,t,this.maxEvents,n?.muted)}}),a()){for(let t of i.effects)if(this.handleReducerEffect(t,r),!a())return;if(("audio-chunk"===t.type&&(this.pcm??this.audio)?.playAudio(t.delta),a())&&("response-done"===t.type&&this.toolCallsInResponse.size>0&&(this.responseToolCallsClosed=!0,this.maybeRequestToolResponse()),a())){if("session-closed"===t.type&&null!=o){this.disconnect(),this.notifyEvent(t,r,!0);return}if(("session-started"===t.type||"session-created"===t.type||"session-updated"===t.type)&&r.active&&!r.closing&&null==r.cause&&(this.options.model.capabilities?.startup==="session-start"?"session-started"===t.type:"session-started"!==t.type)){if(r.ready=!0,r.clearTimer("startup"),this.applyState({...this.state,status:"connected"}),!a()||r.closing)return;this.pcm?.startCapture()}a()&&this.notifyEvent(t,r)}}}handleReducerEffect(t,r){switch(t.type){case"play-audio":this.currentResponseItemId=t.itemId,this.audio?.playAudio(t.delta);break;case"speech-started":if(!this.continuous&&this.state.isPlaying){let t=this.audio?.getPlaybackOffsetMs()??0,a=this.currentResponseItemId;if(this.audio?.stopPlayback(),this.attempt!==r||!r.active)return;null==a||r.closing||null!=r.cause||this.sendEvent({type:"conversation-item-truncate",itemId:a,contentIndex:0,audioEndMs:Math.round(t)})}break;case"tool-call":if(this.continuous)break;this.toolCallsInResponse.add(t.callId),this.executeTool(t.callId,t.name,t.args,r);break;case"error":this.reportError(t.error,r)}}async reportError(t,r){if(this.attempt===r)try{await this.onError?.(t instanceof Error?t:Error(String(t)))}catch{}}
91notifyEvent(t,r,a=!1){if(this.attempt!==r||!r.active&&!a)return;let n=t=>{(r.active||a)&&this.reportError(t,r)};try{Promise.resolve(this.onEvent?.(t)).catch(n)}catch(t){n(t)}}},p3=Symbol.for("vercel.ai.error.AI_NoSuchProviderError");async function p8({response:t,url:r,fallbackMessage:a}){let n=await t.text();return new ey({message:n||a,url:r,requestBodyValues:void 0,statusCode:t.status,responseBody:n})}async function p7({stream:t,onTextPart:r}){let a=t.pipeThrough(new TextDecoderStream).getReader();for(;;){let{done:t,value:n}=await a.read();if(t)break;await r(n)}}async function he({api:t,prompt:r,credentials:a,headers:n,body:i,streamProtocol:o="data",setCompletion:s,setLoading:l,setError:u,setAbortController:c,getAbortController:d,onFinish:p,onError:h,fetch:f=fetch}){let m=new AbortController,g=()=>null==d||d()===m;try{l(!0),u(void 0),c(m),s("");let d=await f(t,{method:"POST",body:JSON.stringify({prompt:r,...i}),credentials:a,headers:oq({"Content-Type":"application/json",...n},`ai-sdk/${d5}`,oj()),signal:m.signal}).catch(t=>{throw t});if(!d.ok)throw await p8({response:d,url:t,fallbackMessage:"Failed to fetch the chat response."});if(!d.body)throw new e_({message:"The response body is empty."});let h="";switch(o){case"text":await p7({stream:d.body,onTextPart:t=>{h+=t,g()&&s(h)}});break;case"data":await pZ({stream:sG({stream:d.body,schema:pN}).pipeThrough(new TransformStream({async transform(t){if(!t.success)throw t.error;let r=t.value;if("text-delta"===r.type)h+=r.delta,g()&&s(h);else if("error"===r.type)throw new d1({chunkType:"error",chunkId:"",message:r.errorText})}})),onError:t=>{throw t}});break;default:throw new dV({parameter:"streamProtocol",value:o,message:`Unknown stream protocol: ${o}`})}return p&&p(r,h),h}catch(t){if("AbortError"===t.name)return null;t instanceof Error&&h&&h(t),g()&&u(t)}finally{g()&&(c(null),l(!1))}}async function ht(t){if(null==t)return[];if(!globalThis.FileList||!(t instanceof globalThis.FileList))throw new eJ({functionality:"FileList",message:"FileList is not supported in the current environment"});return Promise.all(Array.from(t).map(async t=>{let{name:r,type:a}=t;return{type:"file",mediaType:a,filename:r,url:await new Promise((r,a)=>{let n=new FileReader;n.onload=t=>{r(t.target?.result)},n.onerror=t=>a(t),n.readAsDataURL(t)})}}))}st({prefix:"call",size:24}),pV();var hr=class{constructor({api:t="/api/chat",credentials:r,headers:a,body:n,fetch:i,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:s}){this.api=t,this.credentials=r,this.headers=a,this.body=n,this.fetch=i,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:t,...r}){let a=await s0(this.body),n=await s0(this.headers),i=await s0(this.credentials),o={...oB(n),...oB(r.headers)},s=await this.prepareSendMessagesRequest?.({api:this.api,id:r.chatId,messages:r.messages,body:{...a,...r.body},headers:o,credentials:i,requestMetadata:r.metadata,trigger:r.trigger,messageId:r.messageId}),l=s?.api??this.api,u=s?.headers!==void 0?oB(s.headers):o,c=s?.body!==void 0?s.body:{...a,...r.body,id:r.chatId,messages:r.messages,trigger:r.trigger,messageId:r.messageId},d=s?.credentials??i,p=this.fetch??globalThis.fetch,h=await p(l,{method:"POST",headers:{"content-type":"application/json",...u},body:JSON.stringify(c),credentials:d,signal:t});if(!h.ok)throw await p8({response:h,url:l,fallbackMessage:"Failed to fetch the chat response."});if(!h.body)throw new e_({message:"The response body is empty."});return this.processResponseStream(h.body)}async reconnectToStream(t){var r,a;let n,i=await s0(this.body),o=await s0(this.headers),s=await s0(this.credentials),l={...oB(o),...oB(t.headers)},u=await this.prepareReconnectToStreamRequest?.({api:this.api,id:t.chatId,body:{...i,...t.body},headers:l,credentials:s,requestMetadata:t.metadata}),c=u?.api??(r=this.api,a=`/${t.chatId}/stream`,-1===(n=r.search(/[?#]/))?`${r}${a}`:`${r.slice(0,n)}${a}${r.slice(n)}`),d=u?.headers!==void 0?oB(u.headers):l,p=u?.credentials??s,h=this.fetch??globalThis.fetch,f=await h(c,{method:"GET",headers:d,credentials:p,signal:t.abortSignal});if(204===f.status)return null;if(!f.ok)throw await p8({response:f,url:c,fallbackMessage:"Failed to fetch the chat response."});if(!f.body)throw new e_({message:"The response body is empty."});return this.processResponseStream(f.body)}},ha=class extends hr{constructor(t={}){super(t)}
91processResponseStream(t){return sG({stream:t,schema:pN}).pipeThrough(new TransformStream({async transform(t,r){if(!t.success)throw t.error;r.enqueue(t.value)}}))}},hn=class{constructor({generateId:t=sr,id:r=t(),transport:a=new ha,messageMetadataSchema:n,dataPartSchemas:i,state:o,onError:s,onToolCall:l,onFinish:u,onData:c,sendAutomaticallyWhen:d}){this.pendingMessagePreparations=new Set,this.activeResponse=void 0,this.activeResumeRequest=void 0,this.jobExecutor=new pW,this.sendMessage=async(t,r)=>{let a;if(null==t){let t=this.pendingApprovalMessageId;if(null==t){t=this.lastMessage?.id;for(let r=this.state.messages.length-1;r>=0;r--){let a=this.state.messages[r];if("assistant"===a.role&&a.parts.some(t=>pU(t)&&"approval-responded"===t.state)){t=a.id;break}}}let a=null!=t&&t===this.pendingApprovalMessageId?this.state.messages.findIndex(r=>r.id===t):-1;await this.makeRequestForToolApproval({messageId:t,messageIndex:a,...r});return}if("text"in t||"files"in t){let r,n=new AbortController;this.pendingMessagePreparations.add(n);try{r=Array.isArray(t.files)?t.files:await ht(t.files)}finally{this.pendingMessagePreparations.delete(n)}if(n.signal.aborted)return;a={parts:[...r,..."text"in t&&null!=t.text?[{type:"text",text:t.text}]:[]]}}else a=t;if(null!=t.messageId){let r=this.state.messages.findIndex(r=>
91r.id===t.messageId);if(-1===r)throw new dV({parameter:"message.messageId",value:t.messageId,message:`message with id ${t.messageId} not found`});if("user"!==this.state.messages[r].role)throw new dV({parameter:"message.messageId",value:t.messageId,message:`message with id ${t.messageId} is not a user message`});this.state.messages=this.state.messages.slice(0,r+1),this.state.replaceMessage(r,{id:t.messageId,...a,role:a.role??"user",metadata:t.metadata})}else this.state.pushMessage({...a,id:a.id??this.generateId(),role:a.role??"user",metadata:t.metadata});await this.makeRequest({trigger:"submit-message",messageId:t.messageId,...r})},this.regenerate=async({messageId:t,...r}={})=>{let a=null==t?this.state.messages.length-1:this.state.messages.findIndex(r=>r.id===t);if(-1===a)throw new dV({parameter:"messageId",value:t,message:`message ${t} not found`});this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[a].role?a:a+1),await this.makeRequest({trigger:"regenerate-message",messageId:t,...r})},this.resumeStream=async(t={})=>{await this.makeRequest({trigger:"resume-stream",...t})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolApprovalResponse=async({id:t,approved:r,reason:a,options:n})=>this.jobExecutor.run(async()=>{let i=this.state.messages,o=n=>pU(n)&&"approval-requested"===n.state&&n.approval.id===t?{...n,state:"approval-responded",approval:{...n.approval,id:t,approved:r,reason:a}}:n,s=i.findIndex(r=>r.parts.some(r=>pU(r)&&"approval-requested"===r.state&&r.approval.id===t));if(-1!==s){let t=i[s];this.state.replaceMessage(s,{...t,parts:t.parts.map(o)}),this.pendingApprovalMessageId=t.id}this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),"streaming"!==this.status&&"submitted"!==this.status&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(t=>{if(t){let t=-1===s?this.lastMessage?.id:i[s].id;this.makeRequestForToolApproval({messageId:t,messageIndex:s,...n})}})}),this.addToolOutput=async({state:t="output-available",toolCallId:r,output:a,errorText:n,options:i})=>this.jobExecutor.run(async()=>{let o=this.state.messages,s=o[o.length-1],l=i=>pU(i)&&i.toolCallId===r?{...i,state:t,output:a,errorText:n}:i;this.state.replaceMessage(o.length-1,{...s,parts:s.parts.map(l)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(l)),"streaming"!==this.status&&"submitted"!==this.status&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(t=>{t&&this.makeRequest({trigger:"submit-message",messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{for(let t of this.pendingMessagePreparations)t.abort();this.activeResumeRequest?.abortController.abort(),this.activeResponse?.abortController.abort()},this.id=r,this.transport=a,this.generateId=t,this.messageMetadataSchema=n,this.dataPartSchemas=i,this.state=o,this.onError=s,this.onToolCall=l,this.onFinish=u,this.onData=c,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:t,error:r}){this.status!==t&&(this.state.status=t,this.state.error=r)}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(t){this.state.messages=t}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let t=this.sendAutomaticallyWhen({messages:this.state.messages});return t&&"object"==typeof t&&"then"in t?await t:t}async makeRequestForToolApproval({messageId:t,messageIndex:r,...a}){let n=null!=t&&t===this.pendingApprovalMessageId;n&&(this.pendingApprovalMessageId=void 0),await this.makeRequest({trigger:"submit-message",messageId:t,...a}),n&&"error"===this.status&&null==this.pendingApprovalMessageId&&(this.pendingApprovalMessageId=this.state.messages[r]?.id??t)}async makeRequest({trigger:t,metadata:r,headers:a,body:n,messageId:i}){let o,s,l=new AbortController,u="resume-stream"===t?{abortController:l}:void 0;u&&(this.activeResumeRequest?.abortController.abort(),this.activeResumeRequest=u);let c=()=>null==u||this.activeResumeRequest===u,d=()=>{this.activeResumeRequest===u&&(this.activeResumeRequest=void 0)};
91if("resume-stream"===t)try{let t=await this.transport.reconnectToStream({chatId:this.id,abortSignal:l.signal,metadata:r,headers:a,body:n});if(l.signal.aborted||!c()){await t?.cancel().catch(()=>{}),c()&&this.setStatus({status:"ready"}),d();return}if(null==t){this.setStatus({status:"ready"}),d();return}o=t}catch(t){if(l.signal.aborted||"AbortError"===t.name){c()&&this.setStatus({status:"ready"}),d();return}if(!c())return;this.onError&&t instanceof Error&&this.onError(t),this.setStatus({status:"error",error:t}),d();return}this.setStatus({status:"submitted",error:void 0});let p=this.lastMessage,h="submit-message"===t&&null!=i?this.state.messages.findIndex(t=>t.id===i):this.state.messages.length-1,f=-1===h?p:this.state.messages[h],m=-1!==h&&h<this.state.messages.length-1&&f?.role==="assistant",g=!1,y=!1,v=!1;try{let u,d={state:function({lastMessage:t,messageId:r}){return{message:t?.role==="assistant"?t:{id:r,metadata:void 0,role:"assistant",parts:[]},activeTextParts:pj(),activeReasoningParts:pj(),partialToolCalls:pj()}}({lastMessage:"resume-stream"===t||"regenerate-message"===t?void 0:this.state.snapshot(f),messageId:this.generateId()}),abortController:l};s=d,d.abortController.signal.addEventListener("abort",()=>{g=!0}),this.activeResponse=d,u="resume-stream"===t?o:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:d.abortController.signal,metadata:r,headers:a,body:n,trigger:t,messageId:i});let p=t=>this.jobExecutor.run(()=>d.abortController.signal.aborted?Promise.resolve():t({state:d.state,write:({updateStatus:t=!0}={})=>{d.abortController.signal.aborted||(t&&this.setStatus({status:"streaming"}),m?this.state.replaceMessage(h,d.state.message):d.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,d.state.message):this.state.pushMessage(d.state.message))}}));if(await pZ({stream:function({stream:t,messageMetadataSchema:r,dataPartSchemas:a,runUpdateMessageJob:n,onError:i,onToolCall:o,onData:s}){return t.pipeThrough(new TransformStream({async transform(t,l){await n(async({state:n,write:u})=>{function c(){let t=n.message.parts,r=t.length-1;for(;r>=0&&"step-start"!==t[r].type;)r--;return t.slice(r+1)}function d(t){let r=c().filter(pU).find(r=>r.toolCallId===t);if(null==r){let a=n.message.parts;for(let n=a.length-1;n>=0;n--){let i=a[n];if(pU(i)&&i.toolCallId===t){r=i;break}}}if(null==r)throw new d1({chunkType:"tool-invocation",chunkId:t,message:`No tool invocation found for tool call ID "${t}".`});return r}function p(t,r){let a=r??c().find(r=>pD(r)&&r.toolCallId===t.toolCallId);if(null!=a){a.state=t.state,a.input=t.input,a.output=t.output,a.errorText=t.errorText,a.rawInput=t.rawInput,a.preliminary=t.preliminary,void 0!==t.title&&(a.title=t.title),void 0!==t.toolMetadata&&(a.toolMetadata=t.toolMetadata),a.providerExecuted=t.providerExecuted??a.providerExecuted;let r=t.providerMetadata;null!=r&&("output-available"===t.state||"output-error"===t.state?a.resultProviderMetadata=r:a.callProviderMetadata=r)}else n.message.parts.push({type:`tool-${t.toolName}`,toolCallId:t.toolCallId,state:t.state,title:t.title,...void 0!==t.toolMetadata?{toolMetadata:t.toolMetadata}:{},input:t.input,output:t.output,rawInput:t.rawInput,errorText:t.errorText,providerExecuted:t.providerExecuted,preliminary:t.preliminary,...null!=t.providerMetadata&&("output-available"===t.state||"output-error"===t.state)?{resultProviderMetadata:t.providerMetadata}:{},...null!=t.providerMetadata&&"output-available"!==t.state&&"output-error"!==t.state?{callProviderMetadata:t.providerMetadata}:{}})}function h(t,r){let a=r??c().find(r=>"dynamic-tool"===r.type&&r.toolCallId===t.toolCallId);if(null!=a){a.state=t.state,a.toolName=t.toolName,a.input=t.input,a.output=t.output,a.errorText=t.errorText,a.rawInput=t.rawInput??a.rawInput,a.preliminary=t.preliminary,void 0!==t.title&&(a.title=t.title),void 0!==t.toolMetadata&&(a.toolMetadata=t.toolMetadata),a.providerExecuted=t.providerExecuted??a.providerExecuted;let r=t.providerMetadata;null!=r&&("output-available"===t.state||"output-error"===t.state?a.resultProviderMetadata=r:a.callProviderMetadata=r)}else n.message.parts.push({type:"dynamic-tool",toolName:t.toolName,toolCallId:t.toolCallId,state:t.state,input:t.input,output:t.output,errorText:t.errorText,preliminary:t.preliminary,providerExecuted:t.providerExecuted,title:t.title,...void 0!==t.toolMetadata?{toolMetadata:t.toolMetadata}:{},...null!=t.providerMetadata&&("output-available"===t.state||"output-error"===t.state)?{resultProviderMetadata:t.providerMetadata}:{}
91,...null!=t.providerMetadata&&"output-available"!==t.state&&"output-error"!==t.state?{callProviderMetadata:t.providerMetadata}:{}})}async function f(t){if(null!=t){let a=null!=n.message.metadata?function t(r,a){if(void 0===r&&void 0===a)return;if(void 0===r)return a;if(void 0===a)return r;let n={...r};for(let i in a)if("__proto__"!==i&&"constructor"!==i&&"prototype"!==i&&Object.prototype.hasOwnProperty.call(a,i)){let o=a[i];if(void 0===o)continue;let s=i in r?r[i]:void 0,l=null!==o&&"object"==typeof o&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),u=null!=s&&"object"==typeof s&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);l&&u?n[i]=t(s,o):n[i]=o}return n}(n.message.metadata,t):t;null!=r&&await sq({value:a,schema:r,context:{field:"message.metadata",entityId:n.message.id}}),n.message.metadata=a}}switch(t.type){case"text-start":{let r={type:"text",text:"",providerMetadata:t.providerMetadata,state:"streaming"};n.activeTextParts[t.id]=r,n.message.parts.push(r),u();break}case"text-delta":{let r=n.activeTextParts[t.id];if(null==r)throw new d1({chunkType:"text-delta",chunkId:t.id,message:`Received text-delta for missing text part with ID "${t.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});r.text+=t.delta,r.providerMetadata=t.providerMetadata??r.providerMetadata,u();break}case"text-end":{let r=n.activeTextParts[t.id];if(null==r)throw new d1({chunkType:"text-end",chunkId:t.id,message:`Received text-end for missing text part with ID "${t.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});r.state="done",r.providerMetadata=t.providerMetadata??r.providerMetadata,delete n.activeTextParts[t.id],u();break}case"custom":{let r={type:"custom",kind:t.kind,providerMetadata:t.providerMetadata};n.message.parts.push(r),u();break}case"reasoning-start":{let r={type:"reasoning",id:t.id,text:"",providerMetadata:t.providerMetadata,state:"streaming"};n.activeReasoningParts[t.id]=r,n.message.parts.push(r),u();break}case"reasoning-delta":{let r=n.activeReasoningParts[t.id];if(null==r)throw new d1({chunkType:"reasoning-delta",chunkId:t.id,message:`Received reasoning-delta for missing reasoning part with ID "${t.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});r.text+=t.delta,r.providerMetadata=t.providerMetadata??r.providerMetadata,u();break}case"reasoning-end":{let r=n.activeReasoningParts[t.id];if(null==r)throw new d1({chunkType:"reasoning-end",chunkId:t.id,message:`Received reasoning-end for missing reasoning part with ID "${t.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});r.providerMetadata=t.providerMetadata??r.providerMetadata,r.state="done",delete n.activeReasoningParts[t.id],u();break}case"file":case"reasoning-file":n.message.parts.push({type:t.type,mediaType:t.mediaType,url:t.url,...null!=t.providerMetadata?{providerMetadata:t.providerMetadata}:{}}),u();break;case"source-url":n.message.parts.push({type:"source-url",sourceId:t.sourceId,url:t.url,title:t.title,providerMetadata:t.providerMetadata}),u();break;case"source-document":n.message.parts.push({type:"source-document",sourceId:t.sourceId,mediaType:t.mediaType,title:t.title,filename:t.filename,providerMetadata:t.providerMetadata}),u();break;case"tool-input-start":{let r=c().filter(pD);n.partialToolCalls[t.toolCallId]={text:"",toolName:t.toolName,index:r.length,dynamic:t.dynamic,title:t.title,toolMetadata:t.toolMetadata},t.dynamic?h({toolCallId:t.toolCallId,toolName:t.toolName,state:"input-streaming",input:void 0,providerExecuted:t.providerExecuted,title:t.title,toolMetadata:t.toolMetadata,providerMetadata:t.providerMetadata}):p({toolCallId:t.toolCallId,toolName:t.toolName,state:"input-streaming",input:void 0,providerExecuted:t.providerExecuted,title:t.title,toolMetadata:t.toolMetadata,providerMetadata:t.providerMetadata}),u();break}case"tool-input-delta":{let r=n.partialToolCalls[t.toolCallId];if(null==r)throw new d1({chunkType:"tool-input-delta",chunkId:t.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${t.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});r.text+=t.inputTextDelta;let{value:a}=await pT(r.text);r.dynamic?h({toolCallId:t.toolCallId,toolName:r.toolName,state:"input-streaming",input:a,title:r.title,toolMetadata:r.toolMetadata}):p({toolCallId:t.toolCallId,toolName:r.toolName,state:"input-streaming",input:a,title:r.title,toolMetadata:r.toolMetadata}),u();break}case"tool-input-available":t.dynamic?h({toolCallId:t.toolCallId,toolName:t.toolName,state:"input-available",input:t.input,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:t.toolCallId,toolName:t.toolName,state:"input-available",input:t.input,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:t.title,toolMetadata:t.toolMetadata}),u(),o&&!t.providerExecuted&&await o({toolCall:t});break;case"tool-input-error":{let r=c().filter(pU).find(r=>r.toolCallId===t.toolCallId);(null!=r?"dynamic-tool"===r.type:t.dynamic)?h({toolCallId:t.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:t.errorText,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,toolMetadata:t.toolMetadata}):(p({toolCallId:t.toolCallId,toolName:t.toolName,state:"output-error",input:void 0,rawInput:t.input,errorText:t.errorText,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,toolMetadata:t.toolMetadata}),[n.message].some(t=>t.parts.some(t=>null!=t&&"object"==typeof t&&"type"in t&&"string"==typeof t.type&&("dynamic-tool"===t.type||t.type.startsWith("tool-"))&&"state"in t&&"output-error"===t.state&&Object.prototype.hasOwnProperty.call(t,"rawInput")&&"rawInput"in t&&void 0!==t.rawInput))&&(t=>{if(0===t.warnings.length)return;let r=globalThis.AI_SDK_LOG_WARNINGS;if(!1!==r){if("function"==typeof r)return r(t);for(let r of(d4||(d4=!0,d6({message:"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",type:"Warning"}
91)),t.warnings))d6({message:function({warning:t,provider:r,model:a}){let n=null!=r&&null!=a?` (${r} / ${a})`:"",i=`AI SDK Warning${n}:`;switch(t.type){case"unsupported":{let r=`${i} The feature "${t.feature}" is not supported.`;return t.details&&(r+=` ${t.details}`),r}case"compatibility":{let r=`${i} The feature "${t.feature}" is used in a compatibility mode.`;return t.details&&(r+=` ${t.details}`),r}case"deprecated":return`${i} Deprecated: "${t.setting}". ${t.message}`;case"other":return`${i} ${t.message}`;default:return`${i} ${JSON.stringify(t,null,2)}`}}({warning:r,provider:t.provider,model:t.model}),type:"deprecated"===r.type?"DeprecationWarning":"Warning"})}})({warnings:[pF]})),u();break}case"tool-approval-request":{let r=d(t.toolCallId);r.state="approval-requested",r.approval={id:t.approvalId,...null!=t.approvalDescriptor?{descriptor:t.approvalDescriptor}:{},...Object.prototype.hasOwnProperty.call(t,"inputSchemaInput")?{inputSchemaInput:t.inputSchemaInput}:{},...null!=t.reason?{requestReason:t.reason}:{},...!0===t.isAutomatic?{isAutomatic:!0}:{},...null!=t.signature?{signature:t.signature}:{}},u();break}case"tool-approval-response":{let r=function(t){let r=n.message.parts.filter(pU).find(r=>r.approval?.id===t);if(null==r)throw new d1({chunkType:"tool-approval-response",chunkId:t,message:`No tool invocation found for approval ID "${t}".`});return r}(t.approvalId),a=null==r.approval?{id:t.approvalId}:r.approval;r.state="approval-responded",r.approval={...a,id:t.approvalId,approved:t.approved,...null!=t.reason?{reason:t.reason}:{}},null!=t.providerExecuted&&(r.providerExecuted=t.providerExecuted),null!=t.providerMetadata&&(r.callProviderMetadata=t.providerMetadata),u();break}case"tool-output-denied":d(t.toolCallId).state="output-denied",u();break;case"tool-output-available":{let r=d(t.toolCallId);"dynamic-tool"===r.type?h({toolCallId:t.toolCallId,toolName:r.toolName,state:"output-available",input:r.input,output:t.output,preliminary:t.preliminary,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:r.title,toolMetadata:r.toolMetadata},r):p({toolCallId:t.toolCallId,toolName:pL(r),state:"output-available",input:r.input,output:t.output,providerExecuted:t.providerExecuted,preliminary:t.preliminary,providerMetadata:t.providerMetadata,title:r.title,toolMetadata:r.toolMetadata},r),u();break}case"tool-output-error":{let r=d(t.toolCallId);"dynamic-tool"===r.type?h({toolCallId:t.toolCallId,toolName:r.toolName,state:"output-error",input:r.input,errorText:t.errorText,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:r.title,toolMetadata:r.toolMetadata},r):p({toolCallId:t.toolCallId,toolName:pL(r),state:"output-error",input:r.input,rawInput:r.rawInput,errorText:t.errorText,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:r.title,toolMetadata:r.toolMetadata},r),u();break}case"start-step":n.message.parts.push({type:"step-start"});break;case"finish-step":break;case"reset-step":{let t=c();n.activeTextParts=pj(),n.activeReasoningParts=pj(),n.partialToolCalls=pj(),t.length>0&&(n.message.parts.splice(n.message.parts.length-t.length,t.length),u());break}case"start":null!=t.messageId&&(n.message.id=t.messageId),await f(t.messageMetadata),(null!=t.messageId||null!=t.messageMetadata)&&u({updateStatus:!1});break;case"finish":null!=t.finishReason&&(n.finishReason=t.finishReason),await f(t.messageMetadata),null!=t.messageMetadata&&u();break;case"message-metadata":await f(t.messageMetadata),null!=t.messageMetadata&&u();break;case"error":i?.(Error(t.errorText));break;default:if(t.type.startsWith("data-")){if(a?.[t.type]!=null){let r=n.message.parts.findIndex(r=>"id"in r&&"data"in r&&r.id===t.id&&r.type===t.type),i=r>=0?r:n.message.parts.length;await sq({value:t.data,schema:a[t.type],context:{field:`message.parts[${i}].data`,entityName:t.type,entityId:t.id}})}if(t.transient){s?.(t);break}let r=null!=t.id?n.message.parts.find(r=>t.type===r.type&&t.id===r.id):void 0;null!=r?r.data=t.data:n.message.parts.push(t),s?.(t),u()}}l.enqueue(t)})}}))}({stream:u,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:p,onError:t=>{throw t}}),abortSignal:d.abortController.signal,onError:t=>{throw t}}),g)return c()&&this.setStatus({status:"ready"}),null;c()&&this.setStatus({status:"ready"})}catch(t){if(g||"AbortError"===t.name)return g=!0,c()&&this.setStatus({status:"ready"}),null;if(!c())return null;v=!0,t instanceof TypeError&&(t.message.toLowerCase().includes("fetch")||t.message.toLowerCase().includes("network"))&&(y=!0),this.onError&&t instanceof Error&&this.onError(t),this.setStatus({status:"error",error:t})}finally{try{s&&this.onFinish?.({message:s.state.message,messages:this.state.messages,isAbort:g,isDisconnect:y,isError:v,finishReason:s.state.finishReason})}finally{this.activeResponse===s&&(this.activeResponse=void 0),d()}}
91!v&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:"submit-message",messageId:this.lastMessage?.id,metadata:r,headers:a,body:n})}};t.s(["AbstractChat",0,hn,"DefaultChatTransport",0,ha,"Experimental_AbstractRealtimeSession",0,p9,"callCompletionApi",0,he,"isDeepEqualData",0,function t(r,a){if(r===a)return!0;if(null==r||null==a)return!1;if("object"!=typeof r&&"object"!=typeof a)return r===a;if(r.constructor!==a.constructor)return!1;if(r instanceof Date&&a instanceof Date)return r.getTime()===a.getTime();if(Array.isArray(r)){if(r.length!==a.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],a[n]))return!1;return!0}let n=Object.keys(r),i=Object.keys(a);if(n.length!==i.length)return!1;for(let o of n)if(!i.includes(o)||!t(r[o],a[o]))return!1;return!0},"parsePartialJson",0,pT],73957);var hi=t.i(64585),ho=t.i(56032),hs=Object.prototype.hasOwnProperty;let hl=new WeakMap,hu=()=>{},hc=hu(),hd=Object,hp=t=>t===hc,hh=(t,r)=>({...t,...r}),hf={},hm={},hg="undefined",hy=typeof window!=hg,hv=typeof document!=hg,hb=hy&&"Deno"in window,hw=(t,r)=>{let a=hl.get(t);return[()=>!hp(r)&&t.get(r)||hf,n=>{if(!hp(r)){let i=t.get(r);r in hm||(hm[r]=i),a[5](r,hh(i,n),i||hf)}},a[6],()=>!hp(r)&&r in hm?hm[r]:!hp(r)&&t.get(r)||hf]},h_=!0,[hk,hE]=hy&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[hu,hu],hS={initFocus:t=>(hv&&document.addEventListener("visibilitychange",t),hk("focus",t),()=>{hv&&document.removeEventListener("visibilitychange",t),hE("focus",t)}),initReconnect:t=>{let r=()=>{h_=!0,t()},a=()=>{h_=!1};return hk("online",r),hk("offline",a),()=>{hE("online",r),hE("offline",a)}}},hx=!hi.default.useId,hI=!hy||hb,hT=hI?hi.useEffect:hi.useLayoutEffect,hA="u">typeof navigator&&navigator.connection,hC=!hI&&hA&&(["slow-2g","2g"].includes(hA.effectiveType)||hA.saveData),hO=new WeakMap,hM=(t,r)=>t===`[object ${r}]`,hR=0,hP=t=>{let r,a,n=typeof t,i=hd.prototype.toString.call(t),o=hM(i,"Date"),s=hM(i,"RegExp"),l=hM(i,"Object");if(hd(t)!==t||o||s)r=o?t.toJSON():"symbol"==n?t.toString():"string"==n?JSON.stringify(t):""+t;else{if(r=hO.get(t))return r;if(r=++hR+"~",hO.set(t,r),Array.isArray(t)){for(a=0,r="@";a<t.length;a++)r+=hP(t[a])+",";hO.set(t,r)}if(l){r="#";let n=hd.keys(t).sort();for(;!hp(a=n.pop());)hp(t[a])||(r+=a+":"+hP(t[a])+",");hO.set(t,r)}}return r},hz=t=>{if("function"==typeof t)try{t=t()}catch(r){t=""}let r=t;return[t="string"==typeof t?t:(Array.isArray(t)?t.length:t)?hP(t):"",r]},h$=0,hN=()=>++h$;async function hj(...t){let[r,a,n,i]=t,o=hh({populateCache:!0,throwOnError:!0},"boolean"==typeof i?{revalidate:i}:i||{}),s=o.populateCache,l=o.rollbackOnError,u=o.optimisticData,c=o.throwOnError;if("function"==typeof a){let t=[];for(let n of r.keys())!/^\$(inf|sub)\$/.test(n)&&a(r.get(n)._k)&&t.push(n);return Promise.all(t.map(d))}return d(a);async function d(a){let i,[d]=hz(a);if(!d)return;let[p,h]=hw(r,d),[f,m,g,y]=hl.get(r),v=()=>{let t=f[d];return("function"==typeof o.revalidate?o.revalidate(p().data,a):!1!==o.revalidate)&&(delete g[d],delete y[d],t&&t[0])?t[0](2).then(()=>p().data):p().data};if(t.length<3)return v();let b=n,w=!1,_=hN();m[d]=[_,0];let k=!hp(u),E=p(),S=E.data,x=E._c,I=hp(x)?S:x;if(k&&h({data:u="function"==typeof u?u(I,S):u,_c:I}),"function"==typeof b)try{b=b(I)}catch(t){i=t,w=!0}if(b&&"function"==typeof b.then){let t;if(b=await b.catch(t=>{i=t,w=!0}),_!==m[d][0]){if(w)throw i;return b}w&&k&&(t=i,"function"==typeof l?l(t):!1!==l)&&(s=!0,h({data:I,_c:hc}))}if(s&&!w&&("function"==typeof s?h({data:s(b,I),error:hc,_c:hc}):h({data:b,error:hc,_c:hc})),m[d][1]=hN(),Promise.resolve(v()).then(()=>{h({_c:hc})}),w){if(c)throw i;return}return b}}let hD=(t,r)=>{for(let a in t)t[a][0]&&t[a][0](r)},hU=(t,r)=>{if(!hl.has(t)){let a=hh(hS,r),n=Object.create(null),i=hj.bind(hc,t),o=hu,s=Object.create(null),l=(t,r)=>{let a=s[t]||[];return s[t]=a,a.push(r),()=>{let t=a.indexOf(r);t>=0&&(a[t]=a[a.length-1],a.pop())}},u=(r,a,n)=>{t.set(r,a);let i=s[r];if(i)for(let t of i)t(a,n)},c=r=>{let a=hl.get(t),[,i,o,l]=a,u=hN();for(let t in a[8]++,o)delete o[t];for(let t in l)delete l[t];for(let t in i)i[t]=[u,u];let c={};for(let r of[...t.keys()]){let a=t.get(r);t.delete(r);let n=s[r];if(n)for(let t of n)t(c,a)}let d=!r||!1!==r.revalidate;for(let t in n){let r=n[t];for(let t=0;t<r.length;t++)r[t](4,{revalidate:d&&!t})}},d=()=>
91{if(!hl.has(t)&&(hl.set(t,[n,Object.create(null),Object.create(null),Object.create(null),i,u,l,c,0]),!hI)){let r=a.initFocus(setTimeout.bind(hc,hD.bind(hc,n,0))),i=a.initReconnect(setTimeout.bind(hc,hD.bind(hc,n,1)));o=()=>{r&&r(),i&&i(),hl.delete(t)}}};return d(),[t,i,d,o,c]}let a=hl.get(t);return[t,a[4],hc,hc,a[7]]},[hL,hF,,,hZ]=hU(new Map),hB=hh({onLoadingSlow:hu,onSuccess:hu,onError:hu,onErrorRetry:(t,r,a,n,i)=>{let o=a.errorRetryCount,s=i.retryCount,l=~~((Math.random()+.5)*(1<<(s<8?s:8)))*a.errorRetryInterval;(hp(o)||!(s>o))&&setTimeout(n,l,i)},onDiscarded:hu,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:hC?1e4:5e3,focusThrottleInterval:5e3,dedupingInterval:2e3,loadingTimeout:hC?5e3:3e3,compare:function t(r,a){var n,i;if(r===a)return!0;if(r&&a&&(n=r.constructor)===a.constructor){if(n===Date)return r.getTime()===a.getTime();if(n===RegExp)return r.toString()===a.toString();if(n===Array){if((i=r.length)===a.length)for(;i--&&t(r[i],a[i]););return -1===i}if(!n||"object"==typeof r){for(n in i=0,r)if(hs.call(r,n)&&++i&&!hs.call(a,n)||!(n in a)||!t(r[n],a[n]))return!1;return Object.keys(a).length===i}}return r!=r&&a!=a},isPaused:()=>!1,cache:hL,mutate:hF,unload:hZ,fallback:{}},{isOnline:()=>h_,isVisible:()=>{let t=hv&&document.visibilityState;return hp(t)||"hidden"!==t}}),hq=(t,r)=>{let a=hh(t,r);if(r){let{use:n,fallback:i,cacheData:o}=t,{use:s,fallback:l,cacheData:u}=r;n&&s&&(a.use=n.concat(s)),i&&l&&(a.fallback=hh(i,l)),o&&u&&(a.cacheData=hh(o,u))}return a},hV=(0,hi.createContext)({}),hJ=hy&&window.__SWR_DEVTOOLS_USE__,hW=(hJ?window.__SWR_DEVTOOLS_USE__:[]).concat(t=>(r,a,n)=>{let i=a&&((...t)=>{let[n]=hz(r),[,,,i]=hl.get(hL);if(n.startsWith("$inf$"))return a(...t);let o=i[n];return hp(o)?a(...t):(delete i[n],o)});return t(r,i,n)});hJ&&(window.__SWR_DEVTOOLS_REACT__=hi.default);let hG=hi.default.use||(t=>{switch(t.status){case"pending":throw t;case"fulfilled":return t.value;case"rejected":throw t.reason;default:throw t.status="pending",t.then(r=>{t.status="fulfilled",t.value=r},r=>{t.status="rejected",t.reason=r}),t}}),hH={dedupe:!0},hK=(t,r,a)=>{var n;return!!r&&(null==(n=t.get(r))?void 0:n.has(a))===!0},hY=(t,r,a)=>{if(!r)return;let n=t.get(r);n||(n=new Set,t.set(r,n)),n.add(a)},hX=Promise.resolve(hc);hX.status="fulfilled",hX.value=hc;let hQ=()=>hu;hd.defineProperty(t=>{let{value:r}=t,a=(0,hi.useContext)(hV),n="function"==typeof r,i=(0,hi.useMemo)(()=>n?r(a):r,[n,a,r]),o=(0,hi.useMemo)(()=>n?i:hq(a,i),[n,a,i]),s=i&&i.provider,l=(0,hi.useRef)(hc);s&&!l.current&&(l.current=hU(s(o.cache||hL),i));let u=l.current;return u&&(o.cache=u[0],o.mutate=u[1],o.unload=u[4]),hT(()=>{if(u)return u[2]&&u[2](),u[3]},[]),(0,hi.createElement)(hV.Provider,hh(t,{value:o}))},"defaultValue",{value:hB});let h0=(p=(t,r,a)=>{let{cache:n,compare:i,suspense:o,fallbackData:s,revalidateOnMount:l,revalidateIfStale:u,refreshInterval:c,refreshWhenHidden:d,refreshWhenOffline:p,keepPreviousData:h,strictServerPrefetchWarning:f}=a,[m,g,y,v]=hl.get(n),[b,w]=hz(t),_=(0,hi.useRef)(!1),k=(0,hi.useRef)(!1),E=(0,hi.useRef)(b),S=(0,hi.useRef)(r),x=(0,hi.useRef)(a),I=()=>x.current.isVisible()&&x.current.isOnline(),[T,A,C,O]=hw(n,b),M=(0,hi.useRef)({}).current,R=hp(s)?hp(a.fallback)?hc:a.fallback[b]:s,P=a.cacheData,z=b?null==P?void 0:P[b]:hc,$=b?v[b]:hc,N=hp($)&&!hp(z),j=N?z:$,D=(t,r)=>{for(let a in M)if("data"===a){if(!i(t[a],r[a])&&(!hp(t[a])||!i(K,r[a])))return!1}else if(r[a]!==t[a])return!1;return!0},U=!_.current,L=(0,hi.useMemo)(()=>{let t=T(),a=O(),n=t=>{let a=hh(t);return(delete a._k,(()=>{if(!b||!r||x.current.isPaused())return!1;if(U&&!hp(l))return l;let t=hp(R)?a.data:R;return!(o&&N&&hp(t))&&(hp(t)||u)})())?{isValidating:!0,isLoading:!0,...a}:a},i=n(t),s=t===a?i:n(a),c=i;return[()=>{let t=n(T());return D(t,c)?(c.data=t.data,c.isLoading=t.isLoading,c.isValidating=t.isValidating,c.error=t.error,c):(c=t,t)},()=>s]},[n,b]),F=(0,ho.useSyncExternalStore)((0,hi.useCallback)(t=>C(b,(r,a)=>{D(a,r)||t()}),[n,b]),L[0],L[1]),Z=m[b]&&m[b].length>0,B=F.data,q=hp(B)?R&&"function"==typeof R.then?hG(R):R:B,V=F.error,J=(0,hi.useRef)(q),W=(0,hi.useRef)(hc),G=W.current;G||(W.current=G=new WeakMap);let H=(0,hi.useRef)(null),K=h?hp(B)?hp(J.current)?q:J.current:B:q,Y=b&&hp(q),X=(0,hi.useRef)(null);hI||(0,ho.useSyncExternalStore)(hQ,()=>(X.current=!1,X),()=>(X.current=!0,X));let Q=X.current;f&&Q&&!o&&Y&&console.warn(`Missing pre-initiated data for serialized key "${b}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);let ee=!(!b||!r||x.current.isPaused())&&(!Z||!!hp(V))&&(U&&!hp(l)?l:(!o||!N||!Y)&&(o?!hp(q)&&u:hp(q)||u)),et=U&&ee,er=hp(F.isValidating)?et:F.isValidating,ea=hp(F.isLoading)?et:F.isLoading,en=(0,hi.useCallback)(async t=>{let r,n,o=S.current;if(!b||!o||k.current||x.current.isPaused())return!1;let s=!0,l=t||{},u=!y[b]||!l.dedupe,c=N&&!hK(G,P,b)&&!hp(j)&&hp(T().data),d=()=>hx?!k.current&&b===E.current&&_.current:b===E.current,p={isValidating:!1,isLoading:!1},h=()=>{A(p)},f=()=>{let t=y[b];t&&t[1]===n&&delete y[b]},C={isValidating:!0};hp(T().data)&&(C.isLoading=!0);try{if(u&&(A(C),a.loadingTimeout&&hp(T().data)&&setTimeout(()=>{s&&d()&&x.current.onLoadingSlow(b,a)},a.loadingTimeout),c&&hY(G,P,b),y[b]=[c?j:o(w),hN()],c&&v[b]&&delete v[b]),[r,n]=y[b],r=await r,u&&setTimeout(f,a.dedupingInterval),!y[b]||y[b][1]!==n)return u&&d()&&x.current.onDiscarded(b),!1;p.error=hc;let t=g[b];if(!hp(t)&&(n<=t[0]||n<=t[1]||0===t[1]))return h(),u&&d()&&x.current.onDiscarded(b),!1;let l=T().data;p.data=i(l,r)?l:r,u&&d()&&x.current.onSuccess(r,b,a)}catch(a){f();let t=x.current,{shouldRetryOnError:r}=t;!t.isPaused()&&(p.error=a,u&&d())&&(t.onError(a,b,t),(!0===r||"function"==typeof r&&r(a))&&
91(!x.current.revalidateOnFocus||!x.current.revalidateOnReconnect||I())&&t.onErrorRetry(a,b,t,t=>{let r=m[b];r&&r[0]&&r[0](3,t)},{retryCount:(l.retryCount||0)+1,dedupe:!0}))}return s=!1,h(),!0},[b,n]),ei=(0,hi.useCallback)((...t)=>hj(n,E.current,...t),[]);if(hT(()=>{let t=H.current;t&&(H.current=null,hY(G,t.cacheData,t.key),hp(T().data)&&A({data:t.data,error:hc,_k:t._k}),v[t.key]&&delete v[t.key])}),hT(()=>{S.current=r,x.current=a,hp(B)||(J.current=B)}),hT(()=>{if(r||!N||hp(j)||hK(G,P,b)||!hp(T().data))return;hY(G,P,b);let t=g[b];(({value:t,getCacheData:r,canCommit:a,setCache:n})=>{let i=t=>{a()&&hp(r())&&n(t)};Promise.resolve(t).then(t=>{i({data:t,error:hc})},t=>{i({error:t})})})({value:j,getCacheData:()=>T().data,canCommit:()=>!k.current&&b===E.current&&g[b]===t,setCache:t=>A({...t,_k:w})})}),hT(()=>{var t;let r;if(!b)return;let a=en.bind(hc,hH),n=0;x.current.revalidateOnFocus&&(n=Date.now()+x.current.focusThrottleInterval);let i=(t=(t,r={})=>{if(0==t){let t=Date.now();x.current.revalidateOnFocus&&t>n&&I()&&(n=t+x.current.focusThrottleInterval,a())}else if(1==t)x.current.revalidateOnReconnect&&I()&&a();else if(2==t)return en();else if(3==t)return en(r);else if(4==t&&(J.current=hc,r.revalidate))return en()},(r=m[b]||(m[b]=[])).push(t),()=>{let a=r.indexOf(t);a>=0&&(r[a]=r[r.length-1],r.pop())});if(k.current=!1,E.current=b,_.current=!0,A({_k:w}),ee&&!y[b])if(hp(q)||hI)a();else hy&&typeof window.requestAnimationFrame!=hg?window.requestAnimationFrame(a):setTimeout(a,1);return()=>{k.current=!0,i()}},[b]),hT(()=>{let t;function r(){let r="function"==typeof c?c(T().data):c;r&&-1!==t&&(t=setTimeout(a,r))}function a(){!T().error&&(d||x.current.isVisible())&&(p||x.current.isOnline())?en(hH).then(r):r()}return r(),()=>{t&&(clearTimeout(t),t=-1)}},[c,d,p,b]),(0,hi.useDebugValue)(K),o){if(!hx&&hI&&Y&&hp(j))throw Error("Fallback data is required when using Suspense in SSR.");Y&&(S.current=r,x.current=a,k.current=!1);let t=!hp(j)&&Y,n=hc;if(t&&N?(q=n=j&&"function"==typeof j.then?hG(j):j,K=n,hI||(H.current={data:n,_k:w,key:b,cacheData:P})):hG(t?ei(j):hX),!hp(V)&&Y)throw V;let i=Y&&hp(n)?en(hH):hX;!hp(K)&&Y&&(i.status="fulfilled",i.value=!0),hG(i)}return{mutate:ei,get data(){return M.data=!0,K},get error(){return M.error=!0,V},get isValidating(){return M.isValidating=!0,er},get isLoading(){return M.isLoading=!0,ea}}},function(...t){let r,a=(r=(0,hi.useContext)(hV),(0,hi.useMemo)(()=>hh(hB,r),[r])),[n,i,o]="function"==typeof t[1]?[t[0],t[1],t[2]||{}]:[t[0],null,(null===t[1]?t[2]:t[1])||{}],s=hq(a,o),l=p,{use:u}=s,c=(u||[]).concat(hW);for(let t=c.length;t--;)l=c[t](l);return l(n,i||s.fetcher||null,s)});var h1=t.i(61030);function h2(t,r){return null!=r?(0,h1.default)(t,r):t}t.i(17790);var h4=class{constructor(t=[]){this.#e="ready",this.#t=void 0,this.#r=new Set,this.#a=new Set,this.#n=new Set,this.pushMessage=t=>{this.#i=this.#i.concat(t),this.#o()},this.popMessage=()=>{this.#i=this.#i.slice(0,-1),this.#o()},this.replaceMessage=(t,r)=>{this.#i=[...this.#i.slice(0,t),this.snapshot(r),...this.#i.slice(t+1)],this.#o()},this.snapshot=t=>{var r;if(null==t||"object"!=typeof t||!("parts"in t)||!Array.isArray(t.parts))return t;let a={...t,parts:t.parts.map(t=>({...t}))};return"metadata"in t&&(a.metadata=Array.isArray(r=t.metadata)?[...r]:null!=r&&"object"==typeof r&&(Object.getPrototypeOf(r)===Object.prototype||null===Object.getPrototypeOf(r))?{...r}:r),a},this["~registerMessagesCallback"]=(t,r)=>{let a=r?h2(t,r):t;return this.#r.add(a),()=>{this.#r.delete(a)}},this["~registerStatusCallback"]=t=>(this.#a.add(t),()=>{this.#a.delete(t)}),this["~registerErrorCallback"]=t=>(this.#n.add(t),()=>{this.#n.delete(t)}),this.#o=()=>{this.#r.forEach(t=>t())},this.#s=()=>{this.#a.forEach(t=>t())},this.#l=()=>{this.#n.forEach(t=>t())},this.#i=t}#i;#e;#t;#r;#a;#n;get status(){return this.#e}set status(t){this.#e=t,this.#s()}get error(){return this.#t}set error(t){this.#t=t,this.#l()}get messages(){return this.#i}set messages(t){this.#i=[...t],this.#o()}#o;#s;#l},h6=class extends hn{constructor({messages:t,...r}){const a=new h4(t);super({...r,state:a}),this["~registerMessagesCallback"]=(t,r)=>this.#u["~registerMessagesCallback"](t,r),this["~registerStatusCallback"]=t=>this.#u["~registerStatusCallback"](t),this["~registerErrorCallback"]=t=>this.#u["~registerErrorCallback"](t),this.#u=a}#u};"u"<typeof window?hi.useEffect:hi.useLayoutEffect,t.s(["useChat",0,function({throttle:t,experimental_throttle:r,resume:a=!1,...n}={}){let i,o=t??r,s=(0,hi.useRef)({});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen,transport:n.transport});let l=()=>s.current.transport??(i??=new ha),u={...n,transport:{sendMessages:t=>l().sendMessages(t),reconnectToStream:t=>l().reconnectToStream(t)},onToolCall:t=>s.current.onToolCall?.(t),onData:t=>s.current.onData?.(t),onFinish:t=>s.current.onFinish?.(t),onError:t=>s.current.onError?.(t),sendAutomaticallyWhen:t=>s.current.sendAutomaticallyWhen?.(t)??!1},c="chat"in n?n.chat:n.id,{chat:d,isExternallyManaged:p}=(0,hi.useMemo)(()=>({chat:"chat"in n?n.chat:new h6(u),isExternallyManaged:"chat"in n}),[c]);(0,hi.useEffect)(()=>
91{if(!p)return()=>{d.stop()}},[d,p]);let h=(0,hi.useMemo)(()=>({messages:d.messages}),[d]),f=(0,hi.useCallback)(t=>{let r=!0,a=d["~registerMessagesCallback"](()=>{r&&(h.messages=d.messages,t())},o);return h.messages=d.messages,()=>{r=!1,a()}},[d,h,o]),m=(0,hi.useCallback)(()=>h.messages,[h]),g=(0,hi.useSyncExternalStore)(f,m,m),y=(0,hi.useCallback)(t=>d["~registerStatusCallback"](()=>{("ready"===d.status||"error"===d.status)&&(h.messages=d.messages),t()}),[d,h]),v=(0,hi.useCallback)(()=>d.status,[d]),b=(0,hi.useSyncExternalStore)(y,v,v),w=(0,hi.useSyncExternalStore)(d["~registerErrorCallback"],()=>d.error,()=>d.error),_=(0,hi.useCallback)(t=>{"function"==typeof t&&(t=t(d.messages)),d.messages=t},[d]);return(0,hi.useEffect)(()=>{a&&d.resumeStream()},[a,d]),{id:d.id,messages:g,setMessages:_,sendMessage:d.sendMessage,regenerate:d.regenerate,clearError:d.clearError,stop:d.stop,error:w,resumeStream:d.resumeStream,status:b,addToolResult:d.addToolOutput,addToolOutput:d.addToolOutput,addToolApprovalResponse:d.addToolApprovalResponse}},"useCompletion",0,function({api:t="/api/completion",id:r,initialCompletion:a="",initialInput:n="",credentials:i,headers:o,body:s,streamProtocol:l="data",fetch:u,onFinish:c,onError:d,throttle:p,experimental_throttle:h}={}){let f=p??h,m=(0,hi.useId)(),g=r||m,{data:y,mutate:v}=h0([t,g],null,{fallbackData:a}),{data:b=!1,mutate:w}=h0([g,"loading"],null),[_,k]=(0,hi.useState)(void 0),E=(0,hi.useRef)(null),S=(0,hi.useRef)(0),x=(0,hi.useRef)({credentials:i,headers:o,body:s});(0,hi.useEffect)(()=>{x.current={credentials:i,headers:o,body:s}},[i,o,s]);let I=(0,hi.useCallback)(async(r,a)=>{let n=++S.current;return he({api:t,prompt:r,credentials:x.current.credentials,headers:{...oB(x.current.headers),...oB(a?.headers)},body:{...x.current.body,...a?.body},streamProtocol:l,fetch:u,setCompletion:h2(t=>{S.current===n&&v(t,!1)},f),setLoading:w,setError:k,setAbortController:t=>{E.current=t},getAbortController:()=>E.current,onFinish:c,onError:d})},[v,w,t,x,c,d,k,l,u,f]),T=(0,hi.useCallback)(()=>{E.current?.abort()},[]),A=(0,hi.useCallback)(t=>{v(t,!1)},[v]),C=(0,hi.useCallback)(async(t,r)=>I(t,r),[I]),[O,M]=(0,hi.useState)(n),R=(0,hi.useCallback)(t=>{if(t?.preventDefault?.(),!O)return;let r=C(O);return M(""),r},[O,C,M]),P=(0,hi.useCallback)(t=>{M(t.target.value)},[M]);return{completion:y,complete:C,error:_,setCompletion:A,stop:T,input:O,setInput:M,handleInputChange:P,handleSubmit:R,isLoading:b}}],97311);let h5=(0,t.i(6927).default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);t.s(["ArrowUp",0,h5],3591)},47258,(t,r,a)=>{"use strict";var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,l={},u={SYMBOL_FOR_REQ_CONTEXT:()=>d,getContext:()=>p};for(var c in u)n(l,c,{get:u[c],enumerable:!0});r.exports=((t,r,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let l of o(r))s.call(t,l)||void 0===l||n(t,l,{get:()=>r[l],enumerable:!(a=i(r,l))||a.enumerable});return t})(n({},"__esModule",{value:!0}),l);let d=Symbol.for("@vercel/request-context");function p(){let t=globalThis;return t[d]?.get?.()??{}}},6637,(t,r,a)=>{"use strict";var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,l={},u={AccessTokenMissingError:()=>d,RefreshAccessTokenFailedError:()=>p};for(var c in u)n(l,c,{get:u[c],enumerable:!0});r.exports=((t,r,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let l of o(r))s.call(t,l)||void 0===l||n(t,l,{get:()=>r[l],enumerable:!(a=i(r,l))||a.enumerable});return t})(n({},"__esModule",{value:!0}),l);class d extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}}
91class p extends Error{constructor(t){super("Failed to refresh authentication token.",{cause:t}),this.name="RefreshAccessTokenFailedError"}}},24154,(t,r,a)=>{"use strict";var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,l={},u={AccessTokenMissingError:()=>p.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>p.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>h,getVercelOidcTokenSync:()=>f,getVercelToken:()=>m};for(var c in u)n(l,c,{get:u[c],enumerable:!0});r.exports=((t,r,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let l of o(r))s.call(t,l)||void 0===l||n(t,l,{get:()=>r[l],enumerable:!(a=i(r,l))||a.enumerable});return t})(n({},"__esModule",{value:!0}),l);var d=t.r(47258),p=t.r(6637);async function h(){return""}function f(){return""}async function m(){throw Error("getVercelToken is not supported in browser environments")}},64699,(t,r,a)=>{var n={872:function(t,r){"use strict";r.byteLength=function(t){var r=u(t),a=r[0],n=r[1];return(a+n)*3/4-n},r.toByteArray=function(t){var r,a,o=u(t),s=o[0],l=o[1],c=new i((s+l)*3/4-l),d=0,p=l>0?s-4:s;for(a=0;a<p;a+=4)r=n[t.charCodeAt(a)]<<18|n[t.charCodeAt(a+1)]<<12|n[t.charCodeAt(a+2)]<<6|n[t.charCodeAt(a+3)],c[d++]=r>>16&255,c[d++]=r>>8&255,c[d++]=255&r;return 2===l&&(r=n[t.charCodeAt(a)]<<2|n[t.charCodeAt(a+1)]>>4,c[d++]=255&r),1===l&&(r=n[t.charCodeAt(a)]<<10|n[t.charCodeAt(a+1)]<<4|n[t.charCodeAt(a+2)]>>2,c[d++]=r>>8&255,c[d++]=255&r),c},r.fromByteArray=function(t){for(var r,n=t.length,i=n%3,o=[],s=0,l=n-i;s<l;s+=16383)o.push(function(t,r,n){for(var i,o=[],s=r;s<n;s+=3)i=(t[s]<<16&0xff0000)+(t[s+1]<<8&65280)+(255&t[s+2]),o.push(a[i>>18&63]+a[i>>12&63]+a[i>>6&63]+a[63&i]);return o.join("")}(t,s,s+16383>l?l:s+16383));return 1===i?o.push(a[(r=t[n-1])>>2]+a[r<<4&63]+"=="):2===i&&o.push(a[(r=(t[n-2]<<8)+t[n-1])>>10]+a[r>>4&63]+a[r<<2&63]+"="),o.join("")};for(var a=[],n=[],i="u">typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,l=o.length;s<l;++s)a[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var r=t.length;if(r%4>0)throw Error("Invalid string. Length must be a multiple of 4");var a=t.indexOf("=");-1===a&&(a=r);var n=a===r?0:4-a%4;return[a,n]}n[45]=62,n[95]=63},230:function(t,r,a){"use strict";var n=a(872),i=a(321),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function s(t){if(t>0x7fffffff)throw RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return Object.setPrototypeOf(r,l.prototype),r}function l(t,r,a){if("number"==typeof t){if("string"==typeof r)throw TypeError('The "string" argument must be of type string. Received type number');return d(t)}return u(t,r,a)}function u(t,r,a){if("string"==typeof t){var n=t,i=r;if(("string"!=typeof i||""===i)&&(i="utf8"),!l.isEncoding(i))throw TypeError("Unknown encoding: "+i);var o=0|f(n,i),u=s(o),c=u.write(n,i);return c!==o&&(u=u.slice(0,c)),u}if(ArrayBuffer.isView(t))return p(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(O(t,ArrayBuffer)||t&&O(t.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(O(t,SharedArrayBuffer)||t&&O(t.buffer,SharedArrayBuffer)))return function(t,r,a){var n;if(r<0||t.byteLength<r)throw RangeError('"offset" is outside of buffer bounds');if(t.byteLength<r+(a||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(n=void 0===r&&void 0===a?new Uint8Array(t):void 0===a?new Uint8Array(t,r):new Uint8Array(t,r,a),l.prototype),n}(t,r,a);if("number"==typeof t)throw TypeError('The "value" argument must not be of type number. Received type number');var d=t.valueOf&&t.valueOf();if(null!=d&&d!==t)return l.from(d,r,a);var m=function(t){if(l.isBuffer(t)){var r=0|h(t.length),a=s(r);return 0===a.length||t.copy(a,0,0,r),a}return void 0!==t.length?"number"!=typeof t.length||function(t){return t!=t}(t.length)?s(0):p(t):"Buffer"===t.type&&Array.isArray(t.data)?p(t.data):void 0}(t);if(m)return m;if("u">typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return l.from(t[Symbol.toPrimitive]("string"),r,a);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw TypeError('"size" argument must be of type number');
vendor: 16,509 bytes, line 91
91if(t<0)throw RangeError('The value "'+t+'" is invalid for option "size"')}function d(t){return c(t),s(t<0?0:0|h(t))}function p(t){for(var r=t.length<0?0:0|h(t.length),a=s(r),n=0;n<r;n+=1)a[n]=255&t[n];return a}r.Buffer=l,r.SlowBuffer=function(t){return+t!=t&&(t=0),l.alloc(+t)},r.INSPECT_MAX_BYTES=50,r.kMaxLength=0x7fffffff,l.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(t,r),42===t.foo()}catch(t){return!1}}(),!l.TYPED_ARRAY_SUPPORT&&"u">typeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(t,r,a){return u(t,r,a)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(t,r,a){return(c(t),t<=0)?s(t):void 0!==r?"string"==typeof a?s(t).fill(r,a):s(t).fill(r):s(t)},l.allocUnsafe=function(t){return d(t)},l.allocUnsafeSlow=function(t){return d(t)};function h(t){if(t>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|t}function f(t,r){if(l.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||O(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var a=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===a)return 0;for(var i=!1;;)switch(r){case"ascii":case"latin1":case"binary":return a;case"utf8":case"utf-8":return I(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*a;case"hex":return a>>>1;case"base64":return A(t).length;default:if(i)return n?-1:I(t).length;r=(""+r).toLowerCase(),i=!0}}function m(t,r,a){var i,o,s,l=!1;if((void 0===r||r<0)&&(r=0),r>this.length||((void 0===a||a>this.length)&&(a=this.length),a<=0||(a>>>=0)<=(r>>>=0)))return"";for(t||(t="utf8");;)switch(t){case"hex":return function(t,r,a){var n=t.length;(!r||r<0)&&(r=0),(!a||a<0||a>n)&&(a=n);for(var i="",o=r;o<a;++o)i+=M[t[o]];return i}(this,r,a);case"utf8":case"utf-8":return b(this,r,a);case"ascii":return function(t,r,a){var n="";a=Math.min(t.length,a);for(var i=r;i<a;++i)n+=String.fromCharCode(127&t[i]);return n}(this,r,a);case"latin1":case"binary":return function(t,r,a){var n="";a=Math.min(t.length,a);for(var i=r;i<a;++i)n+=String.fromCharCode(t[i]);return n}(this,r,a);case"base64":return i=this,o=r,s=a,0===o&&s===i.length?n.fromByteArray(i):n.fromByteArray(i.slice(o,s));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(t,r,a){for(var n=t.slice(r,a),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}(this,r,a);default:if(l)throw TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),l=!0}}function g(t,r,a){var n=t[r];t[r]=t[a],t[a]=n}function y(t,r,a,n,i){var o;if(0===t.length)return -1;if("string"==typeof a?(n=a,a=0):a>0x7fffffff?a=0x7fffffff:a<-0x80000000&&(a=-0x80000000),(o=a*=1)!=o&&(a=i?0:t.length-1),a<0&&(a=t.length+a),a>=t.length)if(i)return -1;else a=t.length-1;else if(a<0)if(!i)return -1;else a=0;if("string"==typeof r&&(r=l.from(r,n)),l.isBuffer(r))return 0===r.length?-1:v(t,r,a,n,i);if("number"==typeof r){if(r&=255,"function"==typeof Uint8Array.prototype.indexOf)if(i)return Uint8Array.prototype.indexOf.call(t,r,a);else return Uint8Array.prototype.lastIndexOf.call(t,r,a);return v(t,[r],a,n,i)}throw TypeError("val must be string, number or Buffer")}function v(t,r,a,n,i){var o,s=1,l=t.length,u=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return -1;s=2,l/=2,u/=2,a/=2}function c(t,r){return 1===s?t[r]:t.readUInt16BE(r*s)}if(i){var d=-1;for(o=a;o<l;o++)if(c(t,o)===c(r,-1===d?0:o-d)){if(-1===d&&(d=o),o-d+1===u)return d*s}else -1!==d&&(o-=o-d),d=-1}else for(a+u>l&&(a=l-u),o=a;o>=0;o--){for(var p=!0,h=0;h<u;h++)if(c(t,o+h)!==c(r,h)){p=!1;break}if(p)return o}return -1}l.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==l.prototype},l.compare=function(t,r){if(O(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),O(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(t)||!l.isBuffer(r))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;for(var a=t.length,n=r.length,i=0,o=Math.min(a,n);i<o;++i)if(t[i]!==r[i]){a=t[i],n=r[i];break}return a<n?-1:+(n<a)},l.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(t,r){if(!Array.isArray(t))throw TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return l.alloc(0);if(void 0===r)for(a=0,r=0;a<t.length;++a)r+=t[a].length;var a,n=l.allocUnsafe(r),i=0;for(a=0;a<t.length;++a){var o=t[a];if(O(o,Uint8Array)&&(o=l.from(o)),!l.isBuffer(o))throw TypeError('"list" argument must be an Array of Buffers');o.copy(n,i),i+=o.length}return n},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)g(this,r,r+1);return this},l.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)g(this,r,r+3),g(this,r+1,r+2);return this},l.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)g(this,r,r+7),g(this,r+1,r+6),g(this,r+2,r+5),g(this,r+3,r+4);return this},l.prototype.toString=function(){var t=this.length;return 0===t?"":0==arguments.length?b(this,0,t):m.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(t){if(!l.isBuffer(t))throw TypeError("Argument must be a Buffer");return this===t||0===l.compare(this,t)},l.prototype.inspect=function(){var t="",a=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,a).replace(/(.{2})/g,"$1 ").trim(),this.length>a&&(t+=" ... "),"<Buffer "+t+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(t,r,a,n,i){if(O(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(t))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===a&&(a=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||a>t.length||n<0||i>this.length)throw RangeError("out of range index");if(n>=i&&r>=a)return 0;if(n>=i)return -1;if(r>=a)return 1;if(r>>>=0,a>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,s=a-r,u=Math.min(o,s),c=this.slice(n,i),d=t.slice(r,a),p=0;p<u;++p)if(c[p]!==d[p]){o=c[p],s=d[p];break}return o<s?-1:+(s<o)},l.prototype.includes=function(t,r,a){return -1!==this.indexOf(t,r,a)},l.prototype.indexOf=function(t,r,a){return y(this,t,r,a,!0)},l.prototype.lastIndexOf=function(t,r,a){return y(this,t,r,a,!1)};function b(t,r,a){a=Math.min(t.length,a);for(var n=[],i=r;i<a;){var o,s,l,u,c=t[i],d=null,p=c>239?4:c>223?3:c>191?2:1;if(i+p<=a)switch(p){case 1:c<128&&(d=c);break;case 2:(192&(o=t[i+1]))==128&&(u=(31&c)<<6|63&o)>127&&(d=u);break;case 3:o=t[i+1],s=t[i+2],(192&o)==128&&(192&s)==128&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(d=u);break;case 4:o=t[i+1],s=t[i+2],l=t[i+3],(192&o)==128&&(192&s)==128&&(192&l)==128&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&l)>65535&&u<1114112&&(d=u)}null===d?(d=65533,p=1):d>65535&&(d-=65536,n.push(d>>>10&1023|55296),d=56320|1023&d),n.push(d),i+=p}var h=n,f=h.length;if(f<=4096)return String.fromCharCode.apply(String,h);for(var m="",g=0;g<f;)m+=String.fromCharCode.apply(String,h.slice(g,g+=4096));return m}function w(t,r,a){if(t%1!=0||t<0)throw RangeError("offset is not uint");if(t+r>a)throw RangeError("Trying to access beyond buffer length")}function _(t,r,a,n,i,o){if(!l.isBuffer(t))throw TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<o)throw RangeError('"value" argument is out of bounds');if(a+n>t.length)throw RangeError("Index out of range")}function k(t,r,a,n,i,o){if(a+n>t.length||a<0)throw RangeError("Index out of range")}function E(t,r,a,n,o){return r*=1,a>>>=0,o||k(t,r,a,4,34028234663852886e22,-34028234663852886e22),i.write(t,r,a,n,23,4),a+4}function S(t,r,a,n,o){return r*=1,a>>>=0,o||k(t,r,a,8,17976931348623157e292,-17976931348623157e292),i.write(t,r,a,n,52,8),a+8}l.prototype.write=function(t,r,a,n){if(void 0===r)n="utf8",a=this.length,r=0;else if(void 0===a&&"string"==typeof r)n=r,a=this.length,r=0;else if(isFinite(r))r>>>=0,isFinite(a)?(a>>>=0,void 0===n&&(n="utf8")):(n=a,a=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,o,s,l,u,c,d,p,h=this.length-r;if((void 0===a||a>h)&&(a=h),t.length>0&&(a<0||r<0)||r>this.length)throw RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var f=!1;;)switch(n){case"hex":return function(t,r,a,n){a=Number(a)||0;var i=t.length-a;n?(n=Number(n))>i&&(n=i):n=i;var o=r.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var l,u=parseInt(r.substr(2*s,2),16);if((l=u)!=l)break;t[a+s]=u}return s}(this,t,r,a);case"utf8":case"utf-8":return i=r,o=a,C(I(t,this.length-i),this,i,o);case"ascii":return s=r,l=a,C(T(t),this,s,l);case"latin1":case"binary":return function(t,r,a,n){return C(T(r),t,a,n)}(this,t,r,a);case"base64":return u=r,c=a,C(A(t),this,u,c);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return d=r,p=a,C(function(t,r){for(var a,n,i=[],o=0;o<t.length&&!((r-=2)<0);++o)n=(a=t.charCodeAt(o))>>8,i.push(a%256),i.push(n);return i}(t,this.length-d),this,d,p);default:if(f)throw TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),f=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},l.prototype.slice=function(t,r){var a=this.length;t=~~t,r=void 0===r?a:~~r,t<0?(t+=a)<0&&(t=0):t>a&&(t=a),r<0?(r+=a)<0&&(r=0):r>a&&(r=a),r<t&&(r=t);var n=this.subarray(t,r);return Object.setPrototypeOf(n,l.prototype),n},l.prototype.readUIntLE=function(t,r,a){t>>>=0,r>>>=0,a||w(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n},l.prototype.readUIntBE=function(t,r,a){t>>>=0,r>>>=0,a||w(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},l.prototype.readUInt8=function(t,r){return t>>>=0,r||w(t,1,this.length),this[t]},l.prototype.readUInt16LE=function(t,r){return t>>>=0,r||w(t,2,this.length),this[t]|this[t+1]<<8},l.prototype.readUInt16BE=function(t,r){return t>>>=0,r||w(t,2,this.length),this[t]<<8|this[t+1]},l.prototype.readUInt32LE=function(t,r){return t>>>=0,r||w(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+0x1000000*this[t+3]},l.prototype.readUInt32BE=function(t,r){return t>>>=0,r||w(t,4,this.length),0x1000000*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},l.prototype.readIntLE=function(t,r,a){t>>>=0,r>>>=0,a||w(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*r)),n},l.prototype.readIntBE=function(t,r,a){t>>>=0,r>>>=0,a||w(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},l.prototype.readInt8=function(t,r){return(t>>>=0,r||w(t,1,this.length),128&this[t])?-((255-this[t]+1)*1):this[t]},l.prototype.readInt16LE=function(t,r){t>>>=0,r||w(t,2,this.length);var a=this[t]|this[t+1]<<8;return 32768&a?0xffff0000|a:a},l.prototype.readInt16BE=function(t,r){t>>>=0,r||w(t,2,this.length);var a=this[t+1]|this[t]<<8;return 32768&a?0xffff0000|a:a},l.prototype.readInt32LE=function(t,r){return t>>>=0,r||w(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},l.prototype.readInt32BE=function(t,r){return t>>>=0,r||w(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},l.prototype.readFloatLE=function(t,r){return t>>>=0,r||w(t,4,this.length),i.read(this,t,!0,23,4)},l.prototype.readFloatBE=function(t,r){return t>>>=0,r||w(t,4,this.length),i.read(this,t,!1,23,4)},l.prototype.readDoubleLE=function(t,r){return t>>>=0,r||w(t,8,this.length),i.read(this,t,!0,52,8)},l.prototype.readDoubleBE=function(t,r){return t>>>=0,r||w(t,8,this.length),i.read(this,t,!1,52,8)},l.prototype.writeUIntLE=function(t,r,a,n){if(t*=1,r>>>=0,a>>>=0,!n){var i=Math.pow(2,8*a)-1;_(this,t,r,a,i,0)}var o=1,s=0;for(this[r]=255&t;++s<a&&(o*=256);)this[r+s]=t/o&255;return r+a},l.prototype.writeUIntBE=function(t,r,a,n){if(t*=1,r>>>=0,a>>>=0,!n){var i=Math.pow(2,8*a)-1;_(this,t,r,a,i,0)}var o=a-1,s=1;for(this[r+o]=255&t;--o>=0&&(s*=256);)this[r+o]=t/s&255;return r+a},l.prototype.writeUInt8=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,1,255,0),this[r]=255&t,r+1},l.prototype.writeUInt16LE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},l.prototype.writeUInt16BE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},l.prototype.writeUInt32LE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,4,0xffffffff,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},l.prototype.writeUInt32BE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,4,0xffffffff,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},l.prototype.writeIntLE=function(t,r,a,n){if(t*=1,r>>>=0,!n){var i=Math.pow(2,8*a-1);_(this,t,r,a,i-1,-i)}var o=0,s=1,l=0;for(this[r]=255&t;++o<a&&(s*=256);)t<0&&0===l&&0!==this[r+o-1]&&(l=1),this[r+o]=(t/s|0)-l&255;return r+a},l.prototype.writeIntBE=function(t,r,a,n){if(t*=1,r>>>=0,!n){var i=Math.pow(2,8*a-1);_(this,t,r,a,i-1,-i)}var o=a-1,s=1,l=0;for(this[r+o]=255&t;--o>=0&&(s*=256);)t<0&&0===l&&0!==this[r+o+1]&&(l=1),this[r+o]=(t/s|0)-l&255;return r+a},l.prototype.writeInt8=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},l.prototype.writeInt16LE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},l.prototype.writeInt16BE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},l.prototype.writeInt32LE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,4,0x7fffffff,-0x80000000),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},l.prototype.writeInt32BE=function(t,r,a){return t*=1,r>>>=0,a||_(this,t,r,4,0x7fffffff,-0x80000000),t<0&&(t=0xffffffff+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},l.prototype.writeFloatLE=function(t,r,a){return E(this,t,r,!0,a)},l.prototype.writeFloatBE=function(t,r,a){return E(this,t,r,!1,a)},l.prototype.writeDoubleLE=function(t,r,a){return S(this,t,r,!0,a)},l.prototype.writeDoubleBE=function(t,r,a){return S(this,t,r,!1,a)},l.prototype.copy=function(t,r,a,n){if(!l.isBuffer(t))throw TypeError("argument should be a Buffer");if(a||(a=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<a&&(n=a),n===a||0===t.length||0===this.length)return 0;if(r<0)throw RangeError("targetStart out of bounds");if(a<0||a>=this.length)throw RangeError("Index out of range");if(n<0)throw RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-a&&(n=t.length-r+a);var i=n-a;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(r,a,n);else if(this===t&&a<r&&r<n)for(var o=i-1;o>=0;--o)t[o+r]=this[o+a];else Uint8Array.prototype.set.call(t,this.subarray(a,n),r);return i},l.prototype.fill=function(t,r,a,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,a=this.length):"string"==typeof a&&(n=a,a=this.length),void 0!==n&&"string"!=typeof n)throw TypeError("encoding must be a string");if("string"==typeof n&&!l.isEncoding(n))throw TypeError("Unknown encoding: "+n);if(1===t.length){var i,o=t.charCodeAt(0);("utf8"===n&&o<128||"latin1"===n)&&(t=o)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(r<0||this.length<r||this.length<a)throw RangeError("Out of range index");if(a<=r)return this;if(r>>>=0,a=void 0===a?this.length:a>>>0,t||(t=0),"number"==typeof t)for(i=r;i<a;++i)this[i]=t;else{var s=l.isBuffer(t)?t:l.from(t,n),u=s.length;
91if(0===u)throw TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<a-r;++i)this[i+r]=s[i%u]}return this};var x=/[^+/0-9A-Za-z-_]/g;function I(t,r){r=r||1/0;for(var a,n=t.length,i=null,o=[],s=0;s<n;++s){if((a=t.charCodeAt(s))>55295&&a<57344){if(!i){if(a>56319||s+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=a;continue}if(a<56320){(r-=3)>-1&&o.push(239,191,189),i=a;continue}a=(i-55296<<10|a-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,a<128){if((r-=1)<0)break;o.push(a)}else if(a<2048){if((r-=2)<0)break;o.push(a>>6|192,63&a|128)}else if(a<65536){if((r-=3)<0)break;o.push(a>>12|224,a>>6&63|128,63&a|128)}else if(a<1114112){if((r-=4)<0)break;o.push(a>>18|240,a>>12&63|128,a>>6&63|128,63&a|128)}else throw Error("Invalid code point")}return o}function T(t){for(var r=[],a=0;a<t.length;++a)r.push(255&t.charCodeAt(a));return r}function A(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(x,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function C(t,r,a,n){for(var i=0;i<n&&!(i+a>=r.length)&&!(i>=t.length);++i)r[i+a]=t[i];return i}function O(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}var M=function(){for(var t="0123456789abcdef",r=Array(256),a=0;a<16;++a)for(var n=16*a,i=0;i<16;++i)r[n+i]=t[a]+t[i];return r}()},321:function(t,r){r.read=function(t,r,a,n,i){var o,s,l=8*i-n-1,u=(1<<l)-1,c=u>>1,d=-7,p=a?i-1:0,h=a?-1:1,f=t[r+p];for(p+=h,o=f&(1<<-d)-1,f>>=-d,d+=l;d>0;o=256*o+t[r+p],p+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=n;d>0;s=256*s+t[r+p],p+=h,d-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=c}return(f?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,r,a,n,i,o){var s,l,u,c=8*o-i-1,d=(1<<c)-1,p=d>>1,h=5960464477539062e-23*(23===i),f=n?0:o-1,m=n?1:-1,g=+(r<0||0===r&&1/r<0);for(isNaN(r=Math.abs(r))||r===1/0?(l=+!!isNaN(r),s=d):(s=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-s))<1&&(s--,u*=2),s+p>=1?r+=h/u:r+=h*Math.pow(2,1-p),r*u>=2&&(s++,u/=2),s+p>=d?(l=0,s=d):s+p>=1?(l=(r*u-1)*Math.pow(2,i),s+=p):(l=r*Math.pow(2,p-1)*Math.pow(2,i),s=0));i>=8;t[a+f]=255&l,f+=m,l/=256,i-=8);for(s=s<<i|l,c+=i;c>0;t[a+f]=255&s,f+=m,s/=256,c-=8);t[a+f-m]|=128*g}}},i={};function o(t){var r=i[t];if(void 0!==r)return r.exports;var a=i[t]={exports:{}},s=!0;try{n[t](a,a.exports,o),s=!1}finally{s&&delete i[t]}return a.exports}o.ab="/ROOT/node_modules/.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/next/dist/compiled/buffer/",r.exports=o(230)},25661,(t,r,a)=>{"use strict";var n=t.r(64585),i="function"==typeof Object.is?Object.is:function(t,r){return t===r&&(0!==t||1/t==1/r)||t!=t&&r!=r},o=n.useState,s=n.useEffect,l=n.useLayoutEffect,u=n.useDebugValue;function c(t){var r=t.getSnapshot;t=t.value;try{var a=r();return!i(t,a)}catch(t){return!0}}var d="u"<typeof window||void 0===window.document||void 0===window.document.createElement?function(t,r){return r()}:function(t,r){var a=r(),n=o({inst:{value:a,getSnapshot:r}}),i=n[0].inst,d=n[1];return l(function(){i.value=a,i.getSnapshot=r,c(i)&&d({inst:i})},[t,a,r]),s(function(){return c(i)&&d({inst:i}),t(function(){c(i)&&d({inst:i})})},[t]),u(a),a};a.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:d},56032,(t,r,a)=>{"use strict";t.i(52889),r.exports=t.r(25661)},61030,(t,r,a)=>{r.exports=function(t,r){let a;if("function"!=typeof t)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let n=0;return function(...i){clearTimeout(a);let o=Date.now(),s=r-(o-n);s<=0?(n=o,t.apply(this,i)):a=setTimeout(()=>{n=Date.now(),t.apply(this,i)},s)}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.