@opentiny/next-sdk 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent/AgentModelProvider.ts +78 -81
- package/agent/type.ts +6 -9
- package/agent/utils/getAISDKTools.ts +0 -1
- package/agent/utils/getBuiltinMcpTools.ts +7 -7
- package/core.ts +0 -3
- package/dist/SimulatorMask-BHVXyogh-CARX3Rff.js +361 -0
- package/dist/agent/type.d.ts +4 -12
- package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
- package/dist/core.d.ts +0 -1
- package/dist/core.js +16 -17
- package/dist/index-R_HIbfUX.js +6604 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +76 -4969
- package/dist/{initialize-builtin-WebMCP-HgObT902.js → initialize-builtin-WebMCP-JaoKwVlm.js} +1156 -1037
- package/dist/page-tools/a11y/build.d.ts +10 -0
- package/dist/page-tools/a11y/config.d.ts +96 -0
- package/dist/page-tools/a11y/constants.d.ts +11 -0
- package/dist/page-tools/a11y/search.d.ts +17 -0
- package/dist/page-tools/a11y/types.d.ts +95 -0
- package/dist/page-tools/a11y/utils.d.ts +55 -0
- package/dist/page-tools/a11y/vnode.d.ts +40 -0
- package/dist/page-tools/a11y-tree.d.ts +9 -99
- package/dist/page-tools/configs/console-cloud.d.ts +6 -0
- package/dist/page-tools/constants.d.ts +10 -0
- package/dist/page-tools/context.d.ts +40 -0
- package/dist/page-tools/handlers/browserState.d.ts +8 -0
- package/dist/page-tools/handlers/click.d.ts +8 -0
- package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
- package/dist/page-tools/handlers/fill.d.ts +8 -0
- package/dist/page-tools/handlers/scroll.d.ts +8 -0
- package/dist/page-tools/handlers/searchTree.d.ts +9 -0
- package/dist/page-tools/handlers/select.d.ts +8 -0
- package/dist/page-tools/page-agent-highlight/index.d.ts +21 -0
- package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +16 -0
- package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
- package/dist/page-tools/page-agent-tool-event.d.ts +26 -0
- package/dist/page-tools/page-agent-tool.d.ts +3 -8
- package/dist/page-tools/schema.d.ts +44 -0
- package/dist/page-tools/tool-config.d.ts +50 -0
- package/dist/page-tools/utils/dom.d.ts +6 -0
- package/dist/page-tools/utils/scroll.d.ts +15 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.js +732 -0
- package/dist/utils/builtinProxy.d.ts +1 -1
- package/dist/vitest.config.d.ts +2 -0
- package/index.ts +35 -5
- package/package.json +23 -29
- package/page-tools/a11y/build.ts +74 -0
- package/page-tools/a11y/config.ts +465 -0
- package/page-tools/a11y/constants.ts +131 -0
- package/page-tools/a11y/search.ts +127 -0
- package/page-tools/a11y/types.ts +105 -0
- package/page-tools/a11y/utils.ts +239 -0
- package/page-tools/a11y/vnode.ts +439 -0
- package/page-tools/a11y-tree.ts +9 -527
- package/page-tools/bridge.ts +23 -3
- package/page-tools/configs/console-cloud.ts +172 -0
- package/page-tools/constants.ts +12 -0
- package/page-tools/context.ts +50 -0
- package/page-tools/handlers/browserState.ts +12 -0
- package/page-tools/handlers/click.ts +30 -0
- package/page-tools/handlers/executeJavascript.ts +22 -0
- package/page-tools/handlers/fill.ts +65 -0
- package/page-tools/handlers/scroll.ts +66 -0
- package/page-tools/handlers/searchTree.ts +27 -0
- package/page-tools/handlers/select.ts +39 -0
- package/page-tools/page-agent-highlight/index.ts +245 -0
- package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
- package/page-tools/page-agent-mask/SimulatorMask.ts +299 -0
- package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
- package/page-tools/page-agent-mask/cursor-border.svg +3 -0
- package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
- package/page-tools/page-agent-mask/cursor.module.css +70 -0
- package/page-tools/page-agent-mask/hauwei.svg +25 -0
- package/page-tools/page-agent-prompt.md +34 -18
- package/page-tools/page-agent-tool-event.ts +113 -0
- package/page-tools/page-agent-tool.ts +146 -162
- package/page-tools/schema.ts +52 -0
- package/page-tools/tool-config.ts +100 -0
- package/page-tools/utils/dom.ts +158 -0
- package/page-tools/utils/scroll.ts +58 -0
- package/runtime.ts +44 -0
- package/test/page-tools/a11y/build.test.ts +638 -0
- package/test/page-tools/a11y/config.test.ts +370 -0
- package/test/page-tools/configs/console-cloud.test.ts +168 -0
- package/test/page-tools/page-agent-highlight.test.ts +110 -0
- package/test/page-tools/page-agent-tool-dispatch.test.ts +208 -0
- package/test/page-tools/page-agent-tool.test.ts +102 -0
- package/test/page-tools/tool-config.test.ts +112 -0
- package/test/page-tools/utils/dom.test.ts +122 -0
- package/utils/builtinProxy.ts +45 -13
- package/vite.config.runtime.ts +22 -0
- package/vite.config.ts +52 -8
- package/vitest.config.ts +10 -0
- package/McpSdk.ts +0 -14
- package/WebAgent.ts +0 -5
- package/WebMcp.ts +0 -26
- package/Zod.ts +0 -1
- package/dist/McpSdk.d.ts +0 -14
- package/dist/SimulatorMask-BHVXyogh-BFEGpD5S.js +0 -1048
- package/dist/SimulatorMask-BHVXyogh-CCYbrb84.js +0 -801
- package/dist/WebAgent.d.ts +0 -5
- package/dist/WebMcp.d.ts +0 -23
- package/dist/Zod.d.ts +0 -1
- package/dist/index.es.dev.js +0 -59017
- package/dist/index.es.js +0 -46795
- package/dist/index.umd.dev.js +0 -60355
- package/dist/index.umd.js +0 -1248
- package/dist/mcpsdk@1.25.3.dev.js +0 -22780
- package/dist/mcpsdk@1.25.3.es.dev.js +0 -22778
- package/dist/mcpsdk@1.25.3.es.js +0 -16960
- package/dist/mcpsdk@1.25.3.js +0 -48
- package/dist/transport/ExtensionClientTransport.d.ts +0 -24
- package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
- package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
- package/dist/transport/messages.d.ts +0 -9
- package/dist/vite.config.mcpSdk.d.ts +0 -2
- package/dist/vite.config.webAgent.d.ts +0 -2
- package/dist/vite.config.webMcp.d.ts +0 -2
- package/dist/vite.config.webMcpFull.d.ts +0 -2
- package/dist/vite.config.zod.d.ts +0 -2
- package/dist/webagent.dev.js +0 -49360
- package/dist/webagent.es.dev.js +0 -49071
- package/dist/webagent.es.js +0 -39219
- package/dist/webagent.js +0 -642
- package/dist/webmcp-full.dev.js +0 -31336
- package/dist/webmcp-full.es.dev.js +0 -30283
- package/dist/webmcp-full.es.js +0 -22889
- package/dist/webmcp-full.js +0 -645
- package/dist/webmcp.dev.js +0 -9572
- package/dist/webmcp.es.dev.js +0 -8518
- package/dist/webmcp.es.js +0 -6727
- package/dist/webmcp.js +0 -602
- package/dist/zod@3.25.76.dev.js +0 -4037
- package/dist/zod@3.25.76.es.dev.js +0 -4033
- package/dist/zod@3.25.76.es.js +0 -2945
- package/dist/zod@3.25.76.js +0 -1
- package/transport/ExtensionClientTransport.ts +0 -100
- package/transport/ExtensionContentServerTransport.ts +0 -162
- package/transport/ExtensionPageServerTransport.ts +0 -149
- package/transport/messages.ts +0 -63
- package/vite-build-tsc.ts +0 -63
- package/vite-env.d.ts +0 -10
- package/vite.config.mcpSdk.ts +0 -28
- package/vite.config.webAgent.ts +0 -19
- package/vite.config.webMcp.ts +0 -40
- package/vite.config.webMcpFull.ts +0 -19
- package/vite.config.zod.ts +0 -23
- /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
package/dist/webagent.js
DELETED
|
@@ -1,642 +0,0 @@
|
|
|
1
|
-
(function(Kr,lo){typeof exports=="object"&&typeof module<"u"?lo(exports):typeof define=="function"&&define.amd?define(["exports"],lo):(Kr=typeof globalThis<"u"?globalThis:Kr||self,lo(Kr.WebAgent={}))})(this,(function(Kr){"use strict";var lo="vercel.ai.error",b1=Symbol.for(lo),Fd,Vd,we=class g1 extends(Vd=Error,Fd=b1,Vd){constructor({name:t,message:r,cause:n}){super(r),this[Fd]=!0,this.name=t,this.cause=n}static isInstance(t){return g1.hasMarker(t,lo)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},Zd="AI_APICallError",Hd=`vercel.ai.error.${Zd}`,k1=Symbol.for(Hd),Bd,Jd,tt=class extends(Jd=we,Bd=k1,Jd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:a,responseBody:i,cause:s,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Zd,message:t,cause:s}),this[Bd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=a,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return we.hasMarker(t,Hd)}},Gd="AI_EmptyResponseBodyError",Wd=`vercel.ai.error.${Gd}`,T1=Symbol.for(Wd),Kd,Yd,C1=class extends(Yd=we,Kd=T1,Yd){constructor({message:t="Empty response body"}={}){super({name:Gd,message:t}),this[Kd]=!0}static isInstance(t){return we.hasMarker(t,Wd)}};function co(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Qd="AI_InvalidArgumentError",Xd=`vercel.ai.error.${Qd}`,S1=Symbol.for(Xd),ep,tp,rp=class extends(tp=we,ep=S1,tp){constructor({message:t,cause:r,argument:n}){super({name:Qd,message:t,cause:r}),this[ep]=!0,this.argument=n}static isInstance(t){return we.hasMarker(t,Xd)}},np="AI_InvalidPromptError",op=`vercel.ai.error.${np}`,I1=Symbol.for(op),ap,sp,un=class extends(sp=we,ap=I1,sp){constructor({prompt:e,message:t,cause:r}){super({name:np,message:`Invalid prompt: ${t}`,cause:r}),this[ap]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,op)}},ip="AI_InvalidResponseDataError",lp=`vercel.ai.error.${ip}`,x1=Symbol.for(lp),cp,up,cl=class extends(up=we,cp=x1,up){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:ip,message:r}),this[cp]=!0,this.data=t}static isInstance(t){return we.hasMarker(t,lp)}},dp="AI_JSONParseError",pp=`vercel.ai.error.${dp}`,E1=Symbol.for(pp),hp,fp,Wa=class extends(fp=we,hp=E1,fp){constructor({text:t,cause:r}){super({name:dp,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
-
Error message: ${co(r)}`,cause:r}),this[hp]=!0,this.text=t}static isInstance(t){return we.hasMarker(t,pp)}},mp="AI_LoadAPIKeyError",gp=`vercel.ai.error.${mp}`,$1=Symbol.for(gp),_p,yp,Ka=class extends(yp=we,_p=$1,yp){constructor({message:t}){super({name:mp,message:t}),this[_p]=!0}static isInstance(t){return we.hasMarker(t,gp)}},vp="AI_TooManyEmbeddingValuesForCallError",wp=`vercel.ai.error.${vp}`,R1=Symbol.for(wp),bp,kp,P1=class extends(kp=we,bp=R1,kp){constructor(e){super({name:vp,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[bp]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return we.hasMarker(e,wp)}},Tp="AI_TypeValidationError",Cp=`vercel.ai.error.${Tp}`,M1=Symbol.for(Cp),Sp,Ip,An=class Ud extends(Ip=we,Sp=M1,Ip){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const a=[];n.entityName&&a.push(n.entityName),n.entityId&&a.push(`id: "${n.entityId}"`),o+=a.join(", "),o+=")"}super({name:Tp,message:`${o}: Value: ${JSON.stringify(t)}.
|
|
3
|
-
Error message: ${co(r)}`,cause:r}),this[Sp]=!0,this.value=t,this.context=n}static isInstance(t){return we.hasMarker(t,Cp)}static wrap({value:t,cause:r,context:n}){var o,a,i;return Ud.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((a=r.context)==null?void 0:a.entityName)===n?.entityName&&((i=r.context)==null?void 0:i.entityId)===n?.entityId?r:new Ud({value:t,cause:r,context:n})}},xp="AI_UnsupportedFunctionalityError",Ep=`vercel.ai.error.${xp}`,O1=Symbol.for(Ep),$p,Rp,Tr=class extends(Rp=we,$p=O1,Rp){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:xp,message:r}),this[$p]=!0,this.functionality=t}static isInstance(t){return we.hasMarker(t,Ep)}};const Pp=Object.freeze({status:"aborted"});function K(e,t,r){function n(s,l){var c;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(c=s._zod).traits??(c.traits=new Set),s._zod.traits.add(e),t(s,l);for(const u in i.prototype)u in s||Object.defineProperty(s,u,{value:i.prototype[u].bind(s)});s._zod.constr=i,s._zod.def=l}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(s){var l;const c=r?.Parent?new a:this;n(c,s),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Ho extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Mp={};function dn(e){return Mp}function Op(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function A1(e,t){return typeof t=="bigint"?t.toString():t}function ul(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function dl(e){return e==null}function pl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function N1(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}function He(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ya(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bo(e){return JSON.stringify(e)}const Ap=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const q1=ul(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xa(e){if(Qa(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Qa(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const L1=new Set(["string","number","symbol"]);function Jo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ge(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function j1(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const D1={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function U1(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Nn(e,{...e._zod.def,shape:r,checks:[]})}function z1(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Nn(e,{...e._zod.def,shape:r,checks:[]})}function F1(e,t){if(!Xa(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return Ya(this,"shape",n),n},checks:[]};return Nn(e,r)}function V1(e,t){return Nn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ya(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Z1(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(o[a]=e?new e({type:"optional",innerType:n[a]}):n[a])}else for(const a in n)o[a]=e?new e({type:"optional",innerType:n[a]}):n[a];return Nn(t,{...t._zod.def,shape:o,checks:[]})}function H1(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const a in r){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(o[a]=new e({type:"nonoptional",innerType:n[a]}))}else for(const a in n)o[a]=new e({type:"nonoptional",innerType:n[a]});return Nn(t,{...t._zod.def,shape:o,checks:[]})}function Go(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function qn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function es(e){return typeof e=="string"?e:e?.message}function pn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=es(e.inst?._zod.def?.error?.(e))??es(t?.error?.(e))??es(r.customError?.(e))??es(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function hl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Np=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,A1,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qp=K("$ZodError",Np),Lp=K("$ZodError",Np,{Parent:Error});function B1(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function J1(e,t){const r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>o({issues:s}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let s=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(e),n}const G1=e=>(t,r,n,o)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Ho;if(i.issues.length){const s=new(o?.Err??e)(i.issues.map(l=>pn(l,a,dn())));throw Ap(s,o?.callee),s}return i.value},W1=e=>async(t,r,n,o)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const s=new(o?.Err??e)(i.issues.map(l=>pn(l,a,dn())));throw Ap(s,o?.callee),s}return i.value},jp=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Ho;return a.issues.length?{success:!1,error:new(e??qp)(a.issues.map(i=>pn(i,o,dn())))}:{success:!0,data:a.value}},Dp=jp(Lp),Up=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>pn(i,o,dn())))}:{success:!0,data:a.value}},K1=Up(Lp),Y1=/^[cC][^\s-]{8,}$/,Q1=/^[0-9a-z]+$/,X1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ew=/^[0-9a-vA-V]{20}$/,tw=/^[A-Za-z0-9]{27}$/,rw=/^[a-zA-Z0-9_-]{21}$/,nw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ow=/^([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})$/,zp=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,aw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function iw(){return new RegExp(sw,"u")}const lw=/^(?:(?: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])$/,cw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,uw=/^((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])$/,dw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fp=/^[A-Za-z0-9_-]*$/,hw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fw=/^\+(?:[0-9]){6,14}[0-9]$/,Vp="(?:(?:\\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])))",mw=new RegExp(`^${Vp}$`);function Zp(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function gw(e){return new RegExp(`^${Zp(e)}$`)}function _w(e){const t=Zp({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Vp}T(?:${n})$`)}const yw=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vw=/^\d+$/,ww=/^-?\d+(?:\.\d+)?/i,bw=/true|false/i,kw=/null/i,Tw=/^[^A-Z]*$/,Cw=/^[^a-z]*$/,Xt=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Hp={number:"number",bigint:"bigint",object:"date"},Bp=K("$ZodCheckLessThan",(e,t)=>{Xt.init(e,t);const r=Hp[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jp=K("$ZodCheckGreaterThan",(e,t)=>{Xt.init(e,t);const r=Hp[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Sw=K("$ZodCheckMultipleOf",(e,t)=>{Xt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):N1(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Iw=K("$ZodCheckNumberFormat",(e,t)=>{Xt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,a]=D1[t.format];e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,s.minimum=o,s.maximum=a,r&&(s.pattern=vw)}),e._zod.check=i=>{const s=i.value;if(r){if(!Number.isInteger(s)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?i.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}s<o&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>a&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inst:e})}}),xw=K("$ZodCheckMaxLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const i=hl(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ew=K("$ZodCheckMinLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const i=hl(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$w=K("$ZodCheckLengthEquals",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,a=o.length;if(a===t.length)return;const i=hl(o),s=a>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ts=K("$ZodCheckStringFormat",(e,t)=>{var r,n;Xt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Rw=K("$ZodCheckRegex",(e,t)=>{ts.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Pw=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tw),ts.init(e,t)}),Mw=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Cw),ts.init(e,t)}),Ow=K("$ZodCheckIncludes",(e,t)=>{Xt.init(e,t);const r=Jo(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Aw=K("$ZodCheckStartsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`^${Jo(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Nw=K("$ZodCheckEndsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`.*${Jo(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),qw=K("$ZodCheckOverwrite",(e,t)=>{Xt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Lw{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
|
|
4
|
-
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),a=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
5
|
-
`))}}const jw={major:4,minor:0,patch:0},Xe=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=jw;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const a of o._zod.onattach)a(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(a,i,s)=>{let l=Go(a),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(a))continue}else if(l)continue;const h=a.issues.length,p=u._zod.check(a);if(p instanceof Promise&&s?.async===!1)throw new Ho;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==h&&(l||(l=Go(a,h)))});else{if(a.issues.length===h)continue;l||(l=Go(a,h))}}return c?c.then(()=>a):a};e._zod.run=(a,i)=>{const s=e._zod.parse(a,i);if(s instanceof Promise){if(i.async===!1)throw new Ho;return s.then(l=>o(l,n,i))}return o(s,n,i)}}e["~standard"]={validate:o=>{try{const a=Dp(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return K1(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),fl=K("$ZodString",(e,t)=>{Xe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yw(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ot=K("$ZodStringFormat",(e,t)=>{ts.init(e,t),fl.init(e,t)}),Dw=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ow),ot.init(e,t)}),Uw=K("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=zp(n))}else t.pattern??(t.pattern=zp());ot.init(e,t)}),zw=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=aw),ot.init(e,t)}),Fw=K("$ZodURL",(e,t)=>{ot.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),a=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:hw.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&a.endsWith("/")?r.value=a.slice(0,-1):r.value=a;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Vw=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=iw()),ot.init(e,t)}),Zw=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=rw),ot.init(e,t)}),Hw=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Y1),ot.init(e,t)}),Bw=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Q1),ot.init(e,t)}),Jw=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=X1),ot.init(e,t)}),Gw=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ew),ot.init(e,t)}),Ww=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=tw),ot.init(e,t)}),Kw=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=_w(t)),ot.init(e,t)}),Yw=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mw),ot.init(e,t)}),Qw=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gw(t)),ot.init(e,t)}),Xw=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nw),ot.init(e,t)}),eb=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=lw),ot.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),tb=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=cw),ot.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),rb=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=uw),ot.init(e,t)}),nb=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=dw),ot.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Gp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ob=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=pw),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Gp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ab(e){if(!Fp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Gp(r)}const sb=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fp),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ab(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ib=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fw),ot.init(e,t)});function lb(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const cb=K("$ZodJWT",(e,t)=>{ot.init(e,t),e._zod.check=r=>{lb(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Wp=K("$ZodNumber",(e,t)=>{Xe.init(e,t),e._zod.pattern=e._zod.bag.pattern??ww,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),r}}),ub=K("$ZodNumber",(e,t)=>{Iw.init(e,t),Wp.init(e,t)}),db=K("$ZodBoolean",(e,t)=>{Xe.init(e,t),e._zod.pattern=bw,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),pb=K("$ZodNull",(e,t)=>{Xe.init(e,t),e._zod.pattern=kw,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),hb=K("$ZodAny",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),fb=K("$ZodUnknown",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),mb=K("$ZodNever",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Kp(e,t,r){e.issues.length&&t.issues.push(...qn(r,e.issues)),t.value[r]=e.value}const gb=K("$ZodArray",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const s=o[i],l=t.element._zod.run({value:s,issues:[]},n);l instanceof Promise?a.push(l.then(c=>Kp(c,r,i))):Kp(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function rs(e,t,r){e.issues.length&&t.issues.push(...qn(r,e.issues)),t.value[r]=e.value}function Yp(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...qn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const _b=K("$ZodObject",(e,t)=>{Xe.init(e,t);const r=ul(()=>{const h=Object.keys(t.shape);for(const m of h)if(!(t.shape[m]instanceof Xe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);const p=j1(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(p)}});He(e._zod,"propValues",()=>{const h=t.shape,p={};for(const m in h){const f=h[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(const b of f.values)p[m].add(b)}}return p});const n=h=>{const p=new Lw(["shape","payload","ctx"]),m=r.value,f=v=>{const g=Bo(v);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");const b=Object.create(null);let w=0;for(const v of m.keys)b[v]=`key_${w++}`;p.write("const newResult = {}");for(const v of m.keys)if(m.optionalKeys.has(v)){const g=b[v];p.write(`const ${g} = ${f(v)};`);const I=Bo(v);p.write(`
|
|
6
|
-
if (${g}.issues.length) {
|
|
7
|
-
if (input[${I}] === undefined) {
|
|
8
|
-
if (${I} in input) {
|
|
9
|
-
newResult[${I}] = undefined;
|
|
10
|
-
}
|
|
11
|
-
} else {
|
|
12
|
-
payload.issues = payload.issues.concat(
|
|
13
|
-
${g}.issues.map((iss) => ({
|
|
14
|
-
...iss,
|
|
15
|
-
path: iss.path ? [${I}, ...iss.path] : [${I}],
|
|
16
|
-
}))
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
} else if (${g}.value === undefined) {
|
|
20
|
-
if (${I} in input) newResult[${I}] = undefined;
|
|
21
|
-
} else {
|
|
22
|
-
newResult[${I}] = ${g}.value;
|
|
23
|
-
}
|
|
24
|
-
`)}else{const g=b[v];p.write(`const ${g} = ${f(v)};`),p.write(`
|
|
25
|
-
if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
|
|
26
|
-
...iss,
|
|
27
|
-
path: iss.path ? [${Bo(v)}, ...iss.path] : [${Bo(v)}]
|
|
28
|
-
})));`),p.write(`newResult[${Bo(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const C=p.compile();return(v,g)=>C(h,v,g)};let o;const a=Qa,i=!Mp.jitless,l=i&&q1.value,c=t.catchall;let u;e._zod.parse=(h,p)=>{u??(u=r.value);const m=h.value;if(!a(m))return h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h;const f=[];if(i&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),h=o(h,p);else{h.value={};const g=u.shape;for(const I of u.keys){const y=g[I],_=y._zod.run({value:m[I],issues:[]},p),k=y._zod.optin==="optional"&&y._zod.optout==="optional";_ instanceof Promise?f.push(_.then(S=>k?Yp(S,h,I,m):rs(S,h,I))):k?Yp(_,h,I,m):rs(_,h,I)}}if(!c)return f.length?Promise.all(f).then(()=>h):h;const b=[],w=u.keySet,C=c._zod,v=C.def.type;for(const g of Object.keys(m)){if(w.has(g))continue;if(v==="never"){b.push(g);continue}const I=C.run({value:m[g],issues:[]},p);I instanceof Promise?f.push(I.then(y=>rs(y,h,g))):rs(I,h,g)}return b.length&&h.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:e}),f.length?Promise.all(f).then(()=>h):h}});function Qp(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(a=>pn(a,n,dn())))}),t}const Xp=K("$ZodUnion",(e,t)=>{Xe.init(e,t),He(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),He(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),He(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),He(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>pl(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const a=[];for(const i of t.options){const s=i._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)a.push(s),o=!0;else{if(s.issues.length===0)return s;a.push(s)}}return o?Promise.all(a).then(i=>Qp(i,r,e,n)):Qp(a,r,e,n)}}),yb=K("$ZodDiscriminatedUnion",(e,t)=>{Xp.init(e,t);const r=e._zod.parse;He(e._zod,"propValues",()=>{const o={};for(const a of t.options){const i=a._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const[s,l]of Object.entries(i)){o[s]||(o[s]=new Set);for(const c of l)o[s].add(c)}}return o});const n=ul(()=>{const o=t.options,a=new Map;for(const i of o){const s=i._zod.propValues[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of s){if(a.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);a.set(l,i)}}return a});e._zod.parse=(o,a)=>{const i=o.value;if(!Qa(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const s=n.value.get(i?.[t.discriminator]);return s?s._zod.run(o,a):t.unionFallback?r(o,a):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),vb=K("$ZodIntersection",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,c])=>eh(r,l,c)):eh(r,a,i)}});function ml(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xa(e)&&Xa(t)){const r=Object.keys(t),n=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of n){const i=ml(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],a=t[n],i=ml(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function eh(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Go(e))return e;const n=ml(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const wb=K("$ZodRecord",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Xa(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const a=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;r.value={};for(const l of i)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&r.issues.push(...qn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...qn(l,c.issues)),r.value[l]=c.value)}let s;for(const l in o)i.has(l)||(s=s??[],s.push(l));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{r.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const s=t.keyType._zod.run({value:i,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(c=>pn(c,n,dn())),input:i,path:[i],inst:e}),r.value[s.value]=s.value;continue}const l=t.valueType._zod.run({value:o[i],issues:[]},n);l instanceof Promise?a.push(l.then(c=>{c.issues.length&&r.issues.push(...qn(i,c.issues)),r.value[s.value]=c.value})):(l.issues.length&&r.issues.push(...qn(i,l.issues)),r.value[s.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),bb=K("$ZodEnum",(e,t)=>{Xe.init(e,t);const r=Op(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>L1.has(typeof n)).map(n=>typeof n=="string"?Jo(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const a=n.value;return e._zod.values.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:e}),n}}),kb=K("$ZodLiteral",(e,t)=>{Xe.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Jo(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Tb=K("$ZodTransform",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ho;return r.value=o,r}}),Cb=K("$ZodOptional",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Sb=K("$ZodNullable",(e,t)=>{Xe.init(e,t),He(e._zod,"optin",()=>t.innerType._zod.optin),He(e._zod,"optout",()=>t.innerType._zod.optout),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pl(r.source)}|null)$`):void 0}),He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Ib=K("$ZodDefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(a=>th(a,t)):th(o,t)}});function th(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const xb=K("$ZodPrefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Eb=K("$ZodNonOptional",(e,t)=>{Xe.init(e,t),He(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(a=>rh(a,e)):rh(o,e)}});function rh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const $b=K("$ZodCatch",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(e._zod,"optout",()=>t.innerType._zod.optout),He(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>pn(i,n,dn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>pn(a,n,dn()))},input:r.value}),r.issues=[]),r)}}),Rb=K("$ZodPipe",(e,t)=>{Xe.init(e,t),He(e._zod,"values",()=>t.in._zod.values),He(e._zod,"optin",()=>t.in._zod.optin),He(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(a=>nh(a,t,n)):nh(o,t,n)}});function nh(e,t,r){return Go(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Pb=K("$ZodReadonly",(e,t)=>{Xe.init(e,t),He(e._zod,"propValues",()=>t.innerType._zod.propValues),He(e._zod,"values",()=>t.innerType._zod.values),He(e._zod,"optin",()=>t.innerType._zod.optin),He(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(oh):oh(o)}});function oh(e){return e.value=Object.freeze(e.value),e}const Mb=K("$ZodLazy",(e,t)=>{Xe.init(e,t),He(e._zod,"innerType",()=>t.getter()),He(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),He(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),He(e._zod,"optin",()=>e._zod.innerType._zod.optin),He(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Ob=K("$ZodCustom",(e,t)=>{Xt.init(e,t),Xe.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(a=>ah(a,r,n,e));ah(o,r,n,e)}});function ah(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Wo(o))}}class sh{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Ab(){return new sh}const Ko=Ab();function Nb(e,t){return new e({type:"string",...ge(t)})}function qb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ge(t)})}function ih(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ge(t)})}function Lb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ge(t)})}function jb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ge(t)})}function Db(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ge(t)})}function Ub(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ge(t)})}function lh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ge(t)})}function zb(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ge(t)})}function Fb(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ge(t)})}function Vb(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ge(t)})}function Zb(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ge(t)})}function Hb(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ge(t)})}function Bb(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ge(t)})}function Jb(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ge(t)})}function Gb(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ge(t)})}function Wb(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ge(t)})}function Kb(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ge(t)})}function Yb(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ge(t)})}function ch(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ge(t)})}function Qb(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ge(t)})}function Xb(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ge(t)})}function e3(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ge(t)})}function t3(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ge(t)})}function r3(e,t){return new e({type:"string",format:"date",check:"string_format",...ge(t)})}function n3(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ge(t)})}function o3(e,t){return new e({type:"string",format:"duration",check:"string_format",...ge(t)})}function a3(e,t){return new e({type:"number",checks:[],...ge(t)})}function s3(e,t){return new e({type:"number",coerce:!0,checks:[],...ge(t)})}function i3(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ge(t)})}function l3(e,t){return new e({type:"boolean",...ge(t)})}function c3(e,t){return new e({type:"null",...ge(t)})}function u3(e){return new e({type:"any"})}function d3(e){return new e({type:"unknown"})}function p3(e,t){return new e({type:"never",...ge(t)})}function uh(e,t){return new Bp({check:"less_than",...ge(t),value:e,inclusive:!1})}function gl(e,t){return new Bp({check:"less_than",...ge(t),value:e,inclusive:!0})}function dh(e,t){return new Jp({check:"greater_than",...ge(t),value:e,inclusive:!1})}function _l(e,t){return new Jp({check:"greater_than",...ge(t),value:e,inclusive:!0})}function ph(e,t){return new Sw({check:"multiple_of",...ge(t),value:e})}function hh(e,t){return new xw({check:"max_length",...ge(t),maximum:e})}function ns(e,t){return new Ew({check:"min_length",...ge(t),minimum:e})}function fh(e,t){return new $w({check:"length_equals",...ge(t),length:e})}function h3(e,t){return new Rw({check:"string_format",format:"regex",...ge(t),pattern:e})}function f3(e){return new Pw({check:"string_format",format:"lowercase",...ge(e)})}function m3(e){return new Mw({check:"string_format",format:"uppercase",...ge(e)})}function g3(e,t){return new Ow({check:"string_format",format:"includes",...ge(t),includes:e})}function _3(e,t){return new Aw({check:"string_format",format:"starts_with",...ge(t),prefix:e})}function y3(e,t){return new Nw({check:"string_format",format:"ends_with",...ge(t),suffix:e})}function Yo(e){return new qw({check:"overwrite",tx:e})}function v3(e){return Yo(t=>t.normalize(e))}function w3(){return Yo(e=>e.trim())}function b3(){return Yo(e=>e.toLowerCase())}function k3(){return Yo(e=>e.toUpperCase())}function T3(e,t,r){return new e({type:"array",element:t,...ge(r)})}function C3(e,t,r){const n=ge(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function S3(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ge(r)})}class mh{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Ko,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,s);const l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)s.ref=p,this.process(p,h),this.seen.get(p).isParent=!0;else{const m=s.schema;switch(o.type){case"string":{const f=m;f.type="string";const{minimum:b,maximum:w,format:C,patterns:v,contentEncoding:g}=t._zod.bag;if(typeof b=="number"&&(f.minLength=b),typeof w=="number"&&(f.maxLength=w),C&&(f.format=a[C]??C,f.format===""&&delete f.format),g&&(f.contentEncoding=g),v&&v.size>0){const I=[...v];I.length===1?f.pattern=I[0].source:I.length>1&&(s.schema.allOf=[...I.map(y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:y.source}))])}break}case"number":{const f=m,{minimum:b,maximum:w,format:C,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:I}=t._zod.bag;typeof C=="string"&&C.includes("int")?f.type="integer":f.type="number",typeof I=="number"&&(f.exclusiveMinimum=I),typeof b=="number"&&(f.minimum=b,typeof I=="number"&&(I>=b?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof w=="number"&&(f.maximum=w,typeof g=="number"&&(g<=w?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{const f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=m,{minimum:b,maximum:w}=t._zod.bag;typeof b=="number"&&(f.minItems=b),typeof w=="number"&&(f.maxItems=w),f.type="array",f.items=this.process(o.element,{...h,path:[...h.path,"items"]});break}case"object":{const f=m;f.type="object",f.properties={};const b=o.shape;for(const v in b)f.properties[v]=this.process(b[v],{...h,path:[...h.path,"properties",v]});const w=new Set(Object.keys(b)),C=new Set([...w].filter(v=>{const g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));C.size>0&&(f.required=Array.from(C)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=m;f.anyOf=o.options.map((b,w)=>this.process(b,{...h,path:[...h.path,"anyOf",w]}));break}case"intersection":{const f=m,b=this.process(o.left,{...h,path:[...h.path,"allOf",0]}),w=this.process(o.right,{...h,path:[...h.path,"allOf",1]}),C=g=>"allOf"in g&&Object.keys(g).length===1,v=[...C(b)?b.allOf:[b],...C(w)?w.allOf:[w]];f.allOf=v;break}case"tuple":{const f=m;f.type="array";const b=o.items.map((v,g)=>this.process(v,{...h,path:[...h.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=b:f.items=b,o.rest){const v=this.process(o.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...h,path:[...h.path,"items"]}));const{minimum:w,maximum:C}=t._zod.bag;typeof w=="number"&&(f.minItems=w),typeof C=="number"&&(f.maxItems=C);break}case"record":{const f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...h,path:[...h.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...h,path:[...h.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const f=m,b=Op(o.entries);b.every(w=>typeof w=="number")&&(f.type="number"),b.every(w=>typeof w=="string")&&(f.type="string"),f.enum=b;break}case"literal":{const f=m,b=[];for(const w of o.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(w))}else b.push(w);if(b.length!==0)if(b.length===1){const w=b[0];f.type=w===null?"null":typeof w,f.const=w}else b.every(w=>typeof w=="number")&&(f.type="number"),b.every(w=>typeof w=="string")&&(f.type="string"),b.every(w=>typeof w=="boolean")&&(f.type="string"),b.every(w=>w===null)&&(f.type="null"),f.enum=b;break}case"file":{const f=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:C,mime:v}=t._zod.bag;w!==void 0&&(b.minLength=w),C!==void 0&&(b.maxLength=C),v?v.length===1?(b.contentMediaType=v[0],Object.assign(f,b)):f.anyOf=v.map(g=>({...b,contentMediaType:g})):Object.assign(f,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(o.innerType,h);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,h),s.ref=o.innerType;break}case"success":{const f=m;f.type="boolean";break}case"default":{this.process(o.innerType,h),s.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,h),s.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,h),s.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=m,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=b.source;break}case"pipe":{const f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,h),s.ref=f;break}case"readonly":{this.process(o.innerType,h),s.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,h),s.ref=o.innerType;break}case"optional":{this.process(o.innerType,h),s.ref=o.innerType;break}case"lazy":{const f=t._zod.innerType;this.process(f,h),s.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),this.io==="input"&&Ct(t)&&(delete s.schema.examples,delete s.schema.default),this.io==="input"&&s.schema._prefault&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=u=>{const h=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const b=n.external.registry.get(u[0])?.id,w=n.external.uri??(v=>v);if(b)return{ref:w(b)};const C=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=C,{defId:C,ref:`${w("__shared")}#/${h}/${C}`}}if(u[1]===o)return{ref:"#"};const m=`#/${h}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:m}=a(u);h.def={...h.schema},m&&(h.defId=m);const f=h.schema;for(const b in f)delete f[b];f.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${h.cycle?.join("/")}/<root>
|
|
29
|
-
|
|
30
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(n.external){const m=n.external.registry.get(u[0])?.id;if(t!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&n.reused==="ref"){i(u);continue}}const s=(u,h)=>{const p=this.seen.get(u),m=p.def??p.schema,f={...m};if(p.ref===null)return;const b=p.ref;if(p.ref=null,b){s(b,h);const w=this.seen.get(b).schema;w.$ref&&h.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(w)):(Object.assign(m,w),Object.assign(m,f))}p.isParent||this.override({zodSchema:u,jsonSchema:m,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())s(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const h=u[1];h.def&&h.defId&&(c[h.defId]=h.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function I3(e,t){if(e instanceof sh){const n=new mh(t),o={};for(const s of e._idmap.entries()){const[l,c]=s;n.process(c)}const a={},i={registry:e,uri:t?.uri,defs:o};for(const s of e._idmap.entries()){const[l,c]=s;a[l]=n.emit(c,{...t,external:i})}if(Object.keys(o).length>0){const s=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:o}}return{schemas:a}}const r=new mh(t);return r.process(e),r.emit(e,t)}function Ct(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ct(o.element,r);case"object":{for(const a in o.shape)if(Ct(o.shape[a],r))return!0;return!1}case"union":{for(const a of o.options)if(Ct(a,r))return!0;return!1}case"intersection":return Ct(o.left,r)||Ct(o.right,r);case"tuple":{for(const a of o.items)if(Ct(a,r))return!0;return!!(o.rest&&Ct(o.rest,r))}case"record":return Ct(o.keyType,r)||Ct(o.valueType,r);case"map":return Ct(o.keyType,r)||Ct(o.valueType,r);case"set":return Ct(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ct(o.innerType,r);case"lazy":return Ct(o.getter(),r);case"default":return Ct(o.innerType,r);case"prefault":return Ct(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ct(o.in,r)||Ct(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const x3=K("ZodISODateTime",(e,t)=>{Kw.init(e,t),ct.init(e,t)});function gh(e){return t3(x3,e)}const E3=K("ZodISODate",(e,t)=>{Yw.init(e,t),ct.init(e,t)});function $3(e){return r3(E3,e)}const R3=K("ZodISOTime",(e,t)=>{Qw.init(e,t),ct.init(e,t)});function P3(e){return n3(R3,e)}const M3=K("ZodISODuration",(e,t)=>{Xw.init(e,t),ct.init(e,t)});function O3(e){return o3(M3,e)}const os=K("ZodError",(e,t)=>{qp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>J1(e,r)},flatten:{value:r=>B1(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),A3=G1(os),N3=W1(os),q3=jp(os),_h=Up(os),rt=K("ZodType",(e,t)=>(Xe.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Nn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>A3(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>q3(e,r,n),e.parseAsync=async(r,n)=>N3(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_h(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(I9(r,n)),e.superRefine=r=>e.check(x9(r)),e.overwrite=r=>e.check(Yo(r)),e.optional=()=>ce(e),e.nullable=()=>Eh(e),e.nullish=()=>ce(Eh(e)),e.nonoptional=r=>y9(e,r),e.array=()=>L(e),e.or=r=>ae([e,r]),e.and=r=>vl(e,r),e.transform=r=>bl(e,Ih(r)),e.default=r=>m9(e,r),e.prefault=r=>_9(e,r),e.catch=r=>w9(e,r),e.pipe=r=>bl(e,r),e.readonly=()=>T9(e),e.describe=r=>{const n=e.clone();return Ko.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ko.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ko.get(e);const n=e.clone();return Ko.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),yh=K("_ZodString",(e,t)=>{fl.init(e,t),rt.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(h3(...n)),e.includes=(...n)=>e.check(g3(...n)),e.startsWith=(...n)=>e.check(_3(...n)),e.endsWith=(...n)=>e.check(y3(...n)),e.min=(...n)=>e.check(ns(...n)),e.max=(...n)=>e.check(hh(...n)),e.length=(...n)=>e.check(fh(...n)),e.nonempty=(...n)=>e.check(ns(1,...n)),e.lowercase=n=>e.check(f3(n)),e.uppercase=n=>e.check(m3(n)),e.trim=()=>e.check(w3()),e.normalize=(...n)=>e.check(v3(...n)),e.toLowerCase=()=>e.check(b3()),e.toUpperCase=()=>e.check(k3())}),L3=K("ZodString",(e,t)=>{fl.init(e,t),yh.init(e,t),e.email=r=>e.check(qb(j3,r)),e.url=r=>e.check(lh(wh,r)),e.jwt=r=>e.check(e3(X3,r)),e.emoji=r=>e.check(zb(U3,r)),e.guid=r=>e.check(ih(vh,r)),e.uuid=r=>e.check(Lb(as,r)),e.uuidv4=r=>e.check(jb(as,r)),e.uuidv6=r=>e.check(Db(as,r)),e.uuidv7=r=>e.check(Ub(as,r)),e.nanoid=r=>e.check(Fb(z3,r)),e.guid=r=>e.check(ih(vh,r)),e.cuid=r=>e.check(Vb(F3,r)),e.cuid2=r=>e.check(Zb(V3,r)),e.ulid=r=>e.check(Hb(Z3,r)),e.base64=r=>e.check(ch(bh,r)),e.base64url=r=>e.check(Qb(Y3,r)),e.xid=r=>e.check(Bb(H3,r)),e.ksuid=r=>e.check(Jb(B3,r)),e.ipv4=r=>e.check(Gb(J3,r)),e.ipv6=r=>e.check(Wb(G3,r)),e.cidrv4=r=>e.check(Kb(W3,r)),e.cidrv6=r=>e.check(Yb(K3,r)),e.e164=r=>e.check(Xb(Q3,r)),e.datetime=r=>e.check(gh(r)),e.date=r=>e.check($3(r)),e.time=r=>e.check(P3(r)),e.duration=r=>e.check(O3(r))});function d(e){return Nb(L3,e)}const ct=K("ZodStringFormat",(e,t)=>{ot.init(e,t),yh.init(e,t)}),j3=K("ZodEmail",(e,t)=>{zw.init(e,t),ct.init(e,t)}),vh=K("ZodGUID",(e,t)=>{Dw.init(e,t),ct.init(e,t)}),as=K("ZodUUID",(e,t)=>{Uw.init(e,t),ct.init(e,t)}),wh=K("ZodURL",(e,t)=>{Fw.init(e,t),ct.init(e,t)});function D3(e){return lh(wh,e)}const U3=K("ZodEmoji",(e,t)=>{Vw.init(e,t),ct.init(e,t)}),z3=K("ZodNanoID",(e,t)=>{Zw.init(e,t),ct.init(e,t)}),F3=K("ZodCUID",(e,t)=>{Hw.init(e,t),ct.init(e,t)}),V3=K("ZodCUID2",(e,t)=>{Bw.init(e,t),ct.init(e,t)}),Z3=K("ZodULID",(e,t)=>{Jw.init(e,t),ct.init(e,t)}),H3=K("ZodXID",(e,t)=>{Gw.init(e,t),ct.init(e,t)}),B3=K("ZodKSUID",(e,t)=>{Ww.init(e,t),ct.init(e,t)}),J3=K("ZodIPv4",(e,t)=>{eb.init(e,t),ct.init(e,t)}),G3=K("ZodIPv6",(e,t)=>{tb.init(e,t),ct.init(e,t)}),W3=K("ZodCIDRv4",(e,t)=>{rb.init(e,t),ct.init(e,t)}),K3=K("ZodCIDRv6",(e,t)=>{nb.init(e,t),ct.init(e,t)}),bh=K("ZodBase64",(e,t)=>{ob.init(e,t),ct.init(e,t)});function kh(e){return ch(bh,e)}const Y3=K("ZodBase64URL",(e,t)=>{sb.init(e,t),ct.init(e,t)}),Q3=K("ZodE164",(e,t)=>{ib.init(e,t),ct.init(e,t)}),X3=K("ZodJWT",(e,t)=>{cb.init(e,t),ct.init(e,t)}),yl=K("ZodNumber",(e,t)=>{Wp.init(e,t),rt.init(e,t),e.gt=(n,o)=>e.check(dh(n,o)),e.gte=(n,o)=>e.check(_l(n,o)),e.min=(n,o)=>e.check(_l(n,o)),e.lt=(n,o)=>e.check(uh(n,o)),e.lte=(n,o)=>e.check(gl(n,o)),e.max=(n,o)=>e.check(gl(n,o)),e.int=n=>e.check(Th(n)),e.safe=n=>e.check(Th(n)),e.positive=n=>e.check(dh(0,n)),e.nonnegative=n=>e.check(_l(0,n)),e.negative=n=>e.check(uh(0,n)),e.nonpositive=n=>e.check(gl(0,n)),e.multipleOf=(n,o)=>e.check(ph(n,o)),e.step=(n,o)=>e.check(ph(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function q(e){return a3(yl,e)}const e9=K("ZodNumberFormat",(e,t)=>{ub.init(e,t),yl.init(e,t)});function Th(e){return i3(e9,e)}const t9=K("ZodBoolean",(e,t)=>{db.init(e,t),rt.init(e,t)});function _e(e){return l3(t9,e)}const r9=K("ZodNull",(e,t)=>{pb.init(e,t),rt.init(e,t)});function Qo(e){return c3(r9,e)}const n9=K("ZodAny",(e,t)=>{hb.init(e,t),rt.init(e,t)});function ut(){return u3(n9)}const o9=K("ZodUnknown",(e,t)=>{fb.init(e,t),rt.init(e,t)});function Te(){return d3(o9)}const a9=K("ZodNever",(e,t)=>{mb.init(e,t),rt.init(e,t)});function s9(e){return p3(a9,e)}const i9=K("ZodArray",(e,t)=>{gb.init(e,t),rt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ns(r,n)),e.nonempty=r=>e.check(ns(1,r)),e.max=(r,n)=>e.check(hh(r,n)),e.length=(r,n)=>e.check(fh(r,n)),e.unwrap=()=>e.element});function L(e,t){return T3(i9,e,t)}const Ch=K("ZodObject",(e,t)=>{_b.init(e,t),rt.init(e,t),He(e,"shape",()=>t.shape),e.keyof=()=>le(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Te()}),e.loose=()=>e.clone({...e._zod.def,catchall:Te()}),e.strict=()=>e.clone({...e._zod.def,catchall:s9()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F1(e,r),e.merge=r=>V1(e,r),e.pick=r=>U1(e,r),e.omit=r=>z1(e,r),e.partial=(...r)=>Z1(xh,e,r[0]),e.required=(...r)=>H1($h,e,r[0])});function T(e,t){const r={type:"object",get shape(){return Ya(this,"shape",{...e}),this.shape},...ge(t)};return new Ch(r)}function dt(e,t){return new Ch({type:"object",get shape(){return Ya(this,"shape",{...e}),this.shape},catchall:Te(),...ge(t)})}const Sh=K("ZodUnion",(e,t)=>{Xp.init(e,t),rt.init(e,t),e.options=t.options});function ae(e,t){return new Sh({type:"union",options:e,...ge(t)})}const l9=K("ZodDiscriminatedUnion",(e,t)=>{Sh.init(e,t),yb.init(e,t)});function Le(e,t,r){return new l9({type:"union",options:t,discriminator:e,...ge(r)})}const c9=K("ZodIntersection",(e,t)=>{vb.init(e,t),rt.init(e,t)});function vl(e,t){return new c9({type:"intersection",left:e,right:t})}const u9=K("ZodRecord",(e,t)=>{wb.init(e,t),rt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function pe(e,t,r){return new u9({type:"record",keyType:e,valueType:t,...ge(r)})}const wl=K("ZodEnum",(e,t)=>{bb.init(e,t),rt.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const a={};for(const i of n)if(r.has(i))a[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new wl({...t,checks:[],...ge(o),entries:a})},e.exclude=(n,o)=>{const a={...t.entries};for(const i of n)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new wl({...t,checks:[],...ge(o),entries:a})}});function le(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new wl({type:"enum",entries:r,...ge(t)})}const d9=K("ZodLiteral",(e,t)=>{kb.init(e,t),rt.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function M(e,t){return new d9({type:"literal",values:Array.isArray(e)?e:[e],...ge(t)})}const p9=K("ZodTransform",(e,t)=>{Tb.init(e,t),rt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(Wo(a,r.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(Wo(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function Ih(e){return new p9({type:"transform",transform:e})}const xh=K("ZodOptional",(e,t)=>{Cb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ce(e){return new xh({type:"optional",innerType:e})}const h9=K("ZodNullable",(e,t)=>{Sb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Eh(e){return new h9({type:"nullable",innerType:e})}const f9=K("ZodDefault",(e,t)=>{Ib.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function m9(e,t){return new f9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const g9=K("ZodPrefault",(e,t)=>{xb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _9(e,t){return new g9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const $h=K("ZodNonOptional",(e,t)=>{Eb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function y9(e,t){return new $h({type:"nonoptional",innerType:e,...ge(t)})}const v9=K("ZodCatch",(e,t)=>{$b.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function w9(e,t){return new v9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const b9=K("ZodPipe",(e,t)=>{Rb.init(e,t),rt.init(e,t),e.in=t.in,e.out=t.out});function bl(e,t){return new b9({type:"pipe",in:e,out:t})}const k9=K("ZodReadonly",(e,t)=>{Pb.init(e,t),rt.init(e,t)});function T9(e){return new k9({type:"readonly",innerType:e})}const C9=K("ZodLazy",(e,t)=>{Mb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function ss(e){return new C9({type:"lazy",getter:e})}const kl=K("ZodCustom",(e,t)=>{Ob.init(e,t),rt.init(e,t)});function S9(e){const t=new Xt({check:"custom"});return t._zod.check=e,t}function Rh(e,t){return C3(kl,e??(()=>!0),t)}function I9(e,t={}){return S3(kl,e,t)}function x9(e){const t=S9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Wo(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Wo(o))}},e(r.value,r)));return t}function is(e,t={error:`Input not instance of ${e.name}`}){const r=new kl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...ge(t)});return r._zod.bag.Class=e,r}function Ph(e,t){return bl(Ih(e),t)}const Mh={custom:"custom"};function Oh(e){return s3(yl,e)}var Ze;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const a={};for(const i of o)a[i]=i;return a},e.getValidEnumValues=o=>{const a=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),i={};for(const s of a)i[s]=o[s];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(a){return o[a]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const a=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&a.push(i);return a},e.find=(o,a)=>{for(const i of o)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,a=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a})(Ze||(Ze={}));var Ah;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ah||(Ah={}));const he=Ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hn=e=>{switch(typeof e){case"undefined":return he.undefined;case"string":return he.string;case"number":return Number.isNaN(e)?he.nan:he.number;case"boolean":return he.boolean;case"function":return he.function;case"bigint":return he.bigint;case"symbol":return he.symbol;case"object":return Array.isArray(e)?he.array:e===null?he.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?he.promise:typeof Map<"u"&&e instanceof Map?he.map:typeof Set<"u"&&e instanceof Set?he.set:typeof Date<"u"&&e instanceof Date?he.date:he.object;default:return he.unknown}},ne=Ze.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Yr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let s=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Yr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ze.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const a=o.path[0];r[a]=r[a]||[],r[a].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Yr.create=e=>new Yr(e);const Tl=(e,t)=>{let r;switch(e.code){case ne.invalid_type:e.received===he.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ze.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ze.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ze.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${Ze.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ze.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ne.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ne.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ze.assertNever(e)}return{message:r}};let E9=Tl;function $9(){return E9}const R9=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,a=[...r,...o.path||[]],i={...o,path:a};if(o.message!==void 0)return{...o,path:a,message:o.message};let s="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)s=c(i,{data:t,defaultError:s}).message;return{...o,path:a,message:s}};function ue(e,t){const r=$9(),n=R9({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Tl?void 0:Tl].filter(o=>!!o)});e.common.issues.push(n)}class Wt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return xe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const a=await o.key,i=await o.value;n.push({key:a,value:i})}return Wt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:a,value:i}=o;if(a.status==="aborted"||i.status==="aborted")return xe;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[a.value]=i.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),Xo=e=>({status:"dirty",value:e}),mr=e=>({status:"valid",value:e}),Nh=e=>e.status==="aborted",qh=e=>e.status==="dirty",uo=e=>e.status==="valid",ls=e=>typeof Promise<"u"&&e instanceof Promise;var ve;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ve||(ve={}));class zr{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Lh=(e,t)=>{if(uo(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Yr(e.common.issues);return this._error=r,this._error}}};function Pe(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,s)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??n??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??r??s.defaultError}},description:o}}class je{get description(){return this._def.description}_getType(t){return hn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:hn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Wt,ctx:{common:t.parent.common,data:t.data,parsedType:hn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(ls(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hn(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Lh(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hn(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return uo(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>uo(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hn(t)},o=this._parse({data:t,path:n.path,parent:n}),a=await(ls(o)?o:Promise.resolve(o));return Lh(n,a)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,a)=>{const i=t(o),s=()=>a.addIssue({code:ne.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(s(),!1)):i?!0:(s(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new mo({schema:this,typeName:oe.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return mn.create(this,this._def)}nullable(){return go.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fr.create(this)}promise(){return hs.create(this,this._def)}or(t){return us.create([this,t],this._def)}and(t){return ds.create(this,t,this._def)}transform(t){return new mo({...Pe(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new El({...Pe(this._def),innerType:this,defaultValue:r,typeName:oe.ZodDefault})}brand(){return new X9({typeName:oe.ZodBranded,type:this,...Pe(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new $l({...Pe(this._def),innerType:this,catchValue:r,typeName:oe.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Rl.create(this,t)}readonly(){return Pl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const P9=/^c[^\s-]{8,}$/i,M9=/^[0-9a-z]+$/,O9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A9=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,N9=/^[a-z0-9_-]{21}$/i,q9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L9=/^[-+]?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)?)??$/,j9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Cl;const U9=/^(?:(?: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])$/,z9=/^(?:(?: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])$/,F9=/^(([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]))$/,V9=/^(([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])$/,Z9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jh="((\\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])))",B9=new RegExp(`^${jh}$`);function Dh(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function J9(e){return new RegExp(`^${Dh(e)}$`)}function G9(e){let t=`${jh}T${Dh(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function W9(e,t){return!!((t==="v4"||!t)&&U9.test(e)||(t==="v6"||!t)&&F9.test(e))}function K9(e,t){if(!q9.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Y9(e,t){return!!((t==="v4"||!t)&&z9.test(e)||(t==="v6"||!t)&&V9.test(e))}class Qr extends je{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==he.string){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.string,received:a.parsedType}),xe}const n=new Wt;let o;for(const a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=t.data.length>a.value,s=t.data.length<a.value;(i||s)&&(o=this._getOrReturnCtx(t,o),i?ue(o,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&ue(o,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")j9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"email",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Cl||(Cl=new RegExp(D9,"u")),Cl.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"emoji",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")A9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"uuid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")N9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"nanoid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")P9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cuid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")M9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cuid2",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")O9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"ulid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ue(o,{validation:"url",code:ne.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"regex",code:ne.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?G9(a).test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?B9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?J9(a).test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?L9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"duration",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?W9(t.data,a.version)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"ip",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?K9(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"jwt",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Y9(t.data,a.version)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cidr",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Z9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"base64",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?H9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"base64url",code:ne.invalid_string,message:a.message}),n.dirty()):Ze.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:ne.invalid_string,...ve.errToObj(n)})}_addCheck(t){return new Qr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ve.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ve.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ve.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ve.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ve.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ve.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ve.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ve.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ve.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ve.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ve.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ve.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ve.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ve.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ve.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ve.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ve.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ve.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ve.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ve.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ve.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ve.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ve.errToObj(r)})}nonempty(t){return this.min(1,ve.errToObj(t))}trim(){return new Qr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}Qr.create=e=>new Qr({checks:[],typeName:oe.ZodString,coerce:e?.coerce??!1,...Pe(e)});function Q9(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}class po extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==he.number){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.number,received:a.parsedType}),xe}let n;const o=new Wt;for(const a of this._def.checks)a.kind==="int"?Ze.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.invalid_type,expected:"integer",received:"float",message:a.message}),o.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="multipleOf"?Q9(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_finite,message:a.message}),o.dirty()):Ze.assertNever(a);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ve.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ve.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ve.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ve.toString(r))}setLimit(t,r,n,o){return new po({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ve.toString(o)}]})}_addCheck(t){return new po({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ve.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ve.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ve.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ve.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ve.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ve.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ze.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}}po.create=e=>new po({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class ea extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==he.bigint)return this._getInvalidInput(t);let n;const o=new Wt;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):Ze.assertNever(a);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ue(r,{code:ne.invalid_type,expected:he.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,ve.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ve.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ve.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ve.toString(r))}setLimit(t,r,n,o){return new ea({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ve.toString(o)}]})}_addCheck(t){return new ea({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ve.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}ea.create=e=>new ea({checks:[],typeName:oe.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});class Sl extends je{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==he.boolean){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.boolean,received:n.parsedType}),xe}return mr(t.data)}}Sl.create=e=>new Sl({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});class cs extends je{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==he.date){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.date,received:a.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_date}),xe}const n=new Wt;let o;for(const a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Ze.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ve.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ve.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}cs.create=e=>new cs({checks:[],coerce:e?.coerce||!1,typeName:oe.ZodDate,...Pe(e)});class Uh extends je{_parse(t){if(this._getType(t)!==he.symbol){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.symbol,received:n.parsedType}),xe}return mr(t.data)}}Uh.create=e=>new Uh({typeName:oe.ZodSymbol,...Pe(e)});class zh extends je{_parse(t){if(this._getType(t)!==he.undefined){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.undefined,received:n.parsedType}),xe}return mr(t.data)}}zh.create=e=>new zh({typeName:oe.ZodUndefined,...Pe(e)});class Fh extends je{_parse(t){if(this._getType(t)!==he.null){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.null,received:n.parsedType}),xe}return mr(t.data)}}Fh.create=e=>new Fh({typeName:oe.ZodNull,...Pe(e)});class Il extends je{constructor(){super(...arguments),this._any=!0}_parse(t){return mr(t.data)}}Il.create=e=>new Il({typeName:oe.ZodAny,...Pe(e)});class Vh extends je{constructor(){super(...arguments),this._unknown=!0}_parse(t){return mr(t.data)}}Vh.create=e=>new Vh({typeName:oe.ZodUnknown,...Pe(e)});class fn extends je{_parse(t){const r=this._getOrReturnCtx(t);return ue(r,{code:ne.invalid_type,expected:he.never,received:r.parsedType}),xe}}fn.create=e=>new fn({typeName:oe.ZodNever,...Pe(e)});class Zh extends je{_parse(t){if(this._getType(t)!==he.undefined){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.void,received:n.parsedType}),xe}return mr(t.data)}}Zh.create=e=>new Zh({typeName:oe.ZodVoid,...Pe(e)});class Fr extends je{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==he.array)return ue(r,{code:ne.invalid_type,expected:he.array,received:r.parsedType}),xe;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,s=r.data.length<o.exactLength.value;(i||s)&&(ue(r,{code:i?ne.too_big:ne.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(ue(r,{code:ne.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(ue(r,{code:ne.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,s)=>o.type._parseAsync(new zr(r,i,r.path,s)))).then(i=>Wt.mergeArray(n,i));const a=[...r.data].map((i,s)=>o.type._parseSync(new zr(r,i,r.path,s)));return Wt.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new Fr({...this._def,minLength:{value:t,message:ve.toString(r)}})}max(t,r){return new Fr({...this._def,maxLength:{value:t,message:ve.toString(r)}})}length(t,r){return new Fr({...this._def,exactLength:{value:t,message:ve.toString(r)}})}nonempty(t){return this.min(1,t)}}Fr.create=(e,t)=>new Fr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...Pe(t)});function ho(e){if(e instanceof bt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=mn.create(ho(n))}return new bt({...e._def,shape:()=>t})}else return e instanceof Fr?new Fr({...e._def,type:ho(e.element)}):e instanceof mn?mn.create(ho(e.unwrap())):e instanceof go?go.create(ho(e.unwrap())):e instanceof Ln?Ln.create(e.items.map(t=>ho(t))):e}class bt extends je{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Ze.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==he.object){const c=this._getOrReturnCtx(t);return ue(c,{code:ne.invalid_type,expected:he.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:a,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof fn&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||s.push(c);const l=[];for(const c of i){const u=a[c],h=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new zr(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof fn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")s.length>0&&(ue(o,{code:ne.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of s){const h=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new zr(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,p=await u.value;c.push({key:h,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Wt.mergeObjectSync(n,c)):Wt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return ve.errToObj,new bt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ve.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new bt({...this._def,unknownKeys:"strip"})}passthrough(){return new bt({...this._def,unknownKeys:"passthrough"})}extend(t){return new bt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new bt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:oe.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new bt({...this._def,catchall:t})}pick(t){const r={};for(const n of Ze.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new bt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ze.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new bt({...this._def,shape:()=>r})}deepPartial(){return ho(this)}partial(t){const r={};for(const n of Ze.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new bt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ze.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof mn;)a=a._def.innerType;r[n]=a}return new bt({...this._def,shape:()=>r})}keyof(){return Gh(Ze.objectKeys(this.shape))}}bt.create=(e,t)=>new bt({shape:()=>e,unknownKeys:"strip",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)}),bt.strictCreate=(e,t)=>new bt({shape:()=>e,unknownKeys:"strict",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)}),bt.lazycreate=(e,t)=>new bt({shape:e,unknownKeys:"strip",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)});class us extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(a){for(const s of a)if(s.result.status==="valid")return s.result;for(const s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(s=>new Yr(s.ctx.common.issues));return ue(r,{code:ne.invalid_union,unionErrors:i}),xe}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let a;const i=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const s=i.map(l=>new Yr(l));return ue(r,{code:ne.invalid_union,unionErrors:s}),xe}}get options(){return this._def.options}}us.create=(e,t)=>new us({options:e,typeName:oe.ZodUnion,...Pe(t)});function xl(e,t){const r=hn(e),n=hn(t);if(e===t)return{valid:!0,data:e};if(r===he.object&&n===he.object){const o=Ze.objectKeys(t),a=Ze.objectKeys(e).filter(s=>o.indexOf(s)!==-1),i={...e,...t};for(const s of a){const l=xl(e[s],t[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(r===he.array&&n===he.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let a=0;a<e.length;a++){const i=e[a],s=t[a],l=xl(i,s);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===he.date&&n===he.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ds extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(a,i)=>{if(Nh(a)||Nh(i))return xe;const s=xl(a.value,i.value);return s.valid?((qh(a)||qh(i))&&r.dirty(),{status:r.value,value:s.data}):(ue(n,{code:ne.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>o(a,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ds.create=(e,t,r)=>new ds({left:e,right:t,typeName:oe.ZodIntersection,...Pe(r)});class Ln extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.array)return ue(n,{code:ne.invalid_type,expected:he.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return ue(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(ue(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,s)=>{const l=this._def.items[s]||this._def.rest;return l?l._parse(new zr(n,i,n.path,s)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Wt.mergeArray(r,i)):Wt.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new Ln({...this._def,rest:t})}}Ln.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ln({items:e,typeName:oe.ZodTuple,rest:null,...Pe(t)})};class ps extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.object)return ue(n,{code:ne.invalid_type,expected:he.object,received:n.parsedType}),xe;const o=[],a=this._def.keyType,i=this._def.valueType;for(const s in n.data)o.push({key:a._parse(new zr(n,s,n.path,s)),value:i._parse(new zr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?Wt.mergeObjectAsync(r,o):Wt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof je?new ps({keyType:t,valueType:r,typeName:oe.ZodRecord,...Pe(n)}):new ps({keyType:Qr.create(),valueType:t,typeName:oe.ZodRecord,...Pe(r)})}}class Hh extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.map)return ue(n,{code:ne.invalid_type,expected:he.map,received:n.parsedType}),xe;const o=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([s,l],c)=>({key:o._parse(new zr(n,s,n.path,[c,"key"])),value:a._parse(new zr(n,l,n.path,[c,"value"]))}));if(n.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value)}return{status:r.value,value:s}})}else{const s=new Map;for(const l of i){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value)}return{status:r.value,value:s}}}}Hh.create=(e,t,r)=>new Hh({valueType:t,keyType:e,typeName:oe.ZodMap,...Pe(r)});class ta extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.set)return ue(n,{code:ne.invalid_type,expected:he.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ue(n,{code:ne.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(ue(n,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return xe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const s=[...n.data.values()].map((l,c)=>a._parse(new zr(n,l,n.path,c)));return n.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(t,r){return new ta({...this._def,minSize:{value:t,message:ve.toString(r)}})}max(t,r){return new ta({...this._def,maxSize:{value:t,message:ve.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}ta.create=(e,t)=>new ta({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Pe(t)});class Bh extends je{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Bh.create=(e,t)=>new Bh({getter:e,typeName:oe.ZodLazy,...Pe(t)});class Jh extends je{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ue(r,{received:r.data,code:ne.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}Jh.create=(e,t)=>new Jh({value:e,typeName:oe.ZodLiteral,...Pe(t)});function Gh(e,t){return new fo({values:e,typeName:oe.ZodEnum,...Pe(t)})}class fo extends je{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ue(r,{expected:Ze.joinValues(n),received:r.parsedType,code:ne.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return ue(r,{received:r.data,code:ne.invalid_enum_value,options:n}),xe}return mr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return fo.create(t,{...this._def,...r})}exclude(t,r=this._def){return fo.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}fo.create=Gh;class Wh extends je{_parse(t){const r=Ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==he.string&&n.parsedType!==he.number){const o=Ze.objectValues(r);return ue(n,{expected:Ze.joinValues(o),received:n.parsedType,code:ne.invalid_type}),xe}if(this._cache||(this._cache=new Set(Ze.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ze.objectValues(r);return ue(n,{received:n.data,code:ne.invalid_enum_value,options:o}),xe}return mr(t.data)}get enum(){return this._def.values}}Wh.create=(e,t)=>new Wh({values:e,typeName:oe.ZodNativeEnum,...Pe(t)});class hs extends je{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==he.promise&&r.common.async===!1)return ue(r,{code:ne.invalid_type,expected:he.promise,received:r.parsedType}),xe;const n=r.parsedType===he.promise?r.data:Promise.resolve(r.data);return mr(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}hs.create=(e,t)=>new hs({type:e,typeName:oe.ZodPromise,...Pe(t)});class mo extends je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,a={addIssue:i=>{ue(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){const i=o.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async s=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?Xo(l.value):l});{if(r.value==="aborted")return xe;const s=this._def.schema._parseSync({data:i,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"||r.value==="dirty"?Xo(s.value):s}}if(o.type==="refinement"){const i=s=>{const l=o.refinement(s,a);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:(s.status==="dirty"&&r.dirty(),i(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?xe:(s.status==="dirty"&&r.dirty(),i(s.value).then(()=>({status:r.value,value:s.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!uo(i))return xe;const s=o.transform(i.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>uo(i)?Promise.resolve(o.transform(i.value,a)).then(s=>({status:r.value,value:s})):xe);Ze.assertNever(o)}}mo.create=(e,t,r)=>new mo({schema:e,typeName:oe.ZodEffects,effect:t,...Pe(r)}),mo.createWithPreprocess=(e,t,r)=>new mo({schema:t,effect:{type:"preprocess",transform:e},typeName:oe.ZodEffects,...Pe(r)});class mn extends je{_parse(t){return this._getType(t)===he.undefined?mr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mn.create=(e,t)=>new mn({innerType:e,typeName:oe.ZodOptional,...Pe(t)});class go extends je{_parse(t){return this._getType(t)===he.null?mr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}go.create=(e,t)=>new go({innerType:e,typeName:oe.ZodNullable,...Pe(t)});class El extends je{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===he.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}El.create=(e,t)=>new El({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pe(t)});class $l extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ls(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}$l.create=(e,t)=>new $l({innerType:e,typeName:oe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pe(t)});class Kh extends je{_parse(t){if(this._getType(t)!==he.nan){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}Kh.create=e=>new Kh({typeName:oe.ZodNaN,...Pe(e)});class X9 extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Rl extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?xe:a.status==="dirty"?(r.dirty(),Xo(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?xe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new Rl({in:t,out:r,typeName:oe.ZodPipeline})}}class Pl extends je{_parse(t){const r=this._def.innerType._parse(t),n=o=>(uo(o)&&(o.value=Object.freeze(o.value)),o);return ls(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}Pl.create=(e,t)=>new Pl({innerType:e,typeName:oe.ZodReadonly,...Pe(t)});var oe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(oe||(oe={}));const be=Qr.create,gt=po.create,Ml=Sl.create,e4=Il.create;fn.create;const St=Fr.create,vt=bt.create,jn=us.create;ds.create,Ln.create;const t4=ps.create,Vr=fo.create;hs.create,mn.create,go.create;class Ol 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}}const Yh=10,r4=13,Dn=32;function Al(e){}function Qh(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=Al,onError:r=Al,onRetry:n=Al,onComment:o,maxBufferSize:a}=e,i=[];let s=0,l=!0,c,u="",h=0,p,m=!1;function f(y){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,y.charCodeAt(0)===239&&y.charCodeAt(1)===187&&y.charCodeAt(2)===191&&(y=y.slice(3))),i.length===0){const S=w(y);S!==""&&(i.push(S),s=S.length),b();return}if(y.indexOf(`
|
|
31
|
-
`)===-1&&y.indexOf("\r")===-1){i.push(y),s+=y.length,b();return}i.push(y);const _=i.join("");i.length=0,s=0;const k=w(_);k!==""&&(i.push(k),s=k.length),b()}function b(){a!==void 0&&(s+u.length<=a||(m=!0,i.length=0,s=0,c=void 0,u="",h=0,p=void 0,r(new Ol(`Buffered data exceeded max buffer size of ${a} characters`,{type:"max-buffer-size-exceeded"}))))}function w(y){let _=0;if(y.indexOf("\r")===-1){let k=y.indexOf(`
|
|
32
|
-
`,_);for(;k!==-1;){if(_===k){h>0&&t({id:c,event:p,data:u}),c=void 0,u="",h=0,p=void 0,_=k+1,k=y.indexOf(`
|
|
33
|
-
`,_);continue}const S=y.charCodeAt(_);if(Xh(y,_,S)){const E=y.charCodeAt(_+5)===Dn?_+6:_+5,R=y.slice(E,k);if(h===0&&y.charCodeAt(k+1)===Yh){t({id:c,event:p,data:R}),c=void 0,u="",p=void 0,_=k+2,k=y.indexOf(`
|
|
34
|
-
`,_);continue}u=h===0?R:`${u}
|
|
35
|
-
${R}`,h++}else ef(y,_,S)?p=y.slice(y.charCodeAt(_+6)===Dn?_+7:_+6,k)||void 0:C(y,_,k);_=k+1,k=y.indexOf(`
|
|
36
|
-
`,_)}return y.slice(_)}for(;_<y.length;){const k=y.indexOf("\r",_),S=y.indexOf(`
|
|
37
|
-
`,_);let E=-1;if(k!==-1&&S!==-1?E=k<S?k:S:k!==-1?k===y.length-1?E=-1:E=k:S!==-1&&(E=S),E===-1)break;C(y,_,E),_=E+1,y.charCodeAt(_-1)===r4&&y.charCodeAt(_)===Yh&&_++}return y.slice(_)}function C(y,_,k){if(_===k){g();return}const S=y.charCodeAt(_);if(Xh(y,_,S)){const z=y.charCodeAt(_+5)===Dn?_+6:_+5,ee=y.slice(z,k);u=h===0?ee:`${u}
|
|
38
|
-
${ee}`,h++;return}if(ef(y,_,S)){p=y.slice(y.charCodeAt(_+6)===Dn?_+7:_+6,k)||void 0;return}if(S===105&&y.charCodeAt(_+1)===100&&y.charCodeAt(_+2)===58){const z=y.slice(y.charCodeAt(_+3)===Dn?_+4:_+3,k);c=z.includes("\0")?void 0:z;return}if(S===58){if(o){const z=y.slice(_,k);o(z.slice(y.charCodeAt(_+1)===Dn?2:1))}return}const E=y.slice(_,k),R=E.indexOf(":");if(R===-1){v(E,"",E);return}const x=E.slice(0,R),N=E.charCodeAt(R+1)===Dn?2:1,U=E.slice(R+N);v(x,U,E)}function v(y,_,k){switch(y){case"event":p=_||void 0;break;case"data":u=h===0?_:`${u}
|
|
39
|
-
${_}`,h++;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new Ol(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:k}));break;default:r(new Ol(`Unknown field "${y.length>20?`${y.slice(0,20)}…`:y}"`,{type:"unknown-field",field:y,value:_,line:k}));break}}function g(){h>0&&t({id:c,event:p,data:u}),c=void 0,u="",h=0,p=void 0}function I(y={}){if(y.consume&&i.length>0){const _=i.join("");C(_,0,_.length)}l=!0,c=void 0,u="",h=0,p=void 0,i.length=0,s=0,m=!1}return{feed:f,reset:I}}function Xh(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function ef(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class _o extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let a;super({start(i){a=Qh({onEvent:s=>{i.enqueue(s)},onError(s){typeof t=="function"&&t(s),(t==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){a.feed(i)}})}}function It(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function n4({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},a={};for(const i of e)if(i.type==="provider"){const s=(n=r?.(i))!=null?n:i.id in t?t[i.id]:void 0;if(s==null)continue;o[i.name]=s,a[s]=i.name}return{toProviderToolName:i=>{var s;return(s=o[i])!=null?s:i},toCustomToolName:i=>{var s;return(s=a[i])!=null?s:i}}}async function o4(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(tf());return}const a=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(a),r?.removeEventListener("abort",s)},s=()=>{i(),o(tf())};r?.addEventListener("abort",s)})}function tf(){return new DOMException("Delay was aborted","AbortError")}var ra=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function yo(e){return Object.fromEntries([...e.headers])}var{btoa:a4,atob:s4}=globalThis;function Un(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=s4(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function gn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return a4(t)}function vo(e){return e instanceof Uint8Array?gn(e):e}function i4(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,a]of Object.entries(e))if(a!=null){if(Array.isArray(a)){if(a.length===1){n.append(o,a[0]);continue}const i=r?`${o}[]`:o;for(const s of a)n.append(i,s);continue}n.append(o,a)}return n}async function fs(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch{}}var rf="AI_DownloadError",nf=`vercel.ai.error.${rf}`,l4=Symbol.for(nf),of,af,Zt=class extends(af=we,of=l4,af){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:rf,message:o,cause:n}),this[of]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return we.hasMarker(e,nf)}};function c4(e=globalThis){return e.window!=null}function u4(e){let t;try{t=new URL(e)}catch{throw new Zt({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Zt({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname.toLowerCase().replace(/\.+$/,"");if(!r)throw new Zt({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Zt({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(p4(n))throw new Zt({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(sf(r)){if(lf(r))throw new Zt({url:e,message:`URL with IP address ${r} is not allowed`});return}}function sf(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function lf(e){const t=e.split(".").map(Number),[r,n,o]=t;return r===0||r===10||r===100&&n>=64&&n<=127||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===168||r===198&&(n===18||n===19)||r>=240}function d4(e){let t=e.toLowerCase();const r=t.indexOf("%");r!==-1&&(t=t.slice(0,r));const n=t.split("::");if(n.length>2)return null;const o=i=>{if(i==="")return[];const s=[],l=i.split(":");for(let c=0;c<l.length;c++){const u=l[c];if(u.includes(".")){if(c!==l.length-1||!sf(u))return null;const[h,p,m,f]=u.split(".").map(Number);s.push(h<<8|p,m<<8|f);continue}if(!/^[0-9a-f]{1,4}$/.test(u))return null;s.push(parseInt(u,16))}return s},a=o(n[0]);if(a===null)return null;if(n.length===2){const i=o(n[1]);if(i===null)return null;const s=8-a.length-i.length;return s<0?null:[...a,...new Array(s).fill(0),...i]}return a.length===8?a:null}function p4(e){const t=d4(e);if(t===null)return!0;const r=o=>t.slice(0,o).every(a=>a===0);if(r(7)&&(t[7]===0||t[7]===1)||(t[0]&65024)===64512||(t[0]&65472)===65152||(t[0]&65472)===65216||(t[0]&65280)===65280)return!0;if(r(6)||r(5)&&t[5]===65535||r(4)&&t[4]===65535&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===1){const o=t[6]>>8&255,a=t[6]&255,i=t[7]>>8&255,s=t[7]&255;return lf(`${o}.${a}.${i}.${s}`)}return!1}var h4=10;async function cf({url:e,headers:t,abortSignal:r,maxRedirects:n=h4}){const o={signal:r};t!==void 0&&(o.headers=t);let a=e;for(let i=0;i<=n;i++){u4(a);const s=await fetch(a,{...o,redirect:"manual"});if(s.type==="opaqueredirect"){if(!c4())throw new Zt({url:e,message:`Redirect from ${a} could not be validated and was blocked`});return await fetch(a,{...o,redirect:"follow"})}const l=s.headers.get("location");if(s.status>=300&&s.status<400&&l){await fs(s),a=new URL(l,a).toString();continue}return s}throw new Zt({url:e,message:`Too many redirects (max ${n})`})}var Nl=2*1024*1024*1024;async function ql({response:e,url:t,maxBytes:r=Nl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw await fs(e),new Zt({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const a=o.getReader(),i=[];let s=0;try{for(;;){const{done:u,value:h}=await a.read();if(u)break;if(s+=h.length,s>r)throw new Zt({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(h)}}finally{try{await a.cancel()}finally{a.releaseLock()}}const l=new Uint8Array(s);let c=0;for(const u of i)l.set(u,c),c+=u.length;return l}async function uf(e,t){var r,n;try{const o=await cf({url:e,abortSignal:t?.abortSignal});if(!o.ok)throw await fs(o),new Zt({url:e,statusCode:o.status,statusText:o.statusText});const a=await ql({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Nl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([a],i?{type:i}:void 0)}catch(o){throw Zt.isInstance(o)?o:new Zt({url:e,cause:o})}}var na=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,i=new Array(t);for(let s=0;s<t;s++)i[s]=r[Math.random()*a|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new rp({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Kt=na();function Ll(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function zn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var f4=["fetch failed","failed to fetch"],m4=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function g4(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&m4.includes(t))}function df({error:e,url:t,requestBodyValues:r}){if(zn(e))return e;if(e instanceof TypeError&&f4.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new tt({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return g4(e)?new tt({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function oa(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function _4(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function _n(e,...t){const r=new Headers(_4(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var pf="4.0.33",y4=()=>globalThis.fetch,ms=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:a=y4()})=>{try{const i=await a(e,{method:"GET",headers:_n(t,`ai-sdk/provider-utils/${pf}`,oa()),signal:o}),s=yo(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw zn(c)||tt.isInstance(c)?c:new tt({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(zn(l)||tt.isInstance(l))?l:new tt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(i){throw df({error:i,url:e,requestBodyValues:{}})}};function hf(e){return e!=null}function v4({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const a=n.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:a.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function w4({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Ka({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Ka({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables are not supported in this environment.`});if(e=process.env[t],e==null)throw new Ka({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ka({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function wo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function b4(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var k4=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,T4=/"(?: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 ff(e){const t=JSON.parse(e);return t===null||typeof t!="object"||k4.test(e)===!1&&T4.test(e)===!1?t:C4(t)}function C4(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const a=n[o];a&&typeof a=="object"&&t.push(a)}}}return e}function jl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ff(e)}try{return ff(e)}finally{Error.stackTraceLimit=t}}function Dl(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=Fn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Fn):Fn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Fn)),e.allOf!=null&&(e.allOf=e.allOf.map(Fn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Fn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Fn(t[r]);return e}function Fn(e){return typeof e=="boolean"?e:Dl(e)}var S4=Symbol("Let zodToJsonSchema decide on which parser to use"),mf={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"},I4=e=>typeof e=="string"?{...mf,name:e}:{...mf,...e};function or(){return{}}function x4(e,t){var r,n,o;const a={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==oe.ZodAny&&(a.items=Je(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(a.minItems=e.minLength.value),e.maxLength&&(a.maxItems=e.maxLength.value),e.exactLength&&(a.minItems=e.exactLength.value,a.maxItems=e.exactLength.value),a}function E4(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function $4(){return{type:"boolean"}}function gf(e,t){return Je(e.type._def,t)}var R4=(e,t)=>Je(e.innerType._def,t);function _f(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>_f(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return P4(e)}}var P4=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function M4(e,t){return{...Je(e.innerType._def,t),default:e.defaultValue()}}function O4(e,t){return t.effectStrategy==="input"?Je(e.schema._def,t):or()}function A4(e){return{type:"string",enum:Array.from(e.values)}}var N4=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function q4(e,t){const r=[Je(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Je(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(N4(o))n.push(...o.allOf);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...s}=o;a=s}n.push(a)}}),n.length?{allOf:n}:void 0}function L4(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ul=void 0,Cr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ul===void 0&&(Ul=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ul),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function yf(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Sr(r,"email",n.message,t);break;case"format:idn-email":Sr(r,"idn-email",n.message,t);break;case"pattern:zod":Yt(r,Cr.email,n.message,t);break}break;case"url":Sr(r,"uri",n.message,t);break;case"uuid":Sr(r,"uuid",n.message,t);break;case"regex":Yt(r,n.regex,n.message,t);break;case"cuid":Yt(r,Cr.cuid,n.message,t);break;case"cuid2":Yt(r,Cr.cuid2,n.message,t);break;case"startsWith":Yt(r,RegExp(`^${zl(n.value,t)}`),n.message,t);break;case"endsWith":Yt(r,RegExp(`${zl(n.value,t)}$`),n.message,t);break;case"datetime":Sr(r,"date-time",n.message,t);break;case"date":Sr(r,"date",n.message,t);break;case"time":Sr(r,"time",n.message,t);break;case"duration":Sr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{Yt(r,RegExp(zl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Sr(r,"ipv4",n.message,t),n.version!=="v4"&&Sr(r,"ipv6",n.message,t);break}case"base64url":Yt(r,Cr.base64url,n.message,t);break;case"jwt":Yt(r,Cr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Yt(r,Cr.ipv4Cidr,n.message,t),n.version!=="v4"&&Yt(r,Cr.ipv6Cidr,n.message,t);break}case"emoji":Yt(r,Cr.emoji(),n.message,t);break;case"ulid":{Yt(r,Cr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Sr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Yt(r,Cr.base64,n.message,t);break}}break}case"nanoid":Yt(r,Cr.nanoid,n.message,t)}return r}function zl(e,t){return t.patternStrategy==="escape"?D4(e):e}var j4=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function D4(e){let t="";for(let r=0;r<e.length;r++)j4.has(e[r])||(t+="\\"),t+=e[r];return t}function Sr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(a=>a.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function Yt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(a=>a.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:vf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=vf(t,n)}function vf(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let a="",i=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(i){a+=o[c],i=!1;continue}if(n.i){if(s){if(o[c].match(/[a-z]/)){l?(a+=o[c],a+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(a+=o[c],l=!0):a+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){a+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){a+=`(^|(?<=[\r
|
|
40
|
-
]))`;continue}else if(o[c]==="$"){a+=`($|(?=[\r
|
|
41
|
-
]))`;continue}}if(n.s&&o[c]==="."){a+=s?`${o[c]}\r
|
|
42
|
-
`:`[${o[c]}\r
|
|
43
|
-
]`;continue}a+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function wf(e,t){var r,n,o,a,i,s;const l={type:"object",additionalProperties:(r=Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===oe.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=yf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===oe.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===oe.ZodBranded&&e.keyType._def.type._def.typeName===oe.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:c,...u}=gf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function U4(e,t){if(t.mapStrategy==="record")return wf(e,t);const r=Je(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||or(),n=Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||or();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function z4(e){const t=e.values,n=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),o=Array.from(new Set(n.map(a=>typeof a)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function F4(){return{not:or()}}function V4(){return{type:"null"}}var Fl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Z4(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Fl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,a)=>{const i=Fl[a._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(a._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((a,i,s)=>s.indexOf(a)===i);return{type:o.length>1?o:o[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(a=>!n.includes(a))],[])};return H4(e,t)}var H4=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Je(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function B4(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Fl[e.innerType._def.typeName],"null"]};const r=Je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function J4(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function G4(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const i in o){let s=o[i];if(s===void 0||s._def===void 0)continue;const l=K4(s),c=Je(s._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);const a=W4(e,t);return a!==void 0&&(r.additionalProperties=a),r}function W4(e,t){if(e.catchall._def.typeName!=="ZodNever")return Je(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function K4(e){try{return e.isOptional()}catch{return!0}}var Y4=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Je(e.innerType._def,t);const n=Je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:or()},n]}:or()},Q4=(e,t)=>{if(t.pipeStrategy==="input")return Je(e.in._def,t);if(t.pipeStrategy==="output")return Je(e.out._def,t);const r=Je(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Je(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function X4(e,t){return Je(e.type._def,t)}function e6(e,t){const n={type:"array",uniqueItems:!0,items:Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function t6(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Je(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function r6(){return{not:or()}}function n6(){return or()}var o6=(e,t)=>Je(e.innerType._def,t),a6=(e,t,r)=>{switch(t){case oe.ZodString:return yf(e,r);case oe.ZodNumber:return J4(e);case oe.ZodObject:return G4(e,r);case oe.ZodBigInt:return E4(e);case oe.ZodBoolean:return $4();case oe.ZodDate:return _f(e,r);case oe.ZodUndefined:return r6();case oe.ZodNull:return V4();case oe.ZodArray:return x4(e,r);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Z4(e,r);case oe.ZodIntersection:return q4(e,r);case oe.ZodTuple:return t6(e,r);case oe.ZodRecord:return wf(e,r);case oe.ZodLiteral:return L4(e);case oe.ZodEnum:return A4(e);case oe.ZodNativeEnum:return z4(e);case oe.ZodNullable:return B4(e,r);case oe.ZodOptional:return Y4(e,r);case oe.ZodMap:return U4(e,r);case oe.ZodSet:return e6(e,r);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return X4(e,r);case oe.ZodNaN:case oe.ZodNever:return F4();case oe.ZodEffects:return O4(e,r);case oe.ZodAny:return or();case oe.ZodUnknown:return n6();case oe.ZodDefault:return M4(e,r);case oe.ZodBranded:return gf(e,r);case oe.ZodReadonly:return o6(e,r);case oe.ZodCatch:return R4(e,r);case oe.ZodPipeline:return Q4(e,r);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(n=>{})()}},s6=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Je(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==S4)return l}if(o&&!r){const l=i6(o,t);if(l!==void 0)return l}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=a6(e,e.typeName,t),s=typeof i=="function"?Je(i(),t):i;if(s&&l6(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return a.jsonSchema=s,l}return a.jsonSchema=s,s}var i6=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s6(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),or()):t.$refStrategy==="seen"?or():void 0}},l6=(e,t,r)=>(e.description&&(r.description=e.description),r),c6=e=>{const t=I4(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},u6=(e,t)=>{var r;const n=c6(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var p;return{...c,[u]:(p=Je(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:or()}},{}):void 0;const a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Je(e._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1))!=null?r:or(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s);const l=a===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...o,[a]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Vl=Symbol.for("vercel.ai.schema");function ye(e){let t;return()=>(t==null&&(t=e()),t)}function Vn(e,{validate:t}={}){return{[Vl]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function d6(e){return typeof e=="object"&&e!==null&&Vl in e&&e[Vl]===!0&&"jsonSchema"in e&&"validate"in e}function yn(e){return e==null?Vn({properties:{},additionalProperties:!1}):d6(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?me(e):p6(e):e()}function p6(e){return Vn(()=>Dl(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new An({value:t,cause:r.issues})}}})}function h6(e,t){var r;const n=(r=void 0)!=null?r:!1;return Vn(()=>u6(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const a=await e.safeParseAsync(o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function f6(e,t){var r;const n=(r=void 0)!=null?r:!1;return Vn(()=>Dl(I3(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const a=await _h(e,o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function m6(e){return"_zod"in e}function me(e,t){return m6(e)?f6(e):h6(e)}async function _t({value:e,schema:t,context:r}){const n=await ar({value:e,schema:t,context:r});if(!n.success)throw An.wrap({value:e,cause:n.error,context:r});return n.value}async function ar({value:e,schema:t,context:r}){const n=yn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:An.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:An.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function gs({text:e,schema:t}){try{const r=jl(e);return t==null?r:_t({value:r,schema:t})}catch(r){throw Wa.isInstance(r)||An.isInstance(r)?r:new Wa({text:e,cause:r})}}async function gr({text:e,schema:t}){try{const r=jl(e);return t==null?{success:!0,value:r,rawValue:r}:await ar({value:r,schema:t})}catch(r){return{success:!1,error:Wa.isInstance(r)?r:new Wa({text:e,cause:r}),rawValue:void 0}}}function bf(e){try{return jl(e),!0}catch{return!1}}function kf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await gr({text:r,schema:t}))}}))}async function Ir({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ar({value:t[e],schema:r});if(!n.success)throw new rp({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var g6=()=>globalThis.fetch,Ot=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>Cf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),Tf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>Cf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),Cf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=g6()})=>{try{const s=await i(e,{method:"POST",headers:_n(t,`ai-sdk/provider-utils/${pf}`,oa()),body:r.content,signal:a}),l=yo(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:r.values})}catch(u){throw zn(u)||tt.isInstance(u)?u:new tt({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(zn(c)||tt.isInstance(c))?c:new tt({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw df({error:s,url:e,requestBodyValues:r.values})}};function VR(e){return e}function Zl(e){return{...e,type:"dynamic"}}function _6({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l})}function sr({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function yt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var y6=new TextDecoder;async function Sf({response:e,url:t}){return y6.decode(await ql({response:e,url:t}))}var ir=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const i=await Sf({response:n,url:o}),s=yo(n);if(i.trim()==="")return{responseHeaders:s,value:new tt({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{const l=await gs({text:i,schema:e});return{responseHeaders:s,value:new tt({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new tt({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},_s=e=>async({response:t})=>{const r=yo(t);if(t.body==null)throw new C1({});return{responseHeaders:r,value:kf({stream:t.body,schema:e})}},At=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await Sf({response:t,url:r}),a=await gr({text:o,schema:e}),i=yo(t);if(!a.success)throw new tt({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},v6=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=yo(e);if(!e.body)throw new tt({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new tt({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function If(e){return e?.replace(/\/$/,"")}function w6(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*b6({execute:e,input:t,options:r}){const n=e(t,r);if(w6(n)){let o;for await(const a of n)o=a,yield{type:"preliminary",output:a};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function Hl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Bl,xf;function k6(){if(xf)return Bl;xf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,h)=>{for(var p in h)e(u,p,{get:h[p],enumerable:!0})},a=(u,h,p,m)=>{if(h&&typeof h=="object"||typeof h=="function")for(let f of r(h))!n.call(u,f)&&f!==p&&e(u,f,{get:()=>h[f],enumerable:!(m=t(h,f))||m.enumerable});return u},i=u=>a(e({},"__esModule",{value:!0}),u),s={};o(s,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Bl=i(s);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Bl}var Jl,Ef;function T6(){if(Ef)return Jl;Ef=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,h)=>{for(var p in h)e(u,p,{get:h[p],enumerable:!0})},a=(u,h,p,m)=>{if(h&&typeof h=="object"||typeof h=="function")for(let f of r(h))!n.call(u,f)&&f!==p&&e(u,f,{get:()=>h[f],enumerable:!(m=t(h,f))||m.enumerable});return u},i=u=>a(e({},"__esModule",{value:!0}),u),s={};o(s,{AccessTokenMissingError:()=>l,RefreshAccessTokenFailedError:()=>c}),Jl=i(s);class l extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}}class c extends Error{constructor(h){super("Failed to refresh authentication token.",{cause:h}),this.name="RefreshAccessTokenFailedError"}}return Jl}var Gl,$f;function C6(){if($f)return Gl;$f=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(m,f)=>{for(var b in f)e(m,b,{get:f[b],enumerable:!0})},a=(m,f,b,w)=>{if(f&&typeof f=="object"||typeof f=="function")for(let C of r(f))!n.call(m,C)&&C!==b&&e(m,C,{get:()=>f[C],enumerable:!(w=t(f,C))||w.enumerable});return m},i=m=>a(e({},"__esModule",{value:!0}),m),s={};o(s,{AccessTokenMissingError:()=>c.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>c.RefreshAccessTokenFailedError,getContext:()=>l.getContext,getVercelOidcToken:()=>u,getVercelOidcTokenSync:()=>h,getVercelToken:()=>p}),Gl=i(s);var l=k6(),c=T6();async function u(){return""}function h(){return""}async function p(){throw new Error("getVercelToken is not supported in browser environments")}return Gl}var Rf=C6(),S6="vercel.ai.gateway.error",Wl=Symbol.for(S6),Pf,Mf,kt=class _1 extends(Mf=Error,Pf=Wl,Mf){constructor({message:t,statusCode:r=500,cause:n,generationId:o,isRetryable:a=r!=null&&(r===408||r===409||r===429||r>=500)}){super(o?`${t} [${o}]`:t),this[Pf]=!0,this.statusCode=r,this.cause=n,this.generationId=o,this.isRetryable=a}static isInstance(t){return _1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Wl in t&&t[Wl]===!0}},Of="GatewayAuthenticationError",I6=`vercel.ai.gateway.error.${Of}`,Af=Symbol.for(I6),Nf,qf,Kl=class y1 extends(qf=kt,Nf=Af,qf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Nf]=!0,this.name=Of,this.type="authentication_error"}static isInstance(t){return kt.hasMarker(t)&&Af in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a,generationId:i}){let s;return t?s=`AI Gateway authentication failed: Invalid API key.
|
|
44
|
-
|
|
45
|
-
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
46
|
-
|
|
47
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?s=`AI Gateway authentication failed: Invalid OIDC token.
|
|
48
|
-
|
|
49
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
50
|
-
|
|
51
|
-
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:s=`AI Gateway authentication failed: No authentication provided.
|
|
52
|
-
|
|
53
|
-
Option 1 - API key:
|
|
54
|
-
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
55
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
56
|
-
|
|
57
|
-
Option 2 - OIDC token:
|
|
58
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new y1({message:s,statusCode:o,cause:a,generationId:i})}},Lf="GatewayInvalidRequestError",x6=`vercel.ai.gateway.error.${Lf}`,jf=Symbol.for(x6),Df,Uf,E6=class extends(Uf=kt,Df=jf,Uf){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Df]=!0,this.name=Lf,this.type="invalid_request_error"}static isInstance(e){return kt.hasMarker(e)&&jf in e}},zf="GatewayRateLimitError",$6=`vercel.ai.gateway.error.${zf}`,Ff=Symbol.for($6),Vf,Zf,R6=class extends(Zf=kt,Vf=Ff,Zf){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Vf]=!0,this.name=zf,this.type="rate_limit_exceeded"}static isInstance(e){return kt.hasMarker(e)&&Ff in e}},Hf="GatewayModelNotFoundError",P6=`vercel.ai.gateway.error.${Hf}`,Bf=Symbol.for(P6),M6=ye(()=>me(T({modelId:d()}))),Jf,Gf,O6=class extends(Gf=kt,Jf=Bf,Gf){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[Jf]=!0,this.name=Hf,this.type="model_not_found",this.modelId=r}static isInstance(e){return kt.hasMarker(e)&&Bf in e}},Wf="GatewayInternalServerError",A6=`vercel.ai.gateway.error.${Wf}`,Kf=Symbol.for(A6),Yf,Qf,Xf=class extends(Qf=kt,Yf=Kf,Qf){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Yf]=!0,this.name=Wf,this.type="internal_server_error"}static isInstance(e){return kt.hasMarker(e)&&Kf in e}},e0="GatewayFailedDependencyError",N6=`vercel.ai.gateway.error.${e0}`,t0=Symbol.for(N6),r0,n0,q6=class extends(n0=kt,r0=t0,n0){constructor({message:e="Failed dependency",statusCode:t=424,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[r0]=!0,this.name=e0,this.type="failed_dependency"}static isInstance(e){return kt.hasMarker(e)&&t0 in e}},o0="GatewayForbiddenError",L6=`vercel.ai.gateway.error.${o0}`,a0=Symbol.for(L6),s0,i0,j6=class extends(i0=kt,s0=a0,i0){constructor({message:e="Forbidden",statusCode:t=403,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[s0]=!0,this.name=o0,this.type="forbidden"}static isInstance(e){return kt.hasMarker(e)&&a0 in e}},l0="GatewayResponseError",D6=`vercel.ai.gateway.error.${l0}`,c0=Symbol.for(D6),u0,d0,U6=class extends(d0=kt,u0=c0,d0){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:a}={}){super({message:e,statusCode:t,cause:o,generationId:a}),this[u0]=!0,this.name=l0,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return kt.hasMarker(e)&&c0 in e}};async function p0({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var a;const i=await ar({value:e,schema:z6});if(!i.success){const h=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new U6({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:h})}const s=i.value,l=s.error.type,c=s.error.message,u=(a=s.generationId)!=null?a:void 0;switch(l){case"authentication_error":return Kl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new E6({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new R6({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const h=await ar({value:s.error.param,schema:M6});return new O6({message:c,statusCode:t,modelId:h.success?h.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Xf({message:c,statusCode:t,cause:n,generationId:u});case"failed_dependency":return new q6({message:c,statusCode:t,cause:n,generationId:u});case"forbidden":return new j6({message:c,statusCode:t,cause:n,generationId:u});default:return new Xf({message:c,statusCode:t,cause:n,generationId:u})}}var z6=ye(()=>me(T({error:T({message:d(),type:d().nullish(),param:Te().nullish(),code:ae([d(),q()]).nullish()}),generationId:d().nullish()})));function F6(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var h0="GatewayTimeoutError",V6=`vercel.ai.gateway.error.${h0}`,f0=Symbol.for(V6),m0,g0,_0=class v1 extends(g0=kt,m0=f0,g0){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[m0]=!0,this.name=h0,this.type="timeout_error"}static isInstance(t){return kt.hasMarker(t)&&f0 in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const a=`Gateway request timed out: ${t}
|
|
59
|
-
|
|
60
|
-
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`;return new v1({message:a,statusCode:r,cause:n,generationId:o})}};function y0(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Ht(e,t){var r;return kt.isInstance(e)?e:y0(e)?_0.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):tt.isInstance(e)?e.cause&&y0(e.cause)?_0.createTimeoutError({originalMessage:e.message,cause:e}):await p0({response:F6(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await p0({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var v0="ai-gateway-auth-method";async function _r(e){const t=await ar({value:e[v0],schema:Z6});return t.success?t.value:void 0}var Z6=ye(()=>me(ae([M("api-key"),M("oidc")]))),H6=["embedding","image","language","reranking","speech","transcription","video"],w0=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await ms({url:`${this.config.baseURL}/config`,headers:await yt(this.config.headers()),successfulResponseHandler:At(B6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Ht(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await ms({url:`${e.origin}/v1/credits`,headers:await yt(this.config.headers()),successfulResponseHandler:At(J6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Ht(e)}}},B6=ye(()=>me(T({models:L(T({id:d(),name:d(),description:d().nullish(),pricing:T({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:M("v3"),provider:d(),modelId:d()}),modelType:d().nullish()})).transform(e=>e.filter(t=>t.modelType==null||H6.includes(t.modelType)))}))),J6=ye(()=>me(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),G6=class{constructor(e){this.config=e}async getSpendReport(e){try{const t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));const{value:n}=await ms({url:`${t.origin}/v1/report?${r.toString()}`,headers:await yt(this.config.headers()),successfulResponseHandler:At(W6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await Ht(t)}}},W6=ye(()=>me(T({results:L(T({day:d().optional(),hour:d().optional(),user:d().optional(),model:d().optional(),tag:d().optional(),provider:d().optional(),credential_type:le(["byok","system"]).optional(),total_cost:q(),market_cost:q().optional(),input_tokens:q().optional(),output_tokens:q().optional(),cached_input_tokens:q().optional(),cache_creation_input_tokens:q().optional(),reasoning_tokens:q().optional(),request_count:q().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:a,cache_creation_input_tokens:i,reasoning_tokens:s,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...r!==void 0?{marketCost:r}:{},...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...a!==void 0?{cachedInputTokens:a}:{},...i!==void 0?{cacheCreationInputTokens:i}:{},...s!==void 0?{reasoningTokens:s}:{},...l!==void 0?{requestCount:l}:{}})))}))),K6=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await ms({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await yt(this.config.headers()),successfulResponseHandler:At(Y6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await Ht(t)}}},Y6=ye(()=>me(T({data:T({id:d(),total_cost:q(),upstream_inference_cost:q(),usage:q(),created_at:d(),model:d(),is_byok:_e(),provider_name:d(),streamed:_e(),finish_reason:d(),latency:q(),generation_time:q(),native_tokens_prompt:q(),native_tokens_completion:q(),native_tokens_reasoning:q(),native_tokens_cached:q(),native_tokens_cache_creation:q(),billable_web_search_calls:q()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:a,generation_time:i,native_tokens_prompt:s,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:h,billable_web_search_calls:p,...m})=>({...m,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:a,generationTime:i,promptTokens:s,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:h,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),Q6=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await yt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:s}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await yt(this.config.o11yHeaders)),body:t,successfulResponseHandler:At(ut()),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:a,body:s},warnings:r}}catch(a){throw await Ht(a,await _r(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await yt(this.config.headers());try{const{value:a,responseHeaders:i}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await yt(this.config.o11yHeaders)),body:t,successfulResponseHandler:_s(ut()),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:s=>s}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(s){r.length>0&&s.enqueue({type:"stream-start",warnings:r})},transform(s,l){if(s.success){const c=s.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(s.error)}})),request:{body:t},response:{headers:i}}}catch(a){throw await Ht(a,await _r(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),a=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${a}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},X6=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o,a;const i=await yt(this.config.headers());try{const{responseHeaders:s,value:l,rawValue:c}=await Ot({url:this.getUrl(),headers:It(i,t??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:At(tk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(o=l.usage)!=null?o:void 0,providerMetadata:l.providerMetadata,response:{headers:s,body:c},warnings:(a=l.warnings)!=null?a:[]}}catch(s){throw await Ht(s,await _r(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},ek=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),tk=ye(()=>me(T({embeddings:L(L(q())),usage:T({tokens:q()}).nullish(),warnings:L(ek).optional(),providerMetadata:pe(d(),pe(d(),Te())).optional()}))),rk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:a,mask:i,providerOptions:s,headers:l,abortSignal:c}){var u,h,p,m;const f=await yt(this.config.headers());try{const{responseHeaders:b,value:w,rawValue:C}=await Ot({url:this.getUrl(),headers:It(f,l??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s},...a&&{files:a.map(v=>b0(v))},...i&&{mask:b0(i)}},successfulResponseHandler:At(sk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:w.images,warnings:(u=w.warnings)!=null?u:[],providerMetadata:w.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:b},...w.usage!=null&&{usage:{inputTokens:(h=w.usage.inputTokens)!=null?h:void 0,outputTokens:(p=w.usage.outputTokens)!=null?p:void 0,totalTokens:(m=w.usage.totalTokens)!=null?m:void 0}}}}catch(b){throw await Ht(b,await _r(f))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function b0(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}var nk=T({images:L(Te()).optional()}).catchall(Te()),ok=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),ak=T({inputTokens:q().nullish(),outputTokens:q().nullish(),totalTokens:q().nullish()}),sk=T({images:L(d()),warnings:L(ok).optional(),providerMetadata:pe(d(),nk).optional(),usage:ak.optional()}),ik=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:a,seed:i,generateAudio:s,image:l,providerOptions:c,headers:u,abortSignal:h}){var p;const m=await yt(this.config.headers());try{const{responseHeaders:f,value:b}=await Ot({url:this.getUrl(),headers:It(m,u??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...a&&{fps:a},...i&&{seed:i},...s!==void 0&&{generateAudio:s},...c&&{providerOptions:c},...l&&{image:lk(l)}},successfulResponseHandler:async({response:w,url:C,requestBodyValues:v})=>{if(w.body==null)throw new tt({message:"SSE response body is empty",url:C,requestBodyValues:v,statusCode:w.status});const I=kf({stream:w.body,schema:pk}).getReader(),{done:y,value:_}=await I.read();if(I.releaseLock(),y||!_)throw new tt({message:"SSE stream ended without a data event",url:C,requestBodyValues:v,statusCode:w.status});if(!_.success)throw new tt({message:"Failed to parse video SSE event",cause:_.error,url:C,requestBodyValues:v,statusCode:w.status});const k=_.value;if(k.type==="error")throw new tt({message:k.message,statusCode:k.statusCode,url:C,requestBodyValues:v,responseHeaders:Object.fromEntries([...w.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...w.headers])}},failedResponseHandler:ir({errorSchema:ut(),errorToMessage:w=>w}),...h&&{abortSignal:h},fetch:this.config.fetch});return{videos:b.videos,warnings:(p=b.warnings)!=null?p:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await Ht(f,await _r(m))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function lk(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}var ck=T({videos:L(Te()).optional()}).catchall(Te()),uk=ae([T({type:M("url"),url:d(),mediaType:d()}),T({type:M("base64"),data:d(),mediaType:d()})]),dk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),pk=Le("type",[T({type:M("result"),videos:L(uk),warnings:L(dk).optional(),providerMetadata:pe(d(),ck).optional()}),T({type:M("error"),message:d(),errorType:d(),statusCode:q(),param:Te().nullable()})]),hk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:r,headers:n,abortSignal:o,providerOptions:a}){var i;const s=await yt(this.config.headers());try{const{responseHeaders:l,value:c,rawValue:u}=await Ot({url:this.getUrl(),headers:It(s,n??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{documents:e,query:t,...r!=null?{topN:r}:{},...a?{providerOptions:a}:{}},successfulResponseHandler:At(mk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:h=>h}),...o&&{abortSignal:o},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:l,body:u},warnings:(i=c.warnings)!=null?i:[]}}catch(l){throw await Ht(l,await _r(s))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},fk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),mk=ye(()=>me(T({ranking:L(T({index:q(),relevanceScore:q()})),warnings:L(fk).optional(),providerMetadata:pe(d(),pe(d(),Te())).optional()}))),gk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({text:e,voice:t,outputFormat:r,instructions:n,speed:o,language:a,providerOptions:i,headers:s,abortSignal:l}){var c;const u=await yt(this.config.headers());try{const{responseHeaders:h,value:p,rawValue:m}=await Ot({url:this.getUrl(),headers:It(u,s??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{text:e,...t&&{voice:t},...r&&{outputFormat:r},...n&&{instructions:n},...o!=null&&{speed:o},...a&&{language:a},...i&&{providerOptions:i}},successfulResponseHandler:At(vk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:f=>f}),...l&&{abortSignal:l},fetch:this.config.fetch});return{audio:p.audio,warnings:(c=p.warnings)!=null?c:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h,body:m}}}catch(h){throw await Ht(h,await _r(u??{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"3","ai-model-id":this.modelId}}},_k=T({}).catchall(Te()),yk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),vk=T({audio:d(),warnings:L(yk).optional(),providerMetadata:pe(d(),_k).optional()}),wk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({audio:e,mediaType:t,providerOptions:r,headers:n,abortSignal:o}){var a,i,s,l;const c=await yt(this.config.headers());try{const{responseHeaders:u,value:h,rawValue:p}=await Ot({url:this.getUrl(),headers:It(c,n??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{audio:e instanceof Uint8Array?gn(e):e,mediaType:t,...r&&{providerOptions:r}},successfulResponseHandler:At(Tk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:m=>m}),...o&&{abortSignal:o},fetch:this.config.fetch});return{text:h.text,segments:(a=h.segments)!=null?a:[],language:(i=h.language)!=null?i:void 0,durationInSeconds:(s=h.durationInSeconds)!=null?s:void 0,warnings:(l=h.warnings)!=null?l:[],providerMetadata:h.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u,body:p}}}catch(u){throw await Ht(u,await _r(c??{}))}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"3","ai-model-id":this.modelId}}},bk=T({}).catchall(Te()),kk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),Tk=T({text:d(),segments:L(T({text:d(),startSecond:q(),endSecond:q()})).optional(),language:d().nullish(),durationInSeconds:q().nullish(),warnings:L(kk).optional(),providerMetadata:pe(d(),bk).optional()}),Ck=ye(()=>me(vt({query:be().describe("Natural-language web search query. This is required."),type:Vr(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:gt().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:Vr(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:be().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:St(be()).optional().describe("Only return results from these domains."),exclude_domains:St(be()).optional().describe("Exclude results from these domains."),start_published_date:be().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:be().optional().describe("Only return links published before this ISO 8601 date."),contents:vt({text:jn([Ml(),vt({max_characters:gt().optional(),include_html_tags:Ml().optional(),verbosity:Vr(["compact","standard","full"]).optional(),include_sections:St(Vr(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:St(Vr(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:jn([Ml(),vt({query:be().optional(),max_characters:gt().optional()})]).optional(),max_age_hours:gt().optional(),livecrawl_timeout:gt().optional(),subpages:gt().optional(),subpage_target:jn([be(),St(be())]).optional(),extras:vt({links:gt().optional(),image_links:gt().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}))),Sk=ye(()=>me(jn([vt({requestId:be(),searchType:be().optional(),resolvedSearchType:be().optional(),results:St(vt({title:be(),url:be(),id:be(),publishedDate:be().nullable().optional(),author:be().nullable().optional(),image:be().nullable().optional(),favicon:be().nullable().optional(),text:be().optional(),highlights:St(be()).optional(),highlightScores:St(gt()).optional(),summary:be().optional(),subpages:St(e4()).optional(),extras:vt({links:St(be()).optional(),imageLinks:St(be()).optional()}).optional()})),costDollars:vt({total:gt().optional(),search:t4(gt()).optional()}).optional()}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:gt().optional(),message:be()})]))),Ik=sr({id:"gateway.exa_search",inputSchema:Ck,outputSchema:Sk}),xk=(e={})=>Ik(e),Ek=ye(()=>me(vt({objective:be().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:St(be()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Vr(["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:gt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:vt({include_domains:St(be()).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:St(be()).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:be().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:vt({max_chars_per_result:gt().optional().describe("Maximum characters per result."),max_chars_total:gt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:vt({max_age_seconds:gt().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.")}))),$k=ye(()=>me(jn([vt({searchId:be(),results:St(vt({url:be(),title:be(),excerpt:be(),publishDate:be().nullable().optional(),relevanceScore:gt().optional()}))}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:gt().optional(),message:be()})]))),Rk=sr({id:"gateway.parallel_search",inputSchema:Ek,outputSchema:$k}),Pk=(e={})=>Rk(e),Mk=ye(()=>me(vt({query:jn([be(),St(be())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:gt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:gt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:gt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:be().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:St(be()).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:St(be()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:be().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:be().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:be().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:be().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:Vr(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Ok=ye(()=>me(jn([vt({results:St(vt({title:be(),url:be(),snippet:be(),date:be().optional(),lastUpdated:be().optional()})),id:be()}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:gt().optional(),message:be()})]))),Ak=sr({id:"gateway.perplexity_search",inputSchema:Mk,outputSchema:Ok}),Nk=(e={})=>Ak(e),qk={exaSearch:xk,parallelSearch:Pk,perplexitySearch:Nk};async function Lk(){var e;return(e=Rf.getContext().headers)==null?void 0:e["x-vercel-id"]}var jk="3.0.140",Dk="0.0.1";function Uk(e={}){var t,r;let n=null,o=null;const a=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let i=0;const s=(r=If(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const I=await Fk(e);return _n({Authorization:`Bearer ${I.token}`,"ai-gateway-protocol-version":Dk,[v0]:I.authMethod,...e.headers},`ai-sdk/gateway/${jk}`)}catch(I){throw Kl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:I})}},c=()=>{const I=wo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=wo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=wo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),k=wo({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const S=await Lk();return{...I&&{"ai-o11y-deployment-id":I},...y&&{"ai-o11y-environment":y},..._&&{"ai-o11y-region":_},...S&&{"ai-o11y-request-id":S},...k&&{"ai-o11y-project-id":k}}}},u=I=>new Q6(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var I,y,_;const k=(_=(y=(I=e._internal)==null?void 0:I.currentDate)==null?void 0:y.call(I).getTime())!=null?_:Date.now();return(!n||k-i>a)&&(i=k,n=new w0({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then(S=>(o=S,S)).catch(async S=>{throw await Ht(S,await _r(await l()))})),o?Promise.resolve(o):n},p=async()=>new w0({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async I=>{throw await Ht(I,await _r(await l()))}),m=async I=>new G6({baseURL:s,headers:l,fetch:e.fetch}).getSpendReport(I).catch(async y=>{throw await Ht(y,await _r(await l()))}),f=async I=>new K6({baseURL:s,headers:l,fetch:e.fetch}).getGenerationInfo(I).catch(async y=>{throw await Ht(y,await _r(await l()))}),b=function(I){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(I)};b.specificationVersion="v3",b.getAvailableModels=h,b.getCredits=p,b.getSpendReport=m,b.getGenerationInfo=f,b.imageModel=I=>new rk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),b.languageModel=u;const w=I=>new X6(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.embeddingModel=w,b.textEmbeddingModel=w,b.videoModel=I=>new ik(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});const C=I=>new hk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.rerankingModel=C,b.reranking=C;const v=I=>new gk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.speechModel=v,b.speech=v;const g=I=>new wk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});return b.transcriptionModel=g,b.transcription=g,b.chat=b.languageModel,b.embedding=b.embeddingModel,b.image=b.imageModel,b.video=b.videoModel,b.tools=qk,b}var zk=Uk();async function Fk(e){const t=wo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Rf.getVercelOidcToken(),authMethod:"oidc"}}const Zn="1.9.1",k0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Vk(e){const t=new Set([e]),r=new Set,n=e.match(k0);if(!n)return()=>!1;const o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function a(s){return r.add(s),!1}function i(s){return t.add(s),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;const c=l.match(k0);if(!c)return a(l);const u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?a(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?i(l):a(l):o.minor<=u.minor?i(l):a(l)}}const Zk=Vk(Zn),Hk=Zn.split(".")[0],aa=Symbol.for(`opentelemetry.js.api.${Hk}`),sa=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function ia(e,t,r,n=!1){var o;const a=sa[aa]=(o=sa[aa])!==null&&o!==void 0?o:{version:Zn};if(!n&&a[e]){const i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(i.stack||i.message),!1}if(a.version!==Zn){const i=new Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${Zn}`);return r.error(i.stack||i.message),!1}return a[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${Zn}.`),!0}function Hn(e){var t,r;const n=(t=sa[aa])===null||t===void 0?void 0:t.version;if(!(!n||!Zk(n)))return(r=sa[aa])===null||r===void 0?void 0:r[e]}function la(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Zn}.`);const r=sa[aa];r&&delete r[e]}class Bk{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return ca("debug",this._namespace,t)}error(...t){return ca("error",this._namespace,t)}info(...t){return ca("info",this._namespace,t)}warn(...t){return ca("warn",this._namespace,t)}verbose(...t){return ca("verbose",this._namespace,t)}}function ca(e,t,r){const n=Hn("diag");if(n)return n[e](t,...r)}var lr;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(lr||(lr={}));function Jk(e,t){e<lr.NONE?e=lr.NONE:e>lr.ALL&&(e=lr.ALL),t=t||{};function r(n,o){const a=t[n];return typeof a=="function"&&e>=o?a.bind(t):function(){}}return{error:r("error",lr.ERROR),warn:r("warn",lr.WARN),info:r("info",lr.INFO),debug:r("debug",lr.DEBUG),verbose:r("verbose",lr.VERBOSE)}}const Gk="diag";class yr{static instance(){return this._instance||(this._instance=new yr),this._instance}constructor(){function t(o){return function(...a){const i=Hn("diag");if(i)return i[o](...a)}}const r=this,n=(o,a={logLevel:lr.INFO})=>{var i,s,l;if(o===r){const h=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=h.stack)!==null&&i!==void 0?i:h.message),!1}typeof a=="number"&&(a={logLevel:a});const c=Hn("diag"),u=Jk((s=a.logLevel)!==null&&s!==void 0?s:lr.INFO,o);if(c&&!a.suppressOverrideMessage){const h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${h}`),u.warn(`Current logger will overwrite one already registered from ${h}`)}return ia("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{la(Gk,r)},r.createComponentLogger=o=>new Bk(o),r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}}class bo{constructor(t){this._entries=t?new Map(t):new Map}getEntry(t){const r=this._entries.get(t);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(t,r){const n=new bo(this._entries);return n._entries.set(t,r),n}removeEntry(t){const r=new bo(this._entries);return r._entries.delete(t),r}removeEntries(...t){const r=new bo(this._entries);for(const n of t)r._entries.delete(n);return r}clear(){return new bo}}yr.instance();function Wk(e={}){return new bo(new Map(Object.entries(e)))}function T0(e){return Symbol.for(e)}class ys{constructor(t){const r=this;r._currentContext=t?new Map(t):new Map,r.getValue=n=>r._currentContext.get(n),r.setValue=(n,o)=>{const a=new ys(r._currentContext);return a._currentContext.set(n,o),a},r.deleteValue=n=>{const o=new ys(r._currentContext);return o._currentContext.delete(n),o}}}const Kk=new ys;class Yk{constructor(){}createGauge(t,r){return iT}createHistogram(t,r){return lT}createCounter(t,r){return sT}createUpDownCounter(t,r){return cT}createObservableGauge(t,r){return dT}createObservableCounter(t,r){return uT}createObservableUpDownCounter(t,r){return pT}addBatchObservableCallback(t,r){}removeBatchObservableCallback(t){}}class vs{}class Qk extends vs{add(t,r){}}class Xk extends vs{add(t,r){}}class eT extends vs{record(t,r){}}class tT extends vs{record(t,r){}}class Yl{addCallback(t){}removeCallback(t){}}class rT extends Yl{}class nT extends Yl{}class oT extends Yl{}const aT=new Yk,sT=new Qk,iT=new eT,lT=new tT,cT=new Xk,uT=new rT,dT=new nT,pT=new oT,hT={get(e,t){if(e!=null)return e[t]},keys(e){return e==null?[]:Object.keys(e)}},fT={set(e,t,r){e!=null&&(e[t]=r)}};class mT{active(){return Kk}with(t,r,n,...o){return r.call(n,...o)}bind(t,r){return r}enable(){return this}disable(){return this}}const Ql="context",gT=new mT;class ko{constructor(){}static getInstance(){return this._instance||(this._instance=new ko),this._instance}setGlobalContextManager(t){return ia(Ql,t,yr.instance())}active(){return this._getContextManager().active()}with(t,r,n,...o){return this._getContextManager().with(t,r,n,...o)}bind(t,r){return this._getContextManager().bind(t,r)}_getContextManager(){return Hn(Ql)||gT}disable(){this._getContextManager().disable(),la(Ql,yr.instance())}}var Xl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Xl||(Xl={}));const C0="0000000000000000",S0="00000000000000000000000000000000",_T={traceId:S0,spanId:C0,traceFlags:Xl.NONE};class ua{constructor(t=_T){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,r){return this}setAttributes(t){return this}addEvent(t,r){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,r){}}const ec=T0("OpenTelemetry Context Key SPAN");function tc(e){return e.getValue(ec)||void 0}function yT(){return tc(ko.getInstance().active())}function rc(e,t){return e.setValue(ec,t)}function vT(e){return e.deleteValue(ec)}function wT(e,t){return rc(e,new ua(t))}function I0(e){var t;return(t=tc(e))===null||t===void 0?void 0:t.spanContext()}const ws=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function x0(e,t){if(typeof e!="string"||e.length!==t)return!1;let r=0;for(let n=0;n<e.length;n+=4)r+=(ws[e.charCodeAt(n)]|0)+(ws[e.charCodeAt(n+1)]|0)+(ws[e.charCodeAt(n+2)]|0)+(ws[e.charCodeAt(n+3)]|0);return r===t}function bT(e){return x0(e,32)&&e!==S0}function kT(e){return x0(e,16)&&e!==C0}function E0(e){return bT(e.traceId)&&kT(e.spanId)}function TT(e){return new ua(e)}const nc=ko.getInstance();class $0{startSpan(t,r,n=nc.active()){if(!!r?.root)return new ua;const a=n&&I0(n);return CT(a)&&E0(a)?new ua(a):new ua}startActiveSpan(t,r,n,o){let a,i,s;if(arguments.length<2)return;arguments.length===2?s=r:arguments.length===3?(a=r,s=n):(a=r,i=n,s=o);const l=i??nc.active(),c=this.startSpan(t,a,l),u=rc(l,c);return nc.with(u,s,void 0,c)}}function CT(e){return e!==null&&typeof e=="object"&&"spanId"in e&&typeof e.spanId=="string"&&"traceId"in e&&typeof e.traceId=="string"&&"traceFlags"in e&&typeof e.traceFlags=="number"}const ST=new $0;class IT{constructor(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}startSpan(t,r,n){return this._getTracer().startSpan(t,r,n)}startActiveSpan(t,r,n,o){const a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)}_getTracer(){if(this._delegate)return this._delegate;const t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):ST}}class xT{getTracer(t,r,n){return new $0}}const ET=new xT;class R0{getTracer(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new IT(this,t,r,n)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:ET}setDelegate(t){this._delegate=t}getDelegateTracer(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)}}var bs;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(bs||(bs={}));const P0=ko.getInstance();yr.instance();class $T{getMeter(t,r,n){return aT}}const RT=new $T,oc="metrics";class ac{constructor(){}static getInstance(){return this._instance||(this._instance=new ac),this._instance}setGlobalMeterProvider(t){return ia(oc,t,yr.instance())}getMeterProvider(){return Hn(oc)||RT}getMeter(t,r,n){return this.getMeterProvider().getMeter(t,r,n)}disable(){la(oc,yr.instance())}}ac.getInstance();class PT{inject(t,r){}extract(t,r){return t}fields(){return[]}}const sc=T0("OpenTelemetry Baggage Key");function M0(e){return e.getValue(sc)||void 0}function MT(){return M0(ko.getInstance().active())}function OT(e,t){return e.setValue(sc,t)}function AT(e){return e.deleteValue(sc)}const ic="propagation",NT=new PT;class lc{constructor(){this.createBaggage=Wk,this.getBaggage=M0,this.getActiveBaggage=MT,this.setBaggage=OT,this.deleteBaggage=AT}static getInstance(){return this._instance||(this._instance=new lc),this._instance}setGlobalPropagator(t){return ia(ic,t,yr.instance())}inject(t,r,n=fT){return this._getGlobalPropagator().inject(t,r,n)}extract(t,r,n=hT){return this._getGlobalPropagator().extract(t,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){la(ic,yr.instance())}_getGlobalPropagator(){return Hn(ic)||NT}}lc.getInstance();const cc="trace";class uc{constructor(){this._proxyTracerProvider=new R0,this.wrapSpanContext=TT,this.isSpanContextValid=E0,this.deleteSpan=vT,this.getSpan=tc,this.getActiveSpan=yT,this.getSpanContext=I0,this.setSpan=rc,this.setSpanContext=wT}static getInstance(){return this._instance||(this._instance=new uc),this._instance}setGlobalTracerProvider(t){const r=ia(cc,this._proxyTracerProvider,yr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r}getTracerProvider(){return Hn(cc)||this._proxyTracerProvider}getTracer(t,r){return this.getTracerProvider().getTracer(t,r)}disable(){la(cc,yr.instance()),this._proxyTracerProvider=new R0}}const qT=uc.getInstance();var LT=Object.defineProperty,jT=(e,t)=>{for(var r in t)LT(e,r,{get:t[r],enumerable:!0})},O0="AI_InvalidArgumentError",A0=`vercel.ai.error.${O0}`,DT=Symbol.for(A0),N0,Zr=class extends we{constructor({parameter:t,value:r,message:n}){super({name:O0,message:`Invalid argument for parameter ${t}: ${n}`}),this[N0]=!0,this.parameter=t,this.value=r}static isInstance(t){return we.hasMarker(t,A0)}};N0=DT;var q0="AI_InvalidToolApprovalError",L0=`vercel.ai.error.${q0}`,UT=Symbol.for(L0),j0,zT=class extends we{constructor({approvalId:e}){super({name:q0,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[j0]=!0,this.approvalId=e}static isInstance(e){return we.hasMarker(e,L0)}};j0=UT;var D0="AI_InvalidToolApprovalSignatureError",U0=`vercel.ai.error.${D0}`,FT=Symbol.for(U0),z0,F0=class extends we{constructor({approvalId:e,toolCallId:t,reason:r}){super({name:D0,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${r}`}),this[z0]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return we.hasMarker(e,U0)}};z0=FT;var V0="AI_InvalidToolInputError",Z0=`vercel.ai.error.${V0}`,VT=Symbol.for(Z0),H0,ks=class extends we{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${co(r)}`}){super({name:V0,message:n,cause:r}),this[H0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return we.hasMarker(e,Z0)}};H0=VT;var B0="AI_ToolCallNotFoundForApprovalError",J0=`vercel.ai.error.${B0}`,ZT=Symbol.for(J0),G0,dc=class extends we{constructor({toolCallId:e,approvalId:t}){super({name:B0,message:`Tool call "${e}" not found for approval request "${t}".`}),this[G0]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return we.hasMarker(e,J0)}};G0=ZT;var W0="AI_MissingToolResultsError",K0=`vercel.ai.error.${W0}`,HT=Symbol.for(K0),Y0,Q0=class extends we{constructor({toolCallIds:e}){super({name:W0,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Y0]=!0,this.toolCallIds=e}static isInstance(e){return we.hasMarker(e,K0)}};Y0=HT;var X0="AI_NoObjectGeneratedError",em=`vercel.ai.error.${X0}`,BT=Symbol.for(em),tm,vn=class extends we{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:a}){super({name:X0,message:e,cause:t}),this[tm]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=a}static isInstance(e){return we.hasMarker(e,em)}};tm=BT;var rm="AI_NoOutputGeneratedError",nm=`vercel.ai.error.${rm}`,JT=Symbol.for(nm),om,Ts=class extends we{constructor({message:e="No output generated.",cause:t}={}){super({name:rm,message:e,cause:t}),this[om]=!0}static isInstance(e){return we.hasMarker(e,nm)}};om=JT;var am="AI_NoSuchToolError",sm=`vercel.ai.error.${am}`,GT=Symbol.for(sm),im,pc=class extends we{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:am,message:r}),this[im]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return we.hasMarker(e,sm)}};im=GT;var lm="AI_ToolCallRepairError",cm=`vercel.ai.error.${lm}`,WT=Symbol.for(cm),um,KT=class extends we{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${co(e)}`}){super({name:lm,message:r,cause:e}),this[um]=!0,this.originalError=t}static isInstance(e){return we.hasMarker(e,cm)}};um=WT;var YT=class extends we{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},dm="AI_UIMessageStreamError",pm=`vercel.ai.error.${dm}`,QT=Symbol.for(pm),hm,To=class extends we{constructor({chunkType:e,chunkId:t,message:r}){super({name:dm,message:r}),this[hm]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return we.hasMarker(e,pm)}};hm=QT;var fm="AI_InvalidMessageRoleError",mm=`vercel.ai.error.${fm}`,XT=Symbol.for(mm),gm,e5=class extends we{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:fm,message:t}),this[gm]=!0,this.role=e}static isInstance(e){return we.hasMarker(e,mm)}};gm=XT;var _m="AI_RetryError",ym=`vercel.ai.error.${_m}`,t5=Symbol.for(ym),vm,wm=class extends we{constructor({message:e,reason:t,errors:r}){super({name:_m,message:e}),this[vm]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return we.hasMarker(e,ym)}};vm=t5;function Bn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function xr(e){for(const t of Bn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function r5({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var n5="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",bm=!1,hc=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}bm||(bm=!0,console.info(n5));for(const r of e.warnings)console.warn(r5({warning:r,provider:e.provider,model:e.model}))}};function o5({provider:e,modelId:t}){hc({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function a5(e){return e.specificationVersion==="v3"?e:(o5({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:km(o.finishReason),usage:Tm(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:s5(o.stream)}};default:return t[r]}}}))}function s5(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:km(t.finishReason),usage:Tm(t.usage)});break;default:r.enqueue(t);break}}}))}function km(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function Tm(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function Cs(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new YT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return a5(e)}return i5().languageModel(e)}function i5(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:zk}function fc(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function Cm(e){if(!(e==null||typeof e=="number"))return e.stepMs}function l5(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var c5=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],u5=e=>{const t=typeof e=="string"?Un(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function d5(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?u5(e):e}function p5({data:e,signatures:t}){const r=d5(e),n=typeof r=="string"?Un(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((a,i)=>a===null||n[i]===a))return o.mediaType}var Sm="6.0.216",h5=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const a=_n({},`ai-sdk/${Sm}`,oa()),i=await cf({url:o,headers:a,abortSignal:r});if(!i.ok)throw await fs(i),new Zt({url:o,statusCode:i.status,statusText:i.statusText});return{data:await ql({response:i,url:o,maxBytes:t??Nl}),mediaType:(n=i.headers.get("content-type"))!=null?n:void 0}}catch(a){throw Zt.isInstance(a)?a:new Zt({url:o,cause:a})}},f5=(e=h5)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function m5(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Im=ae([d(),is(Uint8Array),is(ArrayBuffer),Rh(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function mc(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=m5(e.toString());if(t==null||r==null)throw new we({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function gc(e){return typeof e=="string"?e:e instanceof ArrayBuffer?gn(new Uint8Array(e)):gn(e)}async function xm({prompt:e,supportedUrls:t,download:r=f5()}){const n=await _5(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const a=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const h=o.get(u.approvalId);h&&a.add(h)}}const i=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Bn(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>g5({message:c,downloadedAssets:n}))],s=[];for(const c of i){if(c.role!=="tool"){s.push(c);continue}const u=s.at(-1);u?.role==="tool"?u.content.push(...c.content):s.push(c)}const l=new Set;for(const c of s)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of a)l.delete(u);if(l.size>0)throw new Q0({toolCallIds:Array.from(l)});break}for(const c of a)l.delete(c);if(l.size>0)throw new Q0({toolCallIds:Array.from(l)});return s.filter(c=>c.role!=="tool"||c.content.length>0)}function g5({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>y5(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:a,mediaType:i}=mc(n.data);return{type:"file",data:a,filename:n.filename,mediaType:i??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:Em({output:n.output,downloadedAssets:t}),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:Em({output:n.output,downloadedAssets:t}),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new e5({role:n})}}}async function _5(e,t,r){var n;const o=[];for(const s of e){if(s.role==="user"&&Array.isArray(s.content))for(const l of s.content)(l.type==="image"||l.type==="file")&&o.push({data:l.type==="image"?l.image:l.data,mediaType:(n=l.mediaType)!=null?n:l.type==="image"?"image/*":void 0});if(s.role==="tool"||s.role==="assistant"){if(!Array.isArray(s.content))continue;for(const l of s.content)if(l.type==="tool-result"&&l.output.type==="content")for(const c of l.output.value)(c.type==="image-url"||c.type==="file-url")&&o.push({data:new URL(c.url),mediaType:c.type==="image-url"?"image/*":void 0})}}const a=o.map(s=>{const l=s.mediaType,{data:c}=mc(s.data);return{mediaType:l,data:c}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&v4({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),i=await t(a);return Object.fromEntries(i.map((s,l)=>s==null?null:[a[l].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function y5(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:a,mediaType:i}=mc(n);let s=i??e.mediaType,l=a;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(r=p5({data:l,signatures:c5}))!=null?r:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function Em({output:e,downloadedAssets:t}){return e.type!=="content"?e:{type:"content",value:e.value.map(r=>{var n,o;if(r.type==="image-url"){const a=t[new URL(r.url).toString()];return a?{type:"image-data",data:gc(a.data),mediaType:(n=a.mediaType)!=null?n:"image/*",providerOptions:r.providerOptions}:r}if(r.type==="file-url"){const a=t[new URL(r.url).toString()];return a?{type:"file-data",data:gc(a.data),mediaType:(o=a.mediaType)!=null?o:"application/octet-stream",providerOptions:r.providerOptions}:r}return r.type!=="media"?r:r.mediaType.startsWith("image/")?{type:"image-data",data:r.data,mediaType:r.mediaType}:{type:"file-data",data:r.data,mediaType:r.mediaType}})}}async function da({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:co(r)}:o==="json"?{type:"error-json",value:$m(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:$m(r)}}function $m(e){return e===void 0?null:e}function _c({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,seed:i,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Zr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Zr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Zr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Zr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new Zr({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Zr({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,stopSequences:s,seed:i}}function v5(e){return e!=null&&Object.keys(e).length>0}async function Rm({tools:e,toolChoice:t,activeTools:r}){if(!v5(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([a])=>r.includes(a)):Object.entries(e),o=[];for(const[a,i]of n){const s=i.type;switch(s){case void 0:case"dynamic":case"function":o.push({type:"function",name:a,description:i.description,inputSchema:await yn(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:a,id:i.id,args:i.args});break;default:{const l=s;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var Jn=ss(()=>ae([Qo(),d(),q(),_e(),pe(d(),Jn.optional()),L(Jn)])),pt=pe(d(),pe(d(),Jn.optional())),Pm=T({type:M("text"),text:d(),providerOptions:pt.optional()}),w5=T({type:M("image"),image:ae([Im,is(URL)]),mediaType:d().optional(),providerOptions:pt.optional()}),Mm=T({type:M("file"),data:ae([Im,is(URL)]),filename:d().optional(),mediaType:d(),providerOptions:pt.optional()}),b5=T({type:M("reasoning"),text:d(),providerOptions:pt.optional()}),k5=T({type:M("tool-call"),toolCallId:d(),toolName:d(),input:Te(),providerOptions:pt.optional(),providerExecuted:_e().optional()}),T5=Le("type",[T({type:M("text"),value:d(),providerOptions:pt.optional()}),T({type:M("json"),value:Jn,providerOptions:pt.optional()}),T({type:M("execution-denied"),reason:d().optional(),providerOptions:pt.optional()}),T({type:M("error-text"),value:d(),providerOptions:pt.optional()}),T({type:M("error-json"),value:Jn,providerOptions:pt.optional()}),T({type:M("content"),value:L(ae([T({type:M("text"),text:d(),providerOptions:pt.optional()}),T({type:M("media"),data:d(),mediaType:d()}),T({type:M("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:pt.optional()}),T({type:M("file-url"),url:d(),providerOptions:pt.optional()}),T({type:M("file-id"),fileId:ae([d(),pe(d(),d())]),providerOptions:pt.optional()}),T({type:M("image-data"),data:d(),mediaType:d(),providerOptions:pt.optional()}),T({type:M("image-url"),url:d(),providerOptions:pt.optional()}),T({type:M("image-file-id"),fileId:ae([d(),pe(d(),d())]),providerOptions:pt.optional()}),T({type:M("custom"),providerOptions:pt.optional()})]))})]),Om=T({type:M("tool-result"),toolCallId:d(),toolName:d(),output:T5,providerOptions:pt.optional()}),C5=T({type:M("tool-approval-request"),approvalId:d(),toolCallId:d()}),S5=T({type:M("tool-approval-response"),approvalId:d(),approved:_e(),reason:d().optional()}),I5=T({role:M("system"),content:d(),providerOptions:pt.optional()}),x5=T({role:M("user"),content:ae([d(),L(ae([Pm,w5,Mm]))]),providerOptions:pt.optional()}),E5=T({role:M("assistant"),content:ae([d(),L(ae([Pm,Mm,b5,k5,Om,C5]))]),providerOptions:pt.optional()}),$5=T({role:M("tool"),content:L(ae([Om,S5])),providerOptions:pt.optional()}),R5=ae([I5,x5,E5,$5]);async function Am({allowSystemInMessages:e,system:t,prompt:r,messages:n}){if(r==null&&n==null)throw new un({prompt:r,message:"prompt or messages must be defined"});if(r!=null&&n!=null)throw new un({prompt:r,message:"prompt and messages cannot be defined at the same time"});if(typeof t!="string"&&!Bn(t).every(a=>a.role==="system"))throw new un({prompt:r,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(r!=null&&typeof r=="string")n=[{role:"user",content:r}];else if(r!=null&&Array.isArray(r))n=r;else if(n==null)throw new un({prompt:r,message:"prompt or messages must be defined"});if(n.length===0)throw new un({prompt:r,message:"messages must not be empty"});if(n.some(a=>a.role==="system")){if(e===!1)throw new un({prompt:r,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}const o=await ar({value:n,schema:L(R5)});if(!o.success)throw new un({prompt:r,message:"The messages do not match the ModelMessage[] schema.",cause:o.error});return{messages:n,system:t}}function Nm(e){if(!Kl.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new we({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
61
|
-
|
|
62
|
-
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
63
|
-
|
|
64
|
-
Alternatively, you can use a provider module instead of the AI Gateway.
|
|
65
|
-
|
|
66
|
-
Learn more: \x1B[34m${r}\x1B[0m
|
|
67
|
-
|
|
68
|
-
`),{name:"GatewayAuthenticationError"})}function pa({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function qm({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((a,[i,s])=>{if(i==="timeout"){const l=fc(s);l!=null&&(a[`ai.settings.${i}`]=l)}else a[`ai.settings.${i}`]=s;return a},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((a,[i,s])=>(a[`ai.telemetry.metadata.${i}`]=s,a),{}),...Object.entries(n??{}).reduce((a,[i,s])=>(s!==void 0&&(a[`ai.request.headers.${i}`]=s),a),{})}}var P5={startSpan(){return Ss},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ss);if(typeof r=="function")return r(Ss);if(typeof n=="function")return n(Ss)}},Ss={spanContext(){return M5},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},M5={traceId:"",spanId:"",traceFlags:0};function Lm({isEnabled:e=!1,tracer:t}={}){return e?t||qT.getTracer("ai"):P5}async function ha({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async a=>{const i=P0.active();try{const s=await P0.with(i,()=>n(a));return o&&a.end(),s}catch(s){try{jm(a,s)}finally{a.end()}throw s}})}function jm(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:bs.ERROR,message:t.message})):e.setStatus({code:bs.ERROR})}function O5(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function yc(e){if(!Array.isArray(e))return e;const t=new Set(e.filter(O5).map(n=>typeof n));if(t.size!==1)return;const[r]=t;return r==="string"?e.filter(n=>typeof n=="string"):r==="number"?e.filter(n=>typeof n=="number"):e.filter(n=>typeof n=="boolean")}async function vr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t)){if(o==null)continue;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const i=await o.input();if(i!=null){const s=yc(i);s!=null&&(r[n]=s)}continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const i=await o.output();if(i!=null){const s=yc(i);s!=null&&(r[n]=s)}continue}const a=yc(o);a!=null&&(r[n]=a)}return r}function Dm(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?gc(r.data):r.data}:r)})))}function A5(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function Um(){const e=A5();return t=>{const r=Bn(t),n=[...e,...r];function o(a){const i=n.map(a).filter(Boolean);return async s=>{for(const l of i)try{await l(s)}catch{}}}return{onStart:o(a=>a.onStart),onStepStart:o(a=>a.onStepStart),onToolCallStart:o(a=>a.onToolCallStart),onToolCallFinish:o(a=>a.onToolCallFinish),onStepFinish:o(a=>a.onStepFinish),onFinish:o(a=>a.onFinish)}}}function vc(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Er(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function wc(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function zm(e,t){var r,n,o,a,i,s,l,c,u,h;return{inputTokens:Er(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Er((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Er((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:Er((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheWriteTokens)},outputTokens:Er(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Er((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Er((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(h=t.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Er(e.totalTokens,t.totalTokens),reasoningTokens:Er(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Er(e.cachedInputTokens,t.cachedInputTokens)}}function Er(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Is(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(!(n==="__proto__"||n==="constructor"||n==="prototype")&&Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const a=n in e?e[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),s=a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);i&&s?r[n]=Is(a,o):r[n]=o}return r}function N5({error:e,exponentialBackoffDelay:t}){const r=tt.isInstance(e)?e.responseHeaders:tt.isInstance(e.cause)?e.cause.responseHeaders:void 0;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const a=r["retry-after"];if(a&&n===void 0){const i=parseFloat(a);Number.isNaN(i)?n=Date.parse(a)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var q5=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Fm(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Fm(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},a=[]){try{return await e()}catch(i){if(zn(i)||t===0)throw i;const s=Ll(i),l=[...a,i],c=l.length;if(c>t)throw new wm({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&(tt.isInstance(i)&&i.isRetryable===!0||kt.isInstance(i)&&i.isRetryable===!0)&&c<=t)return await o4(N5({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),Fm(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new wm({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function Vm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:q5({maxRetries:r,abortSignal:t})}}function Zm({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const a=[],i=[],s=t.content.filter(l=>l.type==="tool-approval-response");for(const l of s){const c=n[l.approvalId];if(c==null)throw new zT({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new dc({toolCallId:c.toolCallId,approvalId:c.approvalId});const h={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?a.push(h):i.push(h)}return{approvedToolApprovals:a,deniedToolApprovals:i}}function xs(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function bc({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:h}){const{toolName:p,toolCallId:m,input:f}=e,b=t?.[p];if(b?.execute==null)return;const w={stepNumber:s,model:l,toolCall:e,messages:o,abortSignal:a,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return ha({name:"ai.toolCall",attributes:vr({telemetry:n,attributes:{...pa({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":m,"ai.toolCall.args":{output:()=>JSON.stringify(f)}}}),tracer:r,fn:async C=>{let v;await xr({event:w,callbacks:u});const g=xs();try{const y=b6({execute:b.execute.bind(b),input:f,options:{toolCallId:m,messages:o,abortSignal:a,experimental_context:i}});for await(const _ of y)_.type==="preliminary"?c?.({...e,type:"tool-result",output:_.output,preliminary:!0}):v=_.output}catch(y){const _=xs()-g;return await xr({event:{...w,success:!1,error:y,durationMs:_},callbacks:h}),jm(C,y),{type:"tool-error",toolCallId:m,toolName:p,input:f,error:y,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}const I=xs()-g;await xr({event:{...w,success:!0,output:v,durationMs:I},callbacks:h});try{C.setAttributes(await vr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(v)}}}))}catch{}return{type:"tool-result",toolCallId:m,toolName:p,input:f,output:v,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}})}function Hm(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
|
|
69
|
-
`)}function Bm(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Jm=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=gn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Un(this.base64Data)),this.uint8ArrayData}},L5=class extends Jm{constructor(e){super(e),this.type="file"}};async function kc({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var Tc=new TextEncoder;function Cc(e){return e==null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Cc).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Cc(e[n])}`).join(",")}}`}function Gm(e){return gn(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function j5(e){return Un(e)}async function Wm(e){const t=typeof e=="string"?Tc.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function Km(e){const t=Cc(e),r=await crypto.subtle.digest("SHA-256",Tc.encode(t));return Gm(new Uint8Array(r))}function Ym(e,t,r,n){return Tc.encode(`${e}
|
|
70
|
-
${t}
|
|
71
|
-
${r}
|
|
72
|
-
${n}`)}async function D5({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){const a=await Wm(e),i=await Km(o),s=Ym(t,r,n,i),l=await crypto.subtle.sign("HMAC",a,s);return Gm(new Uint8Array(l))}async function U5({secret:e,signature:t,approvalId:r,toolCallId:n,toolName:o,input:a}){const i=await Wm(e),s=await Km(a),l=Ym(r,n,o,s),c=j5(t);return crypto.subtle.verify("HMAC",i,c,l)}async function Qm({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){if(e!=null)return D5({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o})}async function Xm({approvedToolApprovals:e,tools:t,messages:r,experimental_context:n,toolApprovalSecret:o}){var a;const i=[],s=[];for(const l of e){const{toolCall:c,approvalRequest:u}=l,h=t?.[c.toolName];if(o!=null){if(u.signature==null)throw new F0({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"missing signature"});if(!await U5({secret:o,signature:u.signature,approvalId:u.approvalId,toolCallId:c.toolCallId,toolName:c.toolName,input:c.input}))throw new F0({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"invalid signature"})}if(h!=null&&typeof h.execute=="function"&&h.inputSchema!=null){const m=await ar({value:c.input,schema:yn(h.inputSchema)});if(!m.success)throw new ks({toolName:c.toolName,toolInput:JSON.stringify(c.input),cause:m.error})}h!=null&&await kc({tool:h,toolCall:c,messages:r,experimental_context:n})?i.push(l):s.push({...l,approvalResponse:{...l.approvalResponse,approved:!1,reason:(a=l.approvalResponse.reason)!=null?a:`Tool "${c.toolName}" does not require approval`}})}return{approvedToolApprovals:i,deniedToolApprovals:s}}var z5={};jT(z5,{array:()=>Z5,choice:()=>H5,json:()=>B5,object:()=>V5,text:()=>Es});function F5(e){const t=["ROOT"];let r=-1,n=null,o=0;function a(u){return u>="0"&&u<="9"||u>="A"&&u<="F"||u>="a"&&u<="f"}function i(u,h,p){switch(u){case'"':{r=h,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=h,n=h,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=h,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{r=h,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{r=h,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function s(u,h){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=h,t.pop();break}}}function l(u,h){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=h,t.pop();break}}}for(let u=0;u<e.length;u++){const h=e[u];switch(t[t.length-1]){case"ROOT":i(h,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(h){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{i(h,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(h,u);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),r=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=u}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{r=u,t.pop();break}default:{r=u,i(h,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}default:{r=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{i(h,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),h==="u"?(o=0,t.push("INSIDE_STRING_UNICODE_ESCAPE")):r=u;break}case"INSIDE_STRING_UNICODE_ESCAPE":{a(h)&&(o++,o===4&&(t.pop(),r=u));break}case"INSIDE_NUMBER":{switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(h,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(h,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,u+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(h,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u)):r=u;break}}}let c=e.slice(0,r+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{c+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const p=e.substring(n,e.length);"true".startsWith(p)?c+="true".slice(p.length):"false".startsWith(p)?c+="false".slice(p.length):"null".startsWith(p)&&(c+="null".slice(p.length))}}return c}async function fa(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await gr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await gr({text:F5(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Es=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),V5=({schema:e,name:t,description:r})=>{const n=yn(e);return{name:"object",responseFormat:yt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},a){const i=await gr({text:o});if(!i.success)throw new vn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await ar({value:i.value,schema:n});if(!s.success)throw new vn({message:"No object generated: response did not match schema.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value},async parsePartialOutput({text:o}){const a=await fa(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){}}},Z5=({element:e,name:t,description:r})=>{const n=yn(e);return{name:"array",responseFormat:yt(n.jsonSchema).then(o=>{const{$schema:a,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},a){const i=await gr({text:o});if(!i.success)throw new vn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=i.value;if(s==null||typeof s!="object"||!("elements"in s)||!Array.isArray(s.elements))throw new vn({message:"No object generated: response did not match schema.",cause:new An({value:s,cause:"response must be an object with an elements array"}),text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});for(const l of s.elements){const c=await ar({value:l,schema:n});if(!c.success)throw new vn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason})}return s.elements},async parsePartialOutput({text:o}){const a=await fa(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;const s=a.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(const c of s){const u=await ar({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:a},i){if(a!=null)for(;o<a.length;o++)i.enqueue(a[o])}})}}},H5=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const a=await gr({text:n});if(!a.success)throw new vn({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!e.includes(i.result))throw new vn({message:"No object generated: response did not match schema.",cause:new An({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){const o=await fa(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=o.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string")return;const i=e.filter(s=>s.startsWith(a.result));return o.state==="successful-parse"?i.includes(a.result)?{partial:a.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),B5=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await gr({text:r});if(!o.success)throw new vn({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await fa(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function e2({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await t2(e);throw new pc({toolName:e.toolName})}try{return await r2({toolCall:e,tools:t})}catch(a){if(r==null||!(pc.isInstance(a)||ks.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:s})=>{const{inputSchema:l}=t[s];return await yn(l).jsonSchema},system:n,messages:o,error:a})}catch(s){throw new KT({cause:s,originalError:a})}if(i==null)throw a;return await r2({toolCall:i,tools:t})}}catch(a){const i=await gr({text:e.input}),s=i.success?i.value:e.input,l=t?.[e.toolName];return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:a,title:l?.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...l?.metadata!=null?{toolMetadata:l.metadata}:{}}}}async function t2(e){const t=e.input.trim()===""?{success:!0,value:{}}:await gr({text:e.input});if(t.success===!1)throw new ks({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function r2({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await t2(e);throw new pc({toolName:e.toolName,availableTools:Object.keys(t)})}const o=yn(n.inputSchema),a=e.input.trim()===""?await ar({value:{},schema:o}):await gr({text:e.input,schema:o});if(a.success===!1)throw new ks({toolName:r,toolInput:e.input,cause:a.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...n.metadata!=null?{toolMetadata:n.metadata}:{},dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...n.metadata!=null?{toolMetadata:n.metadata}:{},title:n.title}}var n2=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:a,finishReason:i,rawFinishReason:s,usage:l,warnings:c,request:u,response:h,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=a,this.finishReason=i,this.rawFinishReason=s,this.usage=l,this.warnings=c,this.request=u,this.response=h,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Sc(e){return({steps:t})=>t.length===e}async function o2({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Ic({content:e,tools:t}){const r=[],n=[];for(const a of e)if(a.type!=="source"&&!((a.type==="tool-result"||a.type==="tool-error")&&!a.providerExecuted)&&!(a.type==="text"&&a.text.length===0))switch(a.type){case"text":n.push({type:"text",text:a.text,providerOptions:a.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:a.text,providerOptions:a.providerMetadata});break;case"file":n.push({type:"file",data:a.file.base64,mediaType:a.file.mediaType,providerOptions:a.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.invalid&&typeof a.input!="object"?{}:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":{const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-error":{const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:a.approvalId,toolCallId:a.toolCall.toolCallId,...a.signature!=null?{signature:a.signature}:{}});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const a of e){if(!(a.type==="tool-result"||a.type==="tool-error")||a.providerExecuted)continue;const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.type==="tool-result"?a.output:a.error,errorMode:a.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,...a.providerMetadata!=null?{providerOptions:a.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function a2(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var J5=na({prefix:"aitxt",size:24});async function s2({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:i,maxRetries:s,abortSignal:l,timeout:c,headers:u,stopWhen:h=Sc(1),experimental_output:p,output:m=p,experimental_telemetry:f,providerOptions:b,experimental_activeTools:w,activeTools:C=w,experimental_prepareStep:v,prepareStep:g=v,experimental_repairToolCall:I,experimental_download:y,experimental_context:_,experimental_toolApprovalSecret:k,experimental_include:S,_internal:{generateId:E=J5}={},experimental_onStart:R,experimental_onStepStart:x,experimental_onToolCallStart:N,experimental_onToolCallFinish:U,onStepFinish:z,onFinish:ee,...Q}){const se=Cs(e),re=Um(),Se=Bn(h),H=fc(c),D=Cm(c),B=D!=null?new AbortController:void 0,F=a2(l,H!=null?AbortSignal.timeout(H):void 0,B?.signal),{maxRetries:$,retry:O}=Vm({maxRetries:s,abortSignal:F}),j=_c(Q),G=_n(u??{},`ai/${Sm}`),Y=qm({model:se,telemetry:f,headers:G,settings:{...j,maxRetries:$}}),W={provider:se.provider,modelId:se.modelId},V=await Am({system:n,prompt:o,messages:a,allowSystemInMessages:i}),A=re(f?.integrations);await xr({event:{model:W,system:n,prompt:o,messages:a,tools:t,toolChoice:r,activeTools:C,maxOutputTokens:j.maxOutputTokens,temperature:j.temperature,topP:j.topP,topK:j.topK,presencePenalty:j.presencePenalty,frequencyPenalty:j.frequencyPenalty,stopSequences:j.stopSequences,seed:j.seed,maxRetries:$,timeout:c,headers:u,providerOptions:b,stopWhen:h,output:m,abortSignal:l,include:S,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_},callbacks:[R,A.onStart]});const Z=Lm(f);try{return await ha({name:"ai.generateText",attributes:vr({telemetry:f,attributes:{...pa({operationId:"ai.generateText",telemetry:f}),...Y,"ai.model.provider":se.provider,"ai.model.id":se.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:a})}}}),tracer:Z,fn:async J=>{var te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr,rr,Lr,pr,P,X,Ie,We,ln;const nt=V.messages,ht=[],{approvedToolApprovals:Ut,deniedToolApprovals:hr}=Zm({messages:nt}),{approvedToolApprovals:jr,deniedToolApprovals:Dr}=await Xm({approvedToolApprovals:Ut.filter(zt=>!zt.toolCall.providerExecuted),tools:t,messages:nt,experimental_context:_,toolApprovalSecret:k}),ie=[...hr,...Dr];if(ie.length>0||jr.length>0){const zt=await i2({toolCalls:jr.map(Ne=>Ne.toolCall),tools:t,tracer:Z,telemetry:f,messages:nt,abortSignal:F,experimental_context:_,stepNumber:0,model:W,onToolCallStart:[N,A.onToolCallStart],onToolCallFinish:[U,A.onToolCallFinish]}),Bt=[];for(const Ne of zt){const nr=await da({toolCallId:Ne.toolCallId,input:Ne.input,tool:t?.[Ne.toolName],output:Ne.type==="tool-result"?Ne.output:Ne.error,errorMode:Ne.type==="tool-error"?"text":"none"});Bt.push({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,output:nr})}for(const Ne of ie)Bt.push({type:"tool-result",toolCallId:Ne.toolCall.toolCallId,toolName:Ne.toolCall.toolName,output:{type:"execution-denied",reason:Ne.approvalResponse.reason,...Ne.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ne.approvalResponse.approvalId}}}}});ht.push({role:"tool",content:Bt})}const Ve=_c(Q);let De,ft=[],Me=[];const Ue=[],xn=new Map;do{const zt=D!=null?setTimeout(()=>B.abort(),D):void 0;try{const Bt=[...nt,...ht],Ne=await g?.({model:se,steps:Ue,stepNumber:Ue.length,messages:Bt,experimental_context:_}),nr=Cs((te=Ne?.model)!=null?te:se),En={provider:nr.provider,modelId:nr.modelId},cn=await xm({prompt:{system:(de=Ne?.system)!=null?de:V.system,messages:(fe=Ne?.messages)!=null?fe:Bt},supportedUrls:await nr.supportedUrls,download:y});_=(Ye=Ne?.experimental_context)!=null?Ye:_;const al=(wt=Ne?.activeTools)!=null?wt:C,{toolChoice:$n,tools:so}=await Rm({tools:t,toolChoice:(st=Ne?.toolChoice)!=null?st:r,activeTools:al}),Rn=(et=Ne?.messages)!=null?et:Bt,Tt=(Be=Ne?.system)!=null?Be:V.system,Ur=Is(b,Ne?.providerOptions);await xr({event:{stepNumber:Ue.length,model:En,system:Tt,messages:Rn,tools:t,toolChoice:$n,activeTools:al,steps:[...Ue],providerOptions:Ur,timeout:c,headers:u,stopWhen:h,output:m,abortSignal:l,include:S,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_},callbacks:[x,A.onStepStart]}),De=await O(()=>{var Re;return ha({name:"ai.generateText.doGenerate",attributes:vr({telemetry:f,attributes:{...pa({operationId:"ai.generateText.doGenerate",telemetry:f}),...Y,"ai.model.provider":nr.provider,"ai.model.id":nr.modelId,"ai.prompt.messages":{input:()=>Dm(cn)},"ai.prompt.tools":{input:()=>so?.map(Jt=>JSON.stringify(Jt))},"ai.prompt.toolChoice":{input:()=>$n!=null?JSON.stringify($n):void 0},"gen_ai.system":nr.provider,"gen_ai.request.model":nr.modelId,"gen_ai.request.frequency_penalty":Q.frequencyPenalty,"gen_ai.request.max_tokens":Q.maxOutputTokens,"gen_ai.request.presence_penalty":Q.presencePenalty,"gen_ai.request.stop_sequences":Q.stopSequences,"gen_ai.request.temperature":(Re=Q.temperature)!=null?Re:void 0,"gen_ai.request.top_k":Q.topK,"gen_ai.request.top_p":Q.topP}}),tracer:Z,fn:async Jt=>{var Gr,Ft,Fa,il,ll,Mn,On,zo;const Qe=await nr.doGenerate({...Ve,tools:so,toolChoice:$n,responseFormat:await m?.responseFormat,prompt:cn,providerOptions:Ur,abortSignal:F,headers:G}),fr={id:(Ft=(Gr=Qe.response)==null?void 0:Gr.id)!=null?Ft:E(),timestamp:(il=(Fa=Qe.response)==null?void 0:Fa.timestamp)!=null?il:new Date,modelId:(Mn=(ll=Qe.response)==null?void 0:ll.modelId)!=null?Mn:nr.modelId,headers:(On=Qe.response)==null?void 0:On.headers,body:(zo=Qe.response)==null?void 0:zo.body},Va=vc(Qe.usage);return Jt.setAttributes(await vr({telemetry:f,attributes:{"ai.response.finishReason":Qe.finishReason.unified,"ai.response.text":{output:()=>Bm(Qe.content)},"ai.response.reasoning":{output:()=>Hm(Qe.content)},"ai.response.toolCalls":{output:()=>{const Fo=l2(Qe.content);return Fo==null?void 0:JSON.stringify(Fo)}},"ai.response.id":fr.id,"ai.response.model":fr.modelId,"ai.response.timestamp":fr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Qe.providerMetadata),"ai.usage.inputTokens":Qe.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Qe.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Qe.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Qe.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Qe.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Qe.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.totalTokens":Va.totalTokens,"ai.usage.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Qe.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Qe.finishReason.unified],"gen_ai.response.id":fr.id,"gen_ai.response.model":fr.modelId,"gen_ai.usage.input_tokens":Qe.usage.inputTokens.total,"gen_ai.usage.output_tokens":Qe.usage.outputTokens.total}})),{...Qe,response:fr}}})});const Pn=await Promise.all(De.content.filter(Re=>Re.type==="tool-call").map(Re=>e2({toolCall:Re,tools:t,repairToolCall:I,system:n,messages:Bt}))),Uo={};for(const Re of Pn){if(Re.invalid)continue;const Jt=t?.[Re.toolName];if(Jt!=null&&(Jt?.onInputAvailable!=null&&await Jt.onInputAvailable({input:Re.input,toolCallId:Re.toolCallId,messages:Bt,abortSignal:F,experimental_context:_}),await kc({tool:Jt,toolCall:Re,messages:Bt,experimental_context:_}))){const Gr=E(),Ft=await Qm({secret:k,approvalId:Gr,toolCallId:Re.toolCallId,toolName:Re.toolName,input:Re.input});Uo[Re.toolCallId]={type:"tool-approval-request",approvalId:Gr,toolCall:Re,...Ft!=null?{signature:Ft}:{}}}}const sl=Pn.filter(Re=>Re.invalid&&Re.dynamic);Me=[];for(const Re of sl)Me.push({type:"tool-error",toolCallId:Re.toolCallId,toolName:Re.toolName,input:Re.input,error:Ll(Re.error),dynamic:!0});ft=Pn.filter(Re=>!Re.providerExecuted),t!=null&&Me.push(...await i2({toolCalls:ft.filter(Re=>!Re.invalid&&Uo[Re.toolCallId]==null),tools:t,tracer:Z,telemetry:f,messages:Bt,abortSignal:F,experimental_context:_,stepNumber:Ue.length,model:En,onToolCallStart:[N,A.onToolCallStart],onToolCallFinish:[U,A.onToolCallFinish]}));for(const Re of Pn){if(!Re.providerExecuted)continue;const Jt=t?.[Re.toolName];Jt?.type==="provider"&&Jt.supportsDeferredResults&&(De.content.some(Ft=>Ft.type==="tool-result"&&Ft.toolCallId===Re.toolCallId)||xn.set(Re.toolCallId,{toolName:Re.toolName}))}for(const Re of De.content)Re.type==="tool-result"&&xn.delete(Re.toolCallId);const io=W5({content:De.content,toolCalls:Pn,toolOutputs:Me,toolApprovalRequests:Object.values(Uo),tools:t});ht.push(...await Ic({content:io,tools:t}));const Ua=(tr=S?.requestBody)==null||tr?(it=De.request)!=null?it:{}:{...De.request,body:void 0},Nd={...De.response,messages:structuredClone(ht),body:(qr=S?.responseBody)==null||qr?(dr=De.response)==null?void 0:dr.body:void 0},qd=Ue.length,za=new n2({stepNumber:qd,model:En,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_,content:io,finishReason:De.finishReason.unified,rawFinishReason:De.finishReason.raw,usage:vc(De.usage),warnings:De.warnings,providerMetadata:De.providerMetadata,request:Ua,response:Nd});hc({warnings:(rr=De.warnings)!=null?rr:[],provider:En.provider,model:En.modelId}),Ue.push(za),await xr({event:za,callbacks:[z,A.onStepFinish]})}finally{zt!=null&&clearTimeout(zt)}}while((ft.length>0&&Me.length===ft.length||xn.size>0)&&!await o2({stopConditions:Se,steps:Ue}));J.setAttributes(await vr({telemetry:f,attributes:{"ai.response.finishReason":De.finishReason.unified,"ai.response.text":{output:()=>Bm(De.content)},"ai.response.reasoning":{output:()=>Hm(De.content)},"ai.response.toolCalls":{output:()=>{const zt=l2(De.content);return zt==null?void 0:JSON.stringify(zt)}},"ai.response.providerMetadata":JSON.stringify(De.providerMetadata)}}));const Ee=Ue[Ue.length-1],lt=Ue.reduce((zt,Bt)=>zm(zt,Bt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});J.setAttributes(await vr({telemetry:f,attributes:{"ai.usage.inputTokens":lt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Lr=lt.inputTokenDetails)==null?void 0:Lr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(pr=lt.inputTokenDetails)==null?void 0:pr.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(P=lt.inputTokenDetails)==null?void 0:P.cacheWriteTokens,"ai.usage.outputTokens":lt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(X=lt.outputTokenDetails)==null?void 0:X.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ie=lt.outputTokenDetails)==null?void 0:Ie.reasoningTokens,"ai.usage.totalTokens":lt.totalTokens,"ai.usage.reasoningTokens":(We=lt.outputTokenDetails)==null?void 0:We.reasoningTokens,"ai.usage.cachedInputTokens":(ln=lt.inputTokenDetails)==null?void 0:ln.cacheReadTokens}})),await xr({event:{stepNumber:Ee.stepNumber,model:Ee.model,functionId:Ee.functionId,metadata:Ee.metadata,experimental_context:Ee.experimental_context,finishReason:Ee.finishReason,rawFinishReason:Ee.rawFinishReason,usage:Ee.usage,content:Ee.content,text:Ee.text,reasoningText:Ee.reasoningText,reasoning:Ee.reasoning,files:Ee.files,sources:Ee.sources,toolCalls:Ee.toolCalls,staticToolCalls:Ee.staticToolCalls,dynamicToolCalls:Ee.dynamicToolCalls,toolResults:Ee.toolResults,staticToolResults:Ee.staticToolResults,dynamicToolResults:Ee.dynamicToolResults,request:Ee.request,response:Ee.response,warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,steps:Ue,totalUsage:lt},callbacks:[ee,A.onFinish]});let mt;return Ee.finishReason==="stop"&&(mt=await(m??Es()).parseCompleteOutput({text:Ee.text},{response:Ee.response,usage:Ee.usage,finishReason:Ee.finishReason})),new G5({steps:Ue,totalUsage:lt,output:mt})}})}catch(J){throw Nm(J)}}async function i2({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>bc({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var G5=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Ts;return this._output}};function l2(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function W5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const a=[];for(const i of e)switch(i.type){case"text":case"reasoning":case"source":a.push(i);break;case"file":{a.push({type:"file",file:new Jm(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{a.push(t.find(s=>s.toolCallId===i.toolCallId));break}case"tool-result":{const s=t.find(l=>l.toolCallId===i.toolCallId);if(s==null){const l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}});break}i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,error:i.result,providerExecuted:!0,dynamic:s.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...s.toolMetadata!=null?{toolMetadata:s.toolMetadata}:{}}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,output:i.result,providerExecuted:!0,dynamic:s.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...s.toolMetadata!=null?{toolMetadata:s.toolMetadata}:{}});break}case"tool-approval-request":{const s=t.find(l=>l.toolCallId===i.toolCallId);if(s==null)throw new dc({toolCallId:i.toolCallId,approvalId:i.approvalId});a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:s});break}}return[...a,...r,...n]}function $s(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function K5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:$s(r,{"content-type":"text/plain; charset=utf-8"})})}function c2({response:e,status:t,statusText:r,headers:n,stream:o}){const a=t??200;r!==void 0?e.writeHead(a,r,n):e.writeHead(a,n);const i=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await i.read();if(l)break;e.write(c)||await new Promise(h=>{e.once("drain",h)})}}catch(l){throw l}finally{e.end()}})()}function Y5({response:e,status:t,statusText:r,headers:n,textStream:o}){c2({response:e,status:t,statusText:r,headers:Object.fromEntries($s(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var u2=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
73
|
-
|
|
74
|
-
`)},flush(e){e.enqueue(`data: [DONE]
|
|
75
|
-
|
|
76
|
-
`)}})}},d2={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Q5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let a=n.pipeThrough(new u2);if(o){const[i,s]=a.tee();a=i,o({stream:s})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:$s(r,d2)})}function X5({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}pe(d(),Jn.optional());function eC(e){return e.type.startsWith("data-")}function Xr(){return Object.create(null)}function xc(e){return e.type.startsWith("tool-")}function tC(e){return e.type==="dynamic-tool"}function p2(e){return xc(e)||tC(e)}function h2(e){return e.type.split("-").slice(1).join("-")}function rC({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:Xr(),activeReasoningParts:Xr(),partialToolCalls:Xr()}}function nC({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:a,onData:i}){return e.pipeThrough(new TransformStream({async transform(s,l){await n(async({state:c,write:u})=>{var h,p,m,f;function b(g){const y=c.message.parts.filter(p2).find(_=>_.toolCallId===g);if(y==null)throw new To({chunkType:"tool-invocation",chunkId:g,message:`No tool invocation found for tool call ID "${g}".`});return y}function w(g){var I;const y=c.message.parts.find(S=>xc(S)&&S.toolCallId===g.toolCallId),_=g,k=y;if(y!=null){y.state=g.state,k.input=_.input,k.output=_.output,k.errorText=_.errorText,k.rawInput=_.rawInput,k.preliminary=_.preliminary,g.title!==void 0&&(k.title=g.title),g.toolMetadata!==void 0&&(k.toolMetadata=g.toolMetadata),k.providerExecuted=(I=_.providerExecuted)!=null?I:y.providerExecuted;const S=_.providerMetadata;if(S!=null)if(g.state==="output-available"||g.state==="output-error"){const E=y;E.resultProviderMetadata=S}else y.callProviderMetadata=S}else c.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,title:g.title,...g.toolMetadata!==void 0?{toolMetadata:g.toolMetadata}:{},input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:_.providerMetadata}:{},..._.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:_.providerMetadata}:{}})}function C(g){var I,y;const _=c.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===g.toolCallId),k=g,S=_;if(_!=null){_.state=g.state,S.toolName=g.toolName,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=(I=k.rawInput)!=null?I:S.rawInput,S.preliminary=k.preliminary,g.title!==void 0&&(S.title=g.title),g.toolMetadata!==void 0&&(S.toolMetadata=g.toolMetadata),S.providerExecuted=(y=k.providerExecuted)!=null?y:_.providerExecuted;const E=k.providerMetadata;if(E!=null)if(g.state==="output-available"||g.state==="output-error"){const R=_;R.resultProviderMetadata=E}else _.callProviderMetadata=E}else c.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,title:g.title,...g.toolMetadata!==void 0?{toolMetadata:g.toolMetadata}:{},...k.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:k.providerMetadata}:{},...k.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:k.providerMetadata}:{}})}async function v(g){if(g!=null){const I=c.message.metadata!=null?Is(c.message.metadata,g):g;t!=null&&await _t({value:I,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=I}}switch(s.type){case"text-start":{const g={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};c.activeTextParts[s.id]=g,c.message.parts.push(g),u();break}case"text-delta":{const g=c.activeTextParts[s.id];if(g==null)throw new To({chunkType:"text-delta",chunkId:s.id,message:`Received text-delta for missing text part with ID "${s.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});g.text+=s.delta,g.providerMetadata=(h=s.providerMetadata)!=null?h:g.providerMetadata,u();break}case"text-end":{const g=c.activeTextParts[s.id];if(g==null)throw new To({chunkType:"text-end",chunkId:s.id,message:`Received text-end for missing text part with ID "${s.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});g.state="done",g.providerMetadata=(p=s.providerMetadata)!=null?p:g.providerMetadata,delete c.activeTextParts[s.id],u();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};c.activeReasoningParts[s.id]=g,c.message.parts.push(g),u();break}case"reasoning-delta":{const g=c.activeReasoningParts[s.id];if(g==null)throw new To({chunkType:"reasoning-delta",chunkId:s.id,message:`Received reasoning-delta for missing reasoning part with ID "${s.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});g.text+=s.delta,g.providerMetadata=(m=s.providerMetadata)!=null?m:g.providerMetadata,u();break}case"reasoning-end":{const g=c.activeReasoningParts[s.id];if(g==null)throw new To({chunkType:"reasoning-end",chunkId:s.id,message:`Received reasoning-end for missing reasoning part with ID "${s.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});g.providerMetadata=(f=s.providerMetadata)!=null?f:g.providerMetadata,g.state="done",delete c.activeReasoningParts[s.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{}}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),u();break}case"tool-input-start":{const g=c.message.parts.filter(xc);c.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:g.length,dynamic:s.dynamic,title:s.title,toolMetadata:s.toolMetadata},s.dynamic?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted,title:s.title,toolMetadata:s.toolMetadata,providerMetadata:s.providerMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted,title:s.title,toolMetadata:s.toolMetadata,providerMetadata:s.providerMetadata}),u();break}case"tool-input-delta":{const g=c.partialToolCalls[s.toolCallId];if(g==null)throw new To({chunkType:"tool-input-delta",chunkId:s.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${s.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});g.text+=s.inputTextDelta;const{value:I}=await fa(g.text);g.dynamic?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"input-streaming",input:I,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:g.toolName,state:"input-streaming",input:I,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"tool-input-available":{s.dynamic?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:s.title,toolMetadata:s.toolMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:s.title,toolMetadata:s.toolMetadata}),u(),a&&!s.providerExecuted&&await a({toolCall:s});break}case"tool-input-error":{const g=c.message.parts.filter(p2).find(y=>y.toolCallId===s.toolCallId);(g!=null?g.type==="dynamic-tool":!!s.dynamic)?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata}),u();break}case"tool-approval-request":{const g=b(s.toolCallId);g.state="approval-requested",g.approval={id:s.approvalId,...s.signature!=null?{signature:s.signature}:{}},u();break}case"tool-output-denied":{const g=b(s.toolCallId);g.state="output-denied",u();break}case"tool-output-available":{const g=b(s.toolCallId);g.type==="dynamic-tool"?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:s.output,preliminary:s.preliminary,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:h2(g),state:"output-available",input:g.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"tool-output-error":{const g=b(s.toolCallId);g.type==="dynamic-tool"?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:h2(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts=Xr(),c.activeReasoningParts=Xr();break}case"start":{s.messageId!=null&&(c.message.id=s.messageId),await v(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&u();break}case"finish":{s.finishReason!=null&&(c.finishReason=s.finishReason),await v(s.messageMetadata),s.messageMetadata!=null&&u();break}case"message-metadata":{await v(s.messageMetadata),s.messageMetadata!=null&&u();break}case"error":{o?.(new Error(s.errorText));break}default:if(eC(s)){if(r?.[s.type]!=null){const y=c.message.parts.findIndex(k=>"id"in k&&"data"in k&&k.id===s.id&&k.type===s.type),_=y>=0?y:c.message.parts.length;await _t({value:s.data,schema:r[s.type],context:{field:`message.parts[${_}].data`,entityName:s.type,entityId:s.id}})}const g=s;if(g.transient){i?.(g);break}const I=g.id!=null?c.message.parts.find(y=>g.type===y.type&&g.id===y.id):void 0;I!=null?I.data=g.data:c.message.parts.push(g),i?.(g),u()}}l.enqueue(s)})}}))}function oC({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:a}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let s=!1;const l=a.pipeThrough(new TransformStream({transform(f,b){if(f.type==="start"){const w=f;w.messageId==null&&e!=null&&(w.messageId=e)}f.type==="abort"&&(s=!0),b.enqueue(f)}}));if(n==null&&r==null)return l;const c=rC({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async f=>{await f({state:c,write:()=>{}})};let h=!1;const p=async()=>{if(h||!n)return;h=!0;const f=c.message.id===i?.id;await n({isAborted:s,isContinuation:f,responseMessage:c.message,messages:[...f?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},m=async()=>{if(!r)return;const f=c.message.id===i?.id;try{await r({isContinuation:f,responseMessage:structuredClone(c.message),messages:[...f?t.slice(0,-1):t,structuredClone(c.message)]})}catch(b){o(b)}};return nC({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(f,b){f.type==="finish-step"&&await m(),b.enqueue(f)},async cancel(){await p()},async flush(){await p()}}))}function aC({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:a}){let i=o.pipeThrough(new u2);if(a){const[s,l]=i.tee();i=s,a({stream:l})}c2({response:e,status:t,statusText:r,headers:Object.fromEntries($s(n,d2).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function ma(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(a){var i;if(!n){n=!0;try{a&&await((i=r.cancel)==null?void 0:i.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:a,value:i}=await r.read();return a?(await o(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(a){throw await o(!0),a}}},t}async function sC({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function f2(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function iC(){let e=[],t=null,r=!1,n=f2();const o=()=>{r=!0,n.resolve(),e.forEach(i=>i.cancel()),e=[],t?.close()},a=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=f2(),await n.promise,a();try{const{value:i,done:s}=await e[0].read();s?(e.shift(),e.length===0&&r?t?.close():await a()):t?.enqueue(i)}catch(i){t?.error(i),e.shift(),o()}};return{stream:new ReadableStream({start(i){t=i},pull:a,async cancel(){for(const i of e)await i.cancel();e=[],r=!0}}),addStream:i=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(i.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function lC({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:a,abortSignal:i,repairToolCall:s,experimental_context:l,toolApprovalSecret:c,generateId:u,stepNumber:h,model:p,onToolCallStart:m,onToolCallFinish:f}){let b=null;const w=new ReadableStream({start(S){b=S}}),C=new Set,v=new Map,g=new Map;let I=!1,y;function _(){I&&C.size===0&&(y!=null&&b.enqueue(y),b.close())}const k=new TransformStream({async transform(S,E){const R=S.type;switch(R){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(S);break}case"file":{E.enqueue({type:"file",file:new L5({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{y={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:vc(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const x=g.get(S.toolCallId);if(x==null){b.enqueue({type:"error",error:new dc({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:x});break}case"tool-call":{try{const x=await e2({toolCall:S,tools:e,repairToolCall:s,system:o,messages:a});if(g.set(x.toolCallId,x),E.enqueue(x),x.invalid){b.enqueue({type:"tool-error",toolCallId:x.toolCallId,toolName:x.toolName,input:x.input,error:Ll(x.error),dynamic:!0,title:x.title,...x.toolMetadata!=null?{toolMetadata:x.toolMetadata}:{}});break}const N=e?.[x.toolName];if(N==null)break;if(N.onInputAvailable!=null&&await N.onInputAvailable({input:x.input,toolCallId:x.toolCallId,messages:a,abortSignal:i,experimental_context:l}),await kc({tool:N,toolCall:x,messages:a,experimental_context:l})){const U=u(),z=await Qm({secret:c,approvalId:U,toolCallId:x.toolCallId,toolName:x.toolName,input:x.input});b.enqueue({type:"tool-approval-request",approvalId:U,toolCall:x,...z!=null?{signature:z}:{}});break}if(v.set(x.toolCallId,x.input),N.execute!=null&&x.providerExecuted!==!0){const U=u();C.add(U),bc({toolCall:x,tools:e,tracer:r,telemetry:n,messages:a,abortSignal:i,experimental_context:l,stepNumber:h,model:p,onToolCallStart:m,onToolCallFinish:f,onPreliminaryToolResult:z=>{b.enqueue(z)}}).then(z=>{b.enqueue(z)}).catch(z=>{b.enqueue({type:"error",error:z})}).finally(()=>{C.delete(U),_()})}}catch(x){b.enqueue({type:"error",error:x})}break}case"tool-result":{const x=S.toolName,N=g.get(S.toolCallId);S.isError?b.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:x,input:v.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic,...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{},...N?.toolMetadata!=null?{toolMetadata:N.toolMetadata}:{}}):E.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:x,input:v.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic,...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{},...N?.toolMetadata!=null?{toolMetadata:N.toolMetadata}:{}});break}default:{const x=R;throw new Error(`Unhandled chunk type: ${x}`)}}},flush(){I=!0,_()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(E){S.enqueue(E)},close(){}})),w.pipeTo(new WritableStream({write(E){S.enqueue(E)},close(){S.close()}}))])}})}var cC=na({prefix:"aitxt",size:24}),uC={file:!0,source:!0,"text-start":!0,"text-end":!0,"text-delta":!0,"reasoning-start":!0,"reasoning-end":!0,"reasoning-delta":!0,"tool-input-start":!0,"tool-input-end":!0,"tool-input-delta":!0,"tool-approval-request":!0,"tool-call":!0,"tool-result":!0,"tool-error":!0,"stream-start":!1,"response-metadata":!1,finish:!1,error:!1,raw:!1};function Ec({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:i,maxRetries:s,abortSignal:l,timeout:c,headers:u,stopWhen:h=Sc(1),experimental_output:p,output:m=p,experimental_telemetry:f,prepareStep:b,providerOptions:w,experimental_activeTools:C,activeTools:v=C,experimental_repairToolCall:g,experimental_transform:I,experimental_download:y,includeRawChunks:_=!1,onChunk:k,onError:S=({error:B})=>{console.error(B)},onFinish:E,onAbort:R,onStepFinish:x,experimental_onStart:N,experimental_onStepStart:U,experimental_onToolCallStart:z,experimental_onToolCallFinish:ee,experimental_context:Q,experimental_toolApprovalSecret:se,experimental_include:re,_internal:{now:Se=xs,generateId:H=cC}={},...D}){const B=fc(c),F=Cm(c),$=l5(c),O=F!=null?new AbortController:void 0,j=$!=null?new AbortController:void 0;return new pC({model:Cs(e),telemetry:f,headers:u,settings:D,maxRetries:s,abortSignal:a2(l,B!=null?AbortSignal.timeout(B):void 0,O?.signal,j?.signal),stepTimeoutMs:F,stepAbortController:O,chunkTimeoutMs:$,chunkAbortController:j,system:n,prompt:o,messages:a,allowSystemInMessages:i,tools:t,toolChoice:r,transforms:Bn(I),activeTools:v,repairToolCall:g,stopConditions:Bn(h),output:m,providerOptions:w,prepareStep:b,includeRawChunks:_,timeout:c,stopWhen:h,originalAbortSignal:l,onChunk:k,onError:S,onFinish:E,onAbort:R,onStepFinish:x,onStart:N,onStepStart:U,onToolCallStart:z,onToolCallFinish:ee,now:Se,generateId:H,experimental_context:Q,experimental_toolApprovalSecret:se,download:y,include:re})}function dC(e){let t,r="",n="",o,a="";function i({controller:s,partialOutput:l=void 0}){s.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(s,l){var c;if(s.type==="finish-step"&&n.length>0&&i({controller:l}),s.type!=="text-delta"&&s.type!=="text-start"&&s.type!=="text-end"){l.enqueue({part:s,partialOutput:void 0});return}if(t==null)t=s.id;else if(s.id!==t){l.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-start"){l.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-end"){n.length>0&&i({controller:l}),l.enqueue({part:s,partialOutput:void 0});return}r+=s.text,n+=s.text,o=(c=s.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const h=typeof u.partial=="string"?u.partial:JSON.stringify(u.partial);h!==a&&(i({controller:l,partialOutput:u.partial}),a=h)}}})}var pC=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:a,stepTimeoutMs:i,stepAbortController:s,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:h,messages:p,allowSystemInMessages:m,tools:f,toolChoice:b,transforms:w,activeTools:C,repairToolCall:v,stopConditions:g,output:I,providerOptions:y,prepareStep:_,includeRawChunks:k,now:S,generateId:E,timeout:R,stopWhen:x,originalAbortSignal:N,onChunk:U,onError:z,onFinish:ee,onAbort:Q,onStepFinish:se,onStart:re,onStepStart:Se,onToolCallStart:H,onToolCallFinish:D,experimental_context:B,experimental_toolApprovalSecret:F,download:$,include:O}){this._totalUsage=new ra,this._finishReason=new ra,this._rawFinishReason=new ra,this._steps=new ra,this.outputSpecification=I,this.includeRawChunks=k,this.tools=f;const G=Um()(t?.integrations);let Y,W=[];const V=[];let A,Z,J,te={},de=[];const fe=[];let Ye;const wt=new Map;let st,et=Xr(),Be=Xr();const tr=new TransformStream({async transform(nt,ht){var Ut,hr,jr,Dr;ht.enqueue(nt);const{part:ie}=nt;if((ie.type==="text-delta"||ie.type==="reasoning-delta"||ie.type==="source"||ie.type==="tool-call"||ie.type==="tool-result"||ie.type==="tool-input-start"||ie.type==="tool-input-delta"||ie.type==="raw")&&await U?.({chunk:ie}),ie.type==="error"){const Ve=Nm(ie.error);Ts.isInstance(Ve)&&(Ye=Ve),await z({error:Ve})}if(ie.type==="text-start"&&(et[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},W.push(et[ie.id])),ie.type==="text-delta"){const Ve=et[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Ve.text+=ie.text,Ve.providerMetadata=(Ut=ie.providerMetadata)!=null?Ut:Ve.providerMetadata}if(ie.type==="text-end"){const Ve=et[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(hr=ie.providerMetadata)!=null?hr:Ve.providerMetadata,delete et[ie.id]}if(ie.type==="reasoning-start"&&(Be[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},W.push(Be[ie.id])),ie.type==="reasoning-delta"){const Ve=Be[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Ve.text+=ie.text,Ve.providerMetadata=(jr=ie.providerMetadata)!=null?jr:Ve.providerMetadata}if(ie.type==="reasoning-end"){const Ve=Be[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(Dr=ie.providerMetadata)!=null?Dr:Ve.providerMetadata,delete Be[ie.id]}if(ie.type==="file"&&W.push({type:"file",file:ie.file,...ie.providerMetadata!=null?{providerMetadata:ie.providerMetadata}:{}}),ie.type==="source"&&W.push(ie),ie.type==="tool-call"&&W.push(ie),ie.type==="tool-result"&&!ie.preliminary&&W.push(ie),ie.type==="tool-approval-request"&&W.push(ie),ie.type==="tool-error"&&W.push(ie),ie.type==="start-step"&&(W=[],Be=Xr(),et=Xr(),te=ie.request,de=ie.warnings),ie.type==="finish-step"){const Ve=await Ic({content:W,tools:f}),De=new n2({stepNumber:fe.length,model:We,...ln,experimental_context:B,content:W,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:de,request:te,response:{...ie.response,messages:[...V,...Ve]},providerMetadata:ie.providerMetadata});await xr({event:De,callbacks:[se,G.onStepFinish]}),hc({warnings:de,provider:We.provider,model:We.modelId}),fe.push(De),V.push(...Ve),Y.resolve()}ie.type==="finish"&&(J=ie.totalUsage,A=ie.finishReason,Z=ie.rawFinishReason)},async flush(nt){var ht,Ut,hr,jr,Dr,ie,Ve;try{if(fe.length===0||Ye!=null){const Ue=a?.aborted?a.reason:Ye??new Ts({message:"No output generated. Check the stream for errors."});Ie._finishReason.reject(Ue),Ie._rawFinishReason.reject(Ue),Ie._totalUsage.reject(Ue),Ie._steps.reject(Ue);return}const De=A??"other",ft=J??wc();Ie._finishReason.resolve(De),Ie._rawFinishReason.resolve(Z),Ie._totalUsage.resolve(ft),Ie._steps.resolve(fe);const Me=fe[fe.length-1];await xr({event:{stepNumber:Me.stepNumber,model:Me.model,functionId:Me.functionId,metadata:Me.metadata,experimental_context:Me.experimental_context,finishReason:Me.finishReason,rawFinishReason:Me.rawFinishReason,totalUsage:ft,usage:Me.usage,content:Me.content,text:Me.text,reasoningText:Me.reasoningText,reasoning:Me.reasoning,files:Me.files,sources:Me.sources,toolCalls:Me.toolCalls,staticToolCalls:Me.staticToolCalls,dynamicToolCalls:Me.dynamicToolCalls,toolResults:Me.toolResults,staticToolResults:Me.staticToolResults,dynamicToolResults:Me.dynamicToolResults,request:Me.request,response:Me.response,warnings:Me.warnings,providerMetadata:Me.providerMetadata,steps:fe},callbacks:[ee,G.onFinish]}),st.setAttributes(await vr({telemetry:t,attributes:{"ai.response.finishReason":De,"ai.response.text":{output:()=>Me.text},"ai.response.reasoning":{output:()=>Me.reasoningText},"ai.response.toolCalls":{output:()=>{var Ue;return(Ue=Me.toolCalls)!=null&&Ue.length?JSON.stringify(Me.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.inputTokens":ft.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ht=ft.inputTokenDetails)==null?void 0:ht.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ut=ft.inputTokenDetails)==null?void 0:Ut.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(hr=ft.inputTokenDetails)==null?void 0:hr.cacheWriteTokens,"ai.usage.outputTokens":ft.outputTokens,"ai.usage.outputTokenDetails.textTokens":(jr=ft.outputTokenDetails)==null?void 0:jr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Dr=ft.outputTokenDetails)==null?void 0:Dr.reasoningTokens,"ai.usage.totalTokens":ft.totalTokens,"ai.usage.reasoningTokens":(ie=ft.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":(Ve=ft.inputTokenDetails)==null?void 0:Ve.cacheReadTokens}}))}catch(De){nt.error(De)}finally{st.end()}}}),it=iC();this.addStream=it.addStream,this.closeStream=it.close;const qr=it.stream.getReader();let dr=new ReadableStream({async start(nt){nt.enqueue({type:"start"})},async pull(nt){function ht(){Q?.({steps:fe}),nt.enqueue({type:"abort",...a?.reason!==void 0?{reason:co(a.reason)}:{}}),nt.close()}try{const{done:Ut,value:hr}=await qr.read();if(Ut){nt.close();return}if(a?.aborted){ht();return}nt.enqueue(hr)}catch(Ut){zn(Ut)&&a?.aborted?ht():nt.error(Ut)}},cancel(nt){return it.stream.cancel(nt)}});for(const nt of w)dr=dr.pipeThrough(nt({tools:f,stopStream(){it.terminate()}}));this.baseStream=dr.pipeThrough(dC(I??Es())).pipeThrough(tr);const{maxRetries:rr,retry:Lr}=Vm({maxRetries:o,abortSignal:a}),pr=Lm(t),P=_c(n),X=qm({model:e,telemetry:t,headers:r,settings:{...P,maxRetries:rr}}),Ie=this,We={provider:e.provider,modelId:e.modelId},ln={functionId:t?.functionId,metadata:t?.metadata};ha({name:"ai.streamText",attributes:vr({telemetry:t,attributes:{...pa({operationId:"ai.streamText",telemetry:t}),...X,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:pr,endWhenDone:!1,fn:async nt=>{st=nt;const ht=await Am({system:u,prompt:h,messages:p,allowSystemInMessages:m});await xr({event:{model:We,system:u,prompt:h,messages:p,tools:f,toolChoice:b,activeTools:C,maxOutputTokens:P.maxOutputTokens,temperature:P.temperature,topP:P.topP,topK:P.topK,presencePenalty:P.presencePenalty,frequencyPenalty:P.frequencyPenalty,stopSequences:P.stopSequences,seed:P.seed,maxRetries:rr,timeout:R,headers:r,providerOptions:y,stopWhen:x,output:I,abortSignal:N,include:O,...ln,experimental_context:B},callbacks:[re,G.onStart]});const Ut=ht.messages,hr=[],{approvedToolApprovals:jr,deniedToolApprovals:Dr}=Zm({messages:Ut});if(Dr.length>0||jr.length>0){const{approvedToolApprovals:Ve,deniedToolApprovals:De}=await Xm({approvedToolApprovals:jr.filter(Ee=>!Ee.toolCall.providerExecuted),tools:f,messages:Ut,experimental_context:B,toolApprovalSecret:F}),ft=[...Dr.filter(Ee=>!Ee.toolCall.providerExecuted),...De],Me=Dr.filter(Ee=>Ee.toolCall.providerExecuted);let Ue;const xn=new ReadableStream({start(Ee){Ue=Ee}});Ie.addStream(xn);try{for(const lt of[...ft,...Me])Ue?.enqueue({type:"tool-output-denied",toolCallId:lt.toolCall.toolCallId,toolName:lt.toolCall.toolName});const Ee=[];if(await Promise.all(Ve.map(async lt=>{const mt=await bc({toolCall:lt.toolCall,tools:f,tracer:pr,telemetry:t,messages:Ut,abortSignal:a,experimental_context:B,stepNumber:fe.length,model:We,onToolCallStart:[H,G.onToolCallStart],onToolCallFinish:[D,G.onToolCallFinish],onPreliminaryToolResult:zt=>{Ue?.enqueue(zt)}});mt!=null&&(Ue?.enqueue(mt),Ee.push(mt))})),Ee.length>0||ft.length>0){const lt=[];for(const mt of Ee)lt.push({type:"tool-result",toolCallId:mt.toolCallId,toolName:mt.toolName,output:await da({toolCallId:mt.toolCallId,input:mt.input,tool:f?.[mt.toolName],output:mt.type==="tool-result"?mt.output:mt.error,errorMode:mt.type==="tool-error"?"text":"none"})});for(const mt of ft)lt.push({type:"tool-result",toolCallId:mt.toolCall.toolCallId,toolName:mt.toolCall.toolName,output:{type:"execution-denied",reason:mt.approvalResponse.reason}});hr.push({role:"tool",content:lt})}}finally{Ue?.close()}}V.push(...hr);async function ie({currentStep:Ve,responseMessages:De,usage:ft}){var Me,Ue,xn,Ee,lt,mt,zt,Bt,Ne;const nr=Ie.includeRawChunks,En=i!=null?setTimeout(()=>s.abort(),i):void 0;let cn;function al(){l!=null&&(cn!=null&&clearTimeout(cn),cn=setTimeout(()=>c.abort(),l))}function $n(){cn!=null&&(clearTimeout(cn),cn=void 0)}function so(){En!=null&&clearTimeout(En)}try{Y=new ra;const Rn=[...Ut,...De],Tt=await _?.({model:e,steps:fe,stepNumber:fe.length,messages:Rn,experimental_context:B}),Ur=Cs((Me=Tt?.model)!=null?Me:e),Pn={provider:Ur.provider,modelId:Ur.modelId},Uo=await xm({prompt:{system:(Ue=Tt?.system)!=null?Ue:ht.system,messages:(xn=Tt?.messages)!=null?xn:Rn},supportedUrls:await Ur.supportedUrls,download:$}),sl=(Ee=Tt?.activeTools)!=null?Ee:C,{toolChoice:io,tools:Ua}=await Rm({tools:f,toolChoice:(lt=Tt?.toolChoice)!=null?lt:b,activeTools:sl});B=(mt=Tt?.experimental_context)!=null?mt:B;const Nd=(zt=Tt?.messages)!=null?zt:Rn,qd=(Bt=Tt?.system)!=null?Bt:ht.system,za=Is(y,Tt?.providerOptions);await xr({event:{stepNumber:fe.length,model:Pn,system:qd,messages:Nd,tools:f,toolChoice:io,activeTools:sl,steps:[...fe],providerOptions:za,timeout:R,headers:r,stopWhen:x,output:I,abortSignal:N,include:O,...ln,experimental_context:B},callbacks:[Se,G.onStepStart]});const{result:{stream:Re,response:Jt,request:Gr},doStreamSpan:Ft,startTimestampMs:Fa}=await Lr(()=>ha({name:"ai.streamText.doStream",attributes:vr({telemetry:t,attributes:{...pa({operationId:"ai.streamText.doStream",telemetry:t}),...X,"ai.model.provider":Ur.provider,"ai.model.id":Ur.modelId,"ai.prompt.messages":{input:()=>Dm(Uo)},"ai.prompt.tools":{input:()=>Ua?.map(ke=>JSON.stringify(ke))},"ai.prompt.toolChoice":{input:()=>io!=null?JSON.stringify(io):void 0},"gen_ai.system":Ur.provider,"gen_ai.request.model":Ur.modelId,"gen_ai.request.frequency_penalty":P.frequencyPenalty,"gen_ai.request.max_tokens":P.maxOutputTokens,"gen_ai.request.presence_penalty":P.presencePenalty,"gen_ai.request.stop_sequences":P.stopSequences,"gen_ai.request.temperature":P.temperature,"gen_ai.request.top_k":P.topK,"gen_ai.request.top_p":P.topP}}),tracer:pr,endWhenDone:!1,fn:async ke=>({startTimestampMs:S(),doStreamSpan:ke,result:await Ur.doStream({...P,tools:Ua,toolChoice:io,responseFormat:await I?.responseFormat,prompt:Uo,providerOptions:za,abortSignal:a,headers:r,includeRawChunks:nr})})})),il=lC({tools:f,generatorStream:Re,tracer:pr,telemetry:t,system:u,messages:Rn,repairToolCall:v,abortSignal:a,experimental_context:B,toolApprovalSecret:F,generateId:E,stepNumber:fe.length,model:Pn,onToolCallStart:[H,G.onToolCallStart],onToolCallFinish:[D,G.onToolCallFinish]}),ll=(Ne=O?.requestBody)==null||Ne?Gr??{}:{...Gr,body:void 0},Mn=[],On=[];let zo;const Qe={};let fr="other",Va,Fo=!1,p1=!1,Gt=wc(),h1,f1=!0,Wr={id:E(),timestamp:new Date,modelId:We.modelId},UR="";Ie.addStream(il.pipeThrough(new TransformStream({async transform(ke,Mt){var Za,Ha,Ba,Ja,Ga;if(al(),ke.type==="stream-start"){zo=ke.warnings;return}if(f1){const Et=S()-Fa;f1=!1,Ft.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Et}),Ft.setAttributes({"ai.response.msToFirstChunk":Et}),Mt.enqueue({type:"start-step",request:ll,warnings:zo??[]})}const Vo=ke.type;switch(uC[Vo]&&(p1=!0),Vo){case"tool-approval-request":case"text-start":case"text-end":{Mt.enqueue(ke);break}case"text-delta":{ke.delta.length>0&&(Mt.enqueue({type:"text-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata}),UR+=ke.delta);break}case"reasoning-start":case"reasoning-end":{Mt.enqueue(ke);break}case"reasoning-delta":{Mt.enqueue({type:"reasoning-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata});break}case"tool-call":{Mt.enqueue(ke),Mn.push(ke);break}case"tool-result":{Mt.enqueue(ke),ke.preliminary||On.push(ke);break}case"tool-error":{Mt.enqueue(ke),On.push(ke);break}case"response-metadata":{Wr={id:(Za=ke.id)!=null?Za:Wr.id,timestamp:(Ha=ke.timestamp)!=null?Ha:Wr.timestamp,modelId:(Ba=ke.modelId)!=null?Ba:Wr.modelId};break}case"finish":{Fo=!0,Gt=ke.usage,fr=ke.finishReason,Va=ke.rawFinishReason,h1=ke.providerMetadata;const Et=S()-Fa;Ft.addEvent("ai.stream.finish"),Ft.setAttributes({"ai.response.msToFinish":Et,"ai.response.avgOutputTokensPerSecond":1e3*((Ja=Gt.outputTokens)!=null?Ja:0)/Et});break}case"file":{Mt.enqueue(ke);break}case"source":{Mt.enqueue(ke);break}case"tool-input-start":{Qe[ke.id]=ke.toolName;const Et=f?.[ke.toolName];Et?.onInputStart!=null&&await Et.onInputStart({toolCallId:ke.id,messages:Rn,abortSignal:a,experimental_context:B}),Mt.enqueue({...ke,dynamic:(Ga=ke.dynamic)!=null?Ga:Et?.type==="dynamic",title:Et?.title});break}case"tool-input-end":{delete Qe[ke.id],Mt.enqueue(ke);break}case"tool-input-delta":{const Et=Qe[ke.id],Zo=f?.[Et];Zo?.onInputDelta!=null&&await Zo.onInputDelta({inputTextDelta:ke.delta,toolCallId:ke.id,messages:Rn,abortSignal:a,experimental_context:B}),Mt.enqueue(ke);break}case"error":{Fo=!0,Mt.enqueue(ke),fr="error";break}case"raw":{nr&&Mt.enqueue(ke);break}default:{const Et=Vo;throw new Error(`Unknown chunk type: ${Et}`)}}},async flush(ke){var Mt,Za,Ha,Ba,Ja,Ga,Vo;if(!Fo&&!p1){ke.enqueue({type:"error",error:new Ts({message:"No output generated. The model stream ended without a finish chunk."})}),Ft.end(),so(),$n(),Ie.closeStream();return}const Et=Mn.length>0?JSON.stringify(Mn):void 0;try{Ft.setAttributes(await vr({telemetry:t,attributes:{"ai.response.finishReason":fr,"ai.response.toolCalls":{output:()=>Et},"ai.response.id":Wr.id,"ai.response.model":Wr.modelId,"ai.response.timestamp":Wr.timestamp.toISOString(),"ai.usage.inputTokens":Gt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Mt=Gt.inputTokenDetails)==null?void 0:Mt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Za=Gt.inputTokenDetails)==null?void 0:Za.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ha=Gt.inputTokenDetails)==null?void 0:Ha.cacheWriteTokens,"ai.usage.outputTokens":Gt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Ba=Gt.outputTokenDetails)==null?void 0:Ba.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ja=Gt.outputTokenDetails)==null?void 0:Ja.reasoningTokens,"ai.usage.totalTokens":Gt.totalTokens,"ai.usage.reasoningTokens":(Ga=Gt.outputTokenDetails)==null?void 0:Ga.reasoningTokens,"ai.usage.cachedInputTokens":(Vo=Gt.inputTokenDetails)==null?void 0:Vo.cacheReadTokens,"gen_ai.response.finish_reasons":[fr],"gen_ai.response.id":Wr.id,"gen_ai.response.model":Wr.modelId,"gen_ai.usage.input_tokens":Gt.inputTokens,"gen_ai.usage.output_tokens":Gt.outputTokens}}))}catch{}ke.enqueue({type:"finish-step",finishReason:fr,rawFinishReason:Va,usage:Gt,providerMetadata:h1,response:{...Wr,headers:Jt?.headers}});const Zo=zm(ft,Gt);await Y.promise;const Ld=fe[fe.length-1];try{Ft.setAttributes(await vr({telemetry:t,attributes:{"ai.response.text":{output:()=>Ld.text},"ai.response.reasoning":{output:()=>Ld.reasoningText},"ai.response.providerMetadata":JSON.stringify(Ld.providerMetadata)}}))}catch{}finally{Ft.end()}const m1=Mn.filter(Vt=>Vt.providerExecuted!==!0),zR=On.filter(Vt=>Vt.providerExecuted!==!0);for(const Vt of Mn){if(Vt.providerExecuted!==!0)continue;const jd=f?.[Vt.toolName];jd?.type==="provider"&&jd.supportsDeferredResults&&(On.some(Dd=>(Dd.type==="tool-result"||Dd.type==="tool-error")&&Dd.toolCallId===Vt.toolCallId)||wt.set(Vt.toolCallId,{toolName:Vt.toolName}))}for(const Vt of On)(Vt.type==="tool-result"||Vt.type==="tool-error")&&wt.delete(Vt.toolCallId);if(so(),$n(),(m1.length>0&&zR.length===m1.length||wt.size>0)&&!await o2({stopConditions:g,steps:fe})){De.push(...await Ic({content:fe[fe.length-1].content,tools:f}));try{await ie({currentStep:Ve+1,responseMessages:De,usage:Zo})}catch(Vt){ke.enqueue({type:"error",error:Vt}),Ie.closeStream()}}else ke.enqueue({type:"finish",finishReason:fr,rawFinishReason:Va,totalUsage:Zo}),Ie.closeStream()}})))}finally{so(),$n()}}await ie({currentStep:0,responseMessages:hr,usage:wc()})}}).catch(nt=>{Ie.addStream(new ReadableStream({start(ht){ht.enqueue({type:"error",error:nt}),ht.close()}})),Ie.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ma(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ma(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}rejectResultPromises(e){this._finishReason.isPending()&&this._finishReason.reject(e),this._rawFinishReason.isPending()&&this._rawFinishReason.reject(e),this._totalUsage.isPending()&&this._totalUsage.reject(e),this._steps.isPending()&&this._steps.reject(e)}async consumeStream(e){var t;try{await sC({stream:this.fullStream,onError:r=>{var n;this.rejectResultPromises(r),(n=e?.onError)==null||n.call(e,r)}})}catch(r){this.rejectResultPromises(r),(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return ma(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Tr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return ma(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Es()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:a=!1,sendStart:i=!0,sendFinish:s=!0,onError:l=()=>"An error occurred."}={}){const c=t!=null?X5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var m;const f=(m=this.tools)==null?void 0:m[p.toolName];return f==null?p.dynamic:f?.type==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(p,m)=>{const f=n?.({part:p}),b=p.type;switch(b){case"text-start":{m.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{o&&m.enqueue({type:b,id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&m.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"source":{a&&p.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),a&&p.sourceType==="document"&&m.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const w=u(p);m.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const w=u(p);p.invalid?m.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):m.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{m.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId,...p.signature!=null?{signature:p.signature}:{}});break}case"tool-result":{const w=u(p);m.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output===void 0?null:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=u(p);m.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:p.providerExecuted?typeof p.error=="string"?p.error:JSON.stringify(p.error):l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{}});break}case"tool-output-denied":{m.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{m.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{i&&m.enqueue({type:"start",...f!=null?{messageMetadata:f}:{},...c!=null?{messageId:c}:{}});break}case"finish":{s&&m.enqueue({type:"finish",finishReason:p.finishReason,...f!=null?{messageMetadata:f}:{}});break}case"abort":{m.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const w=b;throw new Error(`Unknown chunk type: ${w}`)}}f!=null&&b!=="start"&&b!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:f})}}));return ma(oC({stream:h,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:i,sendFinish:s,sendStart:l,onError:c,...u}={}){aC({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:i,sendFinish:s,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){Y5({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:s,onError:l,...c}={}){return Q5({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:s,onError:l}),...c})}toTextStreamResponse(e){return K5({textStream:this.textStream,...e})}};pe(d(),Jn.optional()),na({prefix:"aiobj",size:24}),na({prefix:"aiobj",size:24});let $c;$c=globalThis.crypto;async function hC(e){return(await $c).getRandomValues(new Uint8Array(e))}async function fC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await hC(e-n.length);for(const a of o)a<r&&(n+=t[a%t.length])}return n}async function mC(e){return await fC(e)}async function gC(e){const t=await(await $c).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function m2(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await mC(e),r=await gC(t);return{code_verifier:t,code_challenge:r}}var _C="AI_MCPClientError",g2=`vercel.ai.error.${_C}`,yC=Symbol.for(g2),_2,y2,ze=class extends(y2=we,_2=yC,y2){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o,statusCode:a,url:i,responseBody:s}){super({name:e,message:t,cause:r}),this[_2]=!0,this.data=n,this.code=o,this.statusCode=a,this.url=i,this.responseBody=s}static isInstance(e){return we.hasMarker(e,g2)}},Co="2025-11-25",vC=[Co,"2025-06-18","2025-03-26","2024-11-05"],wC=ce(pe(d(),Te())),bC=dt({name:d(),version:d(),title:ce(d())}),ga=dt({_meta:ce(T({}).loose())}),Hr=ga,v2=T({method:d(),params:ce(ga)}),w2=T({applyDefaults:ce(_e())}).loose(),kC=dt({experimental:ce(T({}).loose()),logging:ce(T({}).loose()),completions:ce(T({}).loose()),prompts:ce(dt({listChanged:ce(_e())})),resources:ce(dt({subscribe:ce(_e()),listChanged:ce(_e())})),tools:ce(dt({listChanged:ce(_e())})),elicitation:ce(w2)});T({elicitation:ce(w2)}).loose();var TC=Hr.extend({protocolVersion:d(),capabilities:kC,serverInfo:bC,instructions:ce(d())}),Rc=Hr.extend({nextCursor:ce(d())}),CC=T({name:d(),title:ce(d()),description:ce(d()),inputSchema:T({type:M("object"),properties:ce(T({}).loose())}).loose(),outputSchema:ce(T({}).loose()),annotations:ce(T({title:ce(d())}).loose()),_meta:wC}).loose(),SC=Rc.extend({tools:L(CC)}),b2=T({type:M("text"),text:d()}).loose(),k2=T({type:M("image"),data:kh(),mimeType:d()}).loose(),IC=T({uri:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d()),size:ce(q())}).loose(),xC=Rc.extend({resources:L(IC)}),T2=T({uri:d(),name:ce(d()),title:ce(d()),mimeType:ce(d())}).loose(),C2=T2.extend({text:d()}),S2=T2.extend({blob:kh()}),I2=T({type:M("resource"),resource:ae([C2,S2])}).loose(),x2=T({type:M("resource_link"),uri:d(),name:d(),description:ce(d()),mimeType:ce(d())}).loose(),EC=Hr.extend({content:L(ae([b2,k2,I2,x2])),structuredContent:ce(Te()),isError:_e().default(!1).optional()}).or(Hr.extend({toolResult:Te()})),$C=T({uriTemplate:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d())}).loose(),RC=Hr.extend({resourceTemplates:L($C)}),PC=Hr.extend({contents:L(ae([C2,S2]))}),MC=T({type:M("ref/prompt"),name:d()}).loose(),OC=T({type:M("ref/resource"),uri:d()}).loose(),AC=T({name:d(),value:d()}).loose();ga.extend({ref:ae([MC,OC]),argument:AC,context:ce(T({arguments:pe(d(),d())}).loose())});var NC=Hr.extend({completion:T({values:L(d()).max(100),total:ce(q().int()),hasMore:ce(_e())}).loose()}),qC=T({name:d(),description:ce(d()),required:ce(_e())}).loose(),LC=T({name:d(),title:ce(d()),description:ce(d()),arguments:ce(L(qC))}).loose(),jC=Rc.extend({prompts:L(LC)}),DC=T({role:ae([M("user"),M("assistant")]),content:ae([b2,k2,I2,x2])}).loose(),UC=Hr.extend({description:ce(d()),messages:L(DC)}),zC=ga.extend({message:d(),requestedSchema:Te()}),E2=v2.extend({method:M("elicitation/create"),params:zC}),FC=Hr.extend({action:ae([M("accept"),M("decline"),M("cancel")]),content:ce(pe(d(),Te()))}),Rs="2.0",VC=T({jsonrpc:M(Rs),id:ae([d(),q().int()])}).merge(v2).strict(),ZC=T({jsonrpc:M(Rs),id:ae([d(),q().int()]),result:Hr}).strict(),HC=T({jsonrpc:M(Rs),id:ae([d(),q().int()]),error:T({code:q().int(),message:d(),data:ce(Te())})}).strict(),BC=T({jsonrpc:M(Rs)}).merge(T({method:d(),params:ce(ga)})).strict(),Pc=ae([VC,BC,ZC,HC]);async function Mc(e){return Pc.parse(await gs({text:e}))}var $2=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",$t=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Mh.custom,message:"URL must be parseable",fatal:!0}),Pp}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),R2=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:q().optional(),scope:d().optional(),refresh_token:d().optional(),authorization_server:$t.optional(),token_endpoint:$t.optional()}).strip(),JC=T({resource:d().url(),authorization_servers:L($t).optional(),jwks_uri:d().url().optional(),scopes_supported:L(d()).optional(),bearer_methods_supported:L(d()).optional(),resource_signing_alg_values_supported:L(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:_e().optional(),authorization_details_types_supported:L(d()).optional(),dpop_signing_alg_values_supported:L(d()).optional(),dpop_bound_access_tokens_required:_e().optional()}).passthrough(),P2=T({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,registration_endpoint:$t.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),grant_types_supported:L(d()).optional(),code_challenge_methods_supported:L(d()),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional()}).passthrough(),GC=T({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,userinfo_endpoint:$t.optional(),jwks_uri:$t,registration_endpoint:$t.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),grant_types_supported:L(d()).optional(),subject_types_supported:L(d()),id_token_signing_alg_values_supported:L(d()),claims_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional()}).passthrough(),WC=GC.merge(P2.pick({code_challenge_methods_supported:!0})),KC=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional(),authorization_server:$t.optional(),token_endpoint:$t.optional()}).strip(),YC=T({redirect_uris:L($t),token_endpoint_auth_method:d().optional(),grant_types:L(d()).optional(),response_types:L(d()).optional(),client_name:d().optional(),client_uri:$t.optional(),logo_uri:$t.optional(),scope:d().optional(),contacts:L(d()).optional(),tos_uri:$t.optional(),policy_uri:d().optional(),jwks_uri:$t.optional(),jwks:ut().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),QC=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),XC=YC.merge(KC),eS="AI_MCPClientOAuthError",M2=`vercel.ai.error.${eS}`,tS=Symbol.for(M2),O2,A2,Br=class extends(A2=we,O2=tS,A2){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[O2]=!0}static isInstance(e){return we.hasMarker(e,M2)}},So=class extends Br{};So.errorCode="server_error";var Ps=class extends Br{};Ps.errorCode="invalid_client";var Ms=class extends Br{};Ms.errorCode="invalid_grant";var Os=class extends Br{};Os.errorCode="unauthorized_client";var rS={[So.errorCode]:So,[Ps.errorCode]:Ps,[Ms.errorCode]:Ms,[Os.errorCode]:Os};function nS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Oc(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function oS({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(a)}var As=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Io(e){return new URL(e).href}function aS(e,t){return{authorizationServerUrl:Io(e),tokenEndpoint:Io(t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e))}}function N2(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function q2(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function L2(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:Io(e.authorization_server),tokenEndpoint:Io(e.token_endpoint)}}async function j2({provider:e,clientInformation:t,tokens:r}){var n;const o=L2(r);if(o)return o;const a=await((n=e.authorizationServerInformation)==null?void 0:n.call(e));return a?{authorizationServerUrl:Io(a.authorizationServerUrl),tokenEndpoint:Io(a.tokenEndpoint)}:L2(t)}async function sS({provider:e,clientInformation:t,authorizationServerInformation:r}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(r),!0):e.saveClientInformation?(await e.saveClientInformation(q2(t,r)),!0):!1}function iS(e,t){if(!t)return;const r=new URL(e).origin;if(t.origin!==r)throw new Br({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${r}`})}function D2({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new Br({message:"OAuth authorization server metadata does not match the metadata that issued the stored credentials"})}function Ns(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const a=/resource_metadata="([^"]*)"/,i=r.match(a);if(i)try{return new URL(i[1])}catch{return}}function lS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ac(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ac(e,void 0,r):void 0;throw n}}async function U2(e,t,r=fetch){return await Ac(e,{"MCP-Protocol-Version":t},r)}function cS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function uS(e,t,r,n){var o,a;const i=new URL(e),s=(o=n?.protocolVersion)!=null?o:Co;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=lS(t,i.pathname);l=new URL(u,(a=n?.metadataServerUrl)!=null?a:i),l.search=i.search}let c=await U2(l,s,r);if(!n?.metadataUrl&&cS(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await U2(u,s,r)}return c}async function dS(e,t,r=fetch){const n=await uS(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return JC.parse(await n.json())}function pS(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=t.origin,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth",expectedIssuer:n}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc",expectedIssuer:n}),o;let a=t.pathname;a.endsWith("/")&&(a=a.slice(0,-1));const i=`${t.origin}${a}`;return o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth",expectedIssuer:i}),o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth",expectedIssuer:n}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc",expectedIssuer:i}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc",expectedIssuer:i}),o}function z2(e,t){if(e.issuer!==t)throw new Br({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function hS(e,{fetchFn:t=fetch,protocolVersion:r=Co}={}){var n;const o={"MCP-Protocol-Version":r},a=pS(e);for(const{url:i,type:s,expectedIssuer:l}of a){const c=await Ac(i,o,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(s==="oauth"){const u=P2.parse(await c.json());return z2(u,l),u}else{const u=WC.parse(await c.json());if(z2(u,l),!((n=u.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function fS(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:i}){const s="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await m2(),h=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",s),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),a&&c.searchParams.set("state",a),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),i&&c.searchParams.set("resource",Oc(i)),{authorizationUrl:c,codeVerifier:h}}function F2(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function V2(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":mS(o,a,r);return;case"client_secret_post":gS(o,a,n);return;case"none":_S(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function mS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function gS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function _S(e,t){t.set("client_id",e)}async function Nc(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=QC.parse(await gs({text:r})),{error:o,error_description:a,error_uri:i}=n,s=rS[o]||So;return new s({message:a||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new So({message:o})}}async function yS(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:a,resource:i,addClientAuthentication:s,fetchFn:l}){var c;const u="authorization_code",h=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(a)});if(s)await s(p,m,e,t);else{const b=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],w=F2(r,b);V2(w,r,p,m)}i&&m.set("resource",Oc(i));const f=await(l??fetch)(h,{method:"POST",headers:p,body:m});if(!f.ok)throw await Nc(f);return R2.parse(await f.json())}async function vS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:i}){var s;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:l,refresh_token:n});if(a)await a(u,h,e,t);else{const m=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],f=F2(r,m);V2(f,r,u,h)}o&&h.set("resource",Oc(o));const p=await(i??fetch)(c,{method:"POST",headers:u,body:h});if(!p.ok)throw await Nc(p);return R2.parse({refresh_token:n,...await p.json()})}async function wS(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const a=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await Nc(a);return XC.parse(await a.json())}async function qc(e,t){var r,n;try{return await Lc(e,t)}catch(o){if(o instanceof Ps||o instanceof Os)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Lc(e,t);if(o instanceof Ms)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Lc(e,t);throw o}}async function bS(e,t,r){const n=nS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!oS({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Lc(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:a,fetchFn:i}){var s,l;let c,u;iS(t,a);try{c=await dS(t,{resourceMetadataUrl:a},i),c.authorization_servers&&c.authorization_servers.length>0&&(u=c.authorization_servers[0])}catch{}u||(u=t);const h=await bS(t,e,c);await((s=e.validateAuthorizationServerURL)==null?void 0:s.call(e,t,u));const p=await hS(u,{fetchFn:i}),m=aS(u,p);let f=await Promise.resolve(e.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const I=await wS(u,{metadata:p,clientMetadata:e.clientMetadata,fetchFn:i});f=q2(I,m),await e.saveClientInformation(f)}if(r!==void 0){if(e.storedState){const k=await e.storedState();if(k!==void 0&&k!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const I=await j2({provider:e,clientInformation:f});if(!I)throw new Br({message:"Stored OAuth authorization server metadata is required when exchanging an authorization code"});D2({storedAuthorizationServerInformation:I,currentAuthorizationServerInformation:m});const y=await e.codeVerifier(),_=await yS(u,{metadata:p,clientInformation:f,authorizationCode:r,codeVerifier:y,redirectUri:e.redirectUrl,resource:h,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(N2(_,m)),"AUTHORIZED"}const b=await e.tokens();if(b?.refresh_token){const I=await j2({provider:e,clientInformation:f,tokens:b});I?D2({storedAuthorizationServerInformation:I,currentAuthorizationServerInformation:m}):await((l=e.invalidateCredentials)==null?void 0:l.call(e,"tokens"));try{if(I){const y=await vS(u,{metadata:p,clientInformation:f,refreshToken:b.refresh_token,resource:h,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(N2(y,m)),"AUTHORIZED"}}catch(y){if(!(!(y instanceof Br)||y instanceof So))throw y}}const w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);const{authorizationUrl:C,codeVerifier:v}=await fS(u,{metadata:p,clientInformation:f,state:w,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:h});if(!await sS({provider:e,clientInformation:f,authorizationServerInformation:m}))throw new Br({message:"OAuth authorization server metadata must be saveable before starting authorization"});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(C),"REDIRECT"}function kS(e){return e===void 0||e==="message"}var TS=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow",fetch:o}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n,this.fetchFn=o??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){var t;const r={...this.headers,...e,"mcp-protocol-version":(t=this.protocolVersion)!=null?t:Co};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return _n(r,`ai-sdk/${$2}`,oa())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,a,i,s,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await this.fetchFn(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ns(u);try{if(await qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const b=new As;return(a=this.onerror)==null||a.call(this,b),t(b)}}catch(f){return(i=this.onerror)==null||i.call(this,f),t(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const b=new ze({message:f});return(s=this.onerror)==null||s.call(this,b),t(b)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),m=async()=>{var f,b,w,C,v;try{for(;;){const{done:g,value:I}=await p.read();if(g){if(this.connected)throw this.connected=!1,new ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:y,data:_}=I;if(y==="endpoint"){if(this.endpoint)continue;const k=new URL(_,this.url);if(k.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(f=this.sseConnection)==null||f.close(),(b=this.abortController)==null||b.abort(),new ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${k.origin}`});this.endpoint=k,this.connected=!0,e()}else if(kS(y))try{const k=await Mc(_);(w=this.onmessage)==null||w.call(this,k)}catch(k){const S=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(C=this.onerror)==null||C.call(this,S)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(v=this.onerror)==null||v.call(this,g),t(g)}};this.sseConnection={close:()=>p.cancel()},m()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,a,i,s,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode},h=await this.fetchFn(t.href,u);if(h.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ns(h);try{if(await qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const m=new As;(a=this.onerror)==null||a.call(this,m);return}}catch(p){(i=this.onerror)==null||i.call(this,p);return}return r(!0)}if(!h.ok){const p=await h.text().catch(()=>null),m=new ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${h.status}): ${p}`});(s=this.onerror)==null||s.call(this,m);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}};function Z2(e){return e===void 0||e==="message"}var CS=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow",fetch:o}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n,this.fetchFn=o??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){var t;const r={...this.headers,...e,"mcp-protocol-version":(t=this.protocolVersion)!=null?t:Co};if(this.sessionId&&(r["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return _n(r,`ai-sdk/${$2}`,oa())}authorizeOnce(e){return this.authProvider?(this.authPromise||(this.authPromise=qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0})),this.authPromise):Promise.resolve("REDIRECT")}async start(){if(this.abortController)throw new ze({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:"DELETE",headers:n,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,a,i,s,l,c;try{const h={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal,redirect:this.redirectMode},p=await this.fetchFn(this.url.href,h),m=p.headers.get("mcp-session-id");if(m&&(this.sessionId=m),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Ns(p);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED")throw new As}catch(C){throw(o=this.onerror)==null||o.call(this,C),C}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const C=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${C}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new ze({message:v,statusCode:p.status,url:this.url.href,responseBody:C??void 0});throw(a=this.onerror)==null||a.call(this,g),g}if(!("id"in e))return;const b=p.headers.get("content-type")||"";if(b.includes("application/json")){const C=await p.json(),v=Array.isArray(C)?C.map(g=>Pc.parse(g)):[Pc.parse(C)];for(const g of v)(i=this.onmessage)==null||i.call(this,g);return}if(b.includes("text/event-stream")){if(!p.body){const I=new ze({message:"MCP HTTP Transport Error: text/event-stream response without body",statusCode:p.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,I),I}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader();(async()=>{var I,y,_;try{for(;;){const{done:k,value:S}=await v.read();if(k)return;const{event:E,data:R}=S;if(Z2(E))try{const x=await Mc(R);(I=this.onmessage)==null||I.call(this,x)}catch(x){const N=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:x});(y=this.onerror)==null||y.call(this,N)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(_=this.onerror)==null||_.call(this,k)}})();return}const w=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${b}`,statusCode:p.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,w),w}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new ze({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,a,i,s;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await this.fetchFn(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal,redirect:this.redirectMode}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Ns(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED"){const b=new As;(n=this.onerror)==null||n.call(this,b);return}}catch(f){(o=this.onerror)==null||o.call(this,f);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const f=new ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(a=this.onerror)==null||a.call(this,f);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),m=async()=>{var f,b,w,C;try{for(;;){const{done:v,value:g}=await p.read();if(v)return;const{event:I,data:y,id:_}=g;if(_&&(this.lastInboundEventId=_),Z2(I))try{const k=await Mc(y);(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:k});(b=this.onerror)==null||b.call(this,S)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(w=this.onerror)==null||w.call(this,v),(C=this.abortController)!=null&&C.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,m()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function SS(e){switch(e.type){case"sse":return new TS(e);case"http":return new CS(e);default:throw new ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function IS(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var xS="1.0.0";function H2({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function ES(e){const t=new $S(e);return await t.init(),t}var $S=class{constructor({transport:e,name:t,clientName:r=t??"ai-sdk-mcp-client",version:n=xS,onUncaughtError:o,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:"",version:""},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=a??{},IS(e)?this.transport=e:this.transport=SS(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new ze({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:r,version:n}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Co,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:TC});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!vC.includes(e.protocolVersion))throw new ze({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"completion/complete":if(!this.serverCapabilities.completions)throw new ze({message:"Server does not support completions"});break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ze({message:"Server does not support prompts"});break;default:throw new ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=r?.signal;a?.throwIfAborted();const i=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,c=>{if(a?.aborted)return o(new ze({message:"Request was aborted",cause:a.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const h=new ze({message:"Failed to parse server response",cause:u});o(h)}}),this.transport.send(s).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:SC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:EC,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:xC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:PC,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:RC,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:jC,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:UC,options:r})}catch(n){throw n}}async completeInternal({options:e,...t}){return this.request({request:{method:"completion/complete",params:t},resultSchema:NC,options:e})}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:a,title:i,description:s,inputSchema:l,annotations:c,_meta:u}of e.tools){const h=i??c?.title;if(t!=="automatic"&&!Object.prototype.hasOwnProperty.call(t,a))continue;const p=this,m=t!=="automatic"?(r=t[a])==null?void 0:r.outputSchema:void 0,f=async(w,C)=>{var v;(v=C?.abortSignal)==null||v.throwIfAborted();const g=await p.callTool({name:a,args:w,options:C});return g.isError?g:m!=null?p.extractStructuredContent(g,m,a):g},b=t==="automatic"?Zl({description:s,title:h,metadata:{clientName:this.clientInfo.name},inputSchema:Vn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:f,toModelOutput:H2}):{description:s,title:h,metadata:{clientName:this.clientInfo.name},inputSchema:t[a].inputSchema,...m!=null?{outputSchema:m}:{},execute:f,toModelOutput:H2};o[a]={...b,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await ar({value:e.structuredContent,schema:yn(t)});if(!n.success)throw new ze({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await gr({text:n.text,schema:t});if(!o.success)throw new ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new ze({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==E2)throw new ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method==="ping"){await this.transport.send({jsonrpc:"2.0",id:e.id,result:{}});return}if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=E2.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=FC.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ze({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function qs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function B2(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...qs(t.headers),...qs(n.headers)}:t.headers};return e(r,o)}:e}const Ls="2025-11-25",RS=[Ls,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gn="io.modelcontextprotocol/related-task",js="2.0",Nt=Rh(e=>e!==null&&(typeof e=="object"||typeof e=="function")),J2=ae([d(),q().int()]),G2=d();dt({ttl:ae([q(),Qo()]).optional(),pollInterval:q().optional()});const PS=T({ttl:q().optional()}),MS=T({taskId:d()}),jc=dt({progressToken:J2.optional(),[Gn]:MS.optional()}),cr=T({_meta:jc.optional()}),_a=cr.extend({task:PS.optional()}),OS=e=>_a.safeParse(e).success,qt=T({method:d(),params:cr.loose().optional()}),wr=T({_meta:jc.optional()}),br=T({method:d(),params:wr.loose().optional()}),Lt=dt({_meta:jc.optional()}),Ds=ae([d(),q().int()]),W2=T({jsonrpc:M(js),id:Ds,...qt.shape}).strict(),Dc=e=>W2.safeParse(e).success,K2=T({jsonrpc:M(js),...br.shape}).strict(),AS=e=>K2.safeParse(e).success,Uc=T({jsonrpc:M(js),id:Ds,result:Lt}).strict(),ya=e=>Uc.safeParse(e).success;var $e;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})($e||($e={}));const zc=T({jsonrpc:M(js),id:Ds.optional(),error:T({code:q().int(),message:d(),data:Te().optional()})}).strict(),NS=e=>zc.safeParse(e).success,Wn=ae([W2,K2,Uc,zc]);ae([Uc,zc]);const Kn=Lt.strict(),qS=wr.extend({requestId:Ds.optional(),reason:d().optional()}),Fc=br.extend({method:M("notifications/cancelled"),params:qS}),LS=T({src:d(),mimeType:d().optional(),sizes:L(d()).optional(),theme:le(["light","dark"]).optional()}),va=T({icons:L(LS).optional()}),xo=T({name:d(),title:d().optional()}),Y2=xo.extend({...xo.shape,...va.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),jS=vl(T({applyDefaults:_e().optional()}),pe(d(),Te())),DS=Ph(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,vl(T({form:jS.optional(),url:Nt.optional()}),pe(d(),Te()).optional())),US=dt({list:Nt.optional(),cancel:Nt.optional(),requests:dt({sampling:dt({createMessage:Nt.optional()}).optional(),elicitation:dt({create:Nt.optional()}).optional()}).optional()}),zS=dt({list:Nt.optional(),cancel:Nt.optional(),requests:dt({tools:dt({call:Nt.optional()}).optional()}).optional()}),FS=T({experimental:pe(d(),Nt).optional(),sampling:T({context:Nt.optional(),tools:Nt.optional()}).optional(),elicitation:DS.optional(),roots:T({listChanged:_e().optional()}).optional(),tasks:US.optional()}),VS=cr.extend({protocolVersion:d(),capabilities:FS,clientInfo:Y2}),ZS=qt.extend({method:M("initialize"),params:VS}),HS=T({experimental:pe(d(),Nt).optional(),logging:Nt.optional(),completions:Nt.optional(),prompts:T({listChanged:_e().optional()}).optional(),resources:T({subscribe:_e().optional(),listChanged:_e().optional()}).optional(),tools:T({listChanged:_e().optional()}).optional(),tasks:zS.optional()}),Q2=Lt.extend({protocolVersion:d(),capabilities:HS,serverInfo:Y2,instructions:d().optional()}),X2=br.extend({method:M("notifications/initialized"),params:wr.optional()}),BS=e=>X2.safeParse(e).success,Vc=qt.extend({method:M("ping"),params:cr.optional()}),JS=T({progress:q(),total:ce(q()),message:ce(d())}),GS=T({...wr.shape,...JS.shape,progressToken:J2}),Zc=br.extend({method:M("notifications/progress"),params:GS}),WS=cr.extend({cursor:G2.optional()}),wa=qt.extend({params:WS.optional()}),ba=Lt.extend({nextCursor:G2.optional()}),KS=le(["working","input_required","completed","failed","cancelled"]),ka=T({taskId:d(),status:KS,ttl:ae([q(),Qo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ce(q()),statusMessage:ce(d())}),Ta=Lt.extend({task:ka}),YS=wr.merge(ka),Us=br.extend({method:M("notifications/tasks/status"),params:YS}),Hc=qt.extend({method:M("tasks/get"),params:cr.extend({taskId:d()})}),Bc=Lt.merge(ka),Jc=qt.extend({method:M("tasks/result"),params:cr.extend({taskId:d()})});Lt.loose();const Gc=wa.extend({method:M("tasks/list")}),Wc=ba.extend({tasks:L(ka)}),Kc=qt.extend({method:M("tasks/cancel"),params:cr.extend({taskId:d()})}),QS=Lt.merge(ka),eg=T({uri:d(),mimeType:ce(d()),_meta:pe(d(),Te()).optional()}),tg=eg.extend({text:d()}),Yc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),rg=eg.extend({blob:Yc}),Ca=le(["user","assistant"]),Eo=T({audience:L(Ca).optional(),priority:q().min(0).max(1).optional(),lastModified:gh({offset:!0}).optional()}),ng=T({...xo.shape,...va.shape,uri:d(),description:ce(d()),mimeType:ce(d()),annotations:Eo.optional(),_meta:ce(dt({}))}),XS=T({...xo.shape,...va.shape,uriTemplate:d(),description:ce(d()),mimeType:ce(d()),annotations:Eo.optional(),_meta:ce(dt({}))}),eI=wa.extend({method:M("resources/list")}),og=ba.extend({resources:L(ng)}),tI=wa.extend({method:M("resources/templates/list")}),ag=ba.extend({resourceTemplates:L(XS)}),Qc=cr.extend({uri:d()}),rI=Qc,nI=qt.extend({method:M("resources/read"),params:rI}),sg=Lt.extend({contents:L(ae([tg,rg]))}),Xc=br.extend({method:M("notifications/resources/list_changed"),params:wr.optional()}),oI=Qc,aI=qt.extend({method:M("resources/subscribe"),params:oI}),sI=Qc,iI=qt.extend({method:M("resources/unsubscribe"),params:sI}),lI=wr.extend({uri:d()}),ig=br.extend({method:M("notifications/resources/updated"),params:lI}),cI=T({name:d(),description:ce(d()),required:ce(_e())}),uI=T({...xo.shape,...va.shape,description:ce(d()),arguments:ce(L(cI)),_meta:ce(dt({}))}),dI=wa.extend({method:M("prompts/list")}),lg=ba.extend({prompts:L(uI)}),pI=cr.extend({name:d(),arguments:pe(d(),d()).optional()}),hI=qt.extend({method:M("prompts/get"),params:pI}),eu=T({type:M("text"),text:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),tu=T({type:M("image"),data:Yc,mimeType:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),ru=T({type:M("audio"),data:Yc,mimeType:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),fI=T({type:M("tool_use"),name:d(),id:d(),input:pe(d(),Te()),_meta:pe(d(),Te()).optional()}),mI=T({type:M("resource"),resource:ae([tg,rg]),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),gI=ng.extend({type:M("resource_link")}),nu=ae([eu,tu,ru,gI,mI]),_I=T({role:Ca,content:nu}),cg=Lt.extend({description:d().optional(),messages:L(_I)}),ou=br.extend({method:M("notifications/prompts/list_changed"),params:wr.optional()}),yI=T({title:d().optional(),readOnlyHint:_e().optional(),destructiveHint:_e().optional(),idempotentHint:_e().optional(),openWorldHint:_e().optional()}),vI=T({taskSupport:le(["required","optional","forbidden"]).optional()}),ug=T({...xo.shape,...va.shape,description:d().optional(),inputSchema:T({type:M("object"),properties:pe(d(),Nt).optional(),required:L(d()).optional()}).catchall(Te()),outputSchema:T({type:M("object"),properties:pe(d(),Nt).optional(),required:L(d()).optional()}).catchall(Te()).optional(),annotations:yI.optional(),execution:vI.optional(),_meta:pe(d(),Te()).optional()}),wI=wa.extend({method:M("tools/list")}),dg=ba.extend({tools:L(ug)}),Sa=Lt.extend({content:L(nu).default([]),structuredContent:pe(d(),Te()).optional(),isError:_e().optional()});Sa.or(Lt.extend({toolResult:Te()}));const bI=_a.extend({name:d(),arguments:pe(d(),Te()).optional()}),kI=qt.extend({method:M("tools/call"),params:bI}),au=br.extend({method:M("notifications/tools/list_changed"),params:wr.optional()}),TI=T({autoRefresh:_e().default(!0),debounceMs:q().int().nonnegative().default(300)}),pg=le(["debug","info","notice","warning","error","critical","alert","emergency"]),CI=cr.extend({level:pg}),SI=qt.extend({method:M("logging/setLevel"),params:CI}),II=wr.extend({level:pg,logger:d().optional(),data:Te()}),hg=br.extend({method:M("notifications/message"),params:II}),xI=T({name:d().optional()}),EI=T({hints:L(xI).optional(),costPriority:q().min(0).max(1).optional(),speedPriority:q().min(0).max(1).optional(),intelligencePriority:q().min(0).max(1).optional()}),$I=T({mode:le(["auto","required","none"]).optional()}),RI=T({type:M("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:L(nu).default([]),structuredContent:T({}).loose().optional(),isError:_e().optional(),_meta:pe(d(),Te()).optional()}),PI=Le("type",[eu,tu,ru]),zs=Le("type",[eu,tu,ru,fI,RI]),MI=T({role:Ca,content:ae([zs,L(zs)]),_meta:pe(d(),Te()).optional()}),OI=_a.extend({messages:L(MI),modelPreferences:EI.optional(),systemPrompt:d().optional(),includeContext:le(["none","thisServer","allServers"]).optional(),temperature:q().optional(),maxTokens:q().int(),stopSequences:L(d()).optional(),metadata:Nt.optional(),tools:L(ug).optional(),toolChoice:$I.optional()}),su=qt.extend({method:M("sampling/createMessage"),params:OI}),iu=Lt.extend({model:d(),stopReason:ce(le(["endTurn","stopSequence","maxTokens"]).or(d())),role:Ca,content:PI}),fg=Lt.extend({model:d(),stopReason:ce(le(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Ca,content:ae([zs,L(zs)])}),AI=T({type:M("boolean"),title:d().optional(),description:d().optional(),default:_e().optional()}),NI=T({type:M("string"),title:d().optional(),description:d().optional(),minLength:q().optional(),maxLength:q().optional(),format:le(["email","uri","date","date-time"]).optional(),default:d().optional()}),qI=T({type:le(["number","integer"]),title:d().optional(),description:d().optional(),minimum:q().optional(),maximum:q().optional(),default:q().optional()}),LI=T({type:M("string"),title:d().optional(),description:d().optional(),enum:L(d()),default:d().optional()}),jI=T({type:M("string"),title:d().optional(),description:d().optional(),oneOf:L(T({const:d(),title:d()})),default:d().optional()}),DI=T({type:M("string"),title:d().optional(),description:d().optional(),enum:L(d()),enumNames:L(d()).optional(),default:d().optional()}),UI=ae([LI,jI]),zI=T({type:M("array"),title:d().optional(),description:d().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({type:M("string"),enum:L(d())}),default:L(d()).optional()}),FI=T({type:M("array"),title:d().optional(),description:d().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({anyOf:L(T({const:d(),title:d()}))}),default:L(d()).optional()}),VI=ae([zI,FI]),ZI=ae([DI,UI,VI]),HI=ae([ZI,AI,NI,qI]),BI=_a.extend({mode:M("form").optional(),message:d(),requestedSchema:T({type:M("object"),properties:pe(d(),HI),required:L(d()).optional()})}),JI=_a.extend({mode:M("url"),message:d(),elicitationId:d(),url:d().url()}),GI=ae([BI,JI]),lu=qt.extend({method:M("elicitation/create"),params:GI}),WI=wr.extend({elicitationId:d()}),KI=br.extend({method:M("notifications/elicitation/complete"),params:WI}),cu=Lt.extend({action:le(["accept","decline","cancel"]),content:Ph(e=>e===null?void 0:e,pe(d(),ae([d(),q(),_e(),L(d())])).optional())}),YI=T({type:M("ref/resource"),uri:d()}),QI=T({type:M("ref/prompt"),name:d()}),XI=cr.extend({ref:ae([QI,YI]),argument:T({name:d(),value:d()}),context:T({arguments:pe(d(),d()).optional()}).optional()}),e8=qt.extend({method:M("completion/complete"),params:XI}),mg=Lt.extend({completion:dt({values:L(d()).max(100),total:ce(q().int()),hasMore:ce(_e())})}),t8=T({uri:d().startsWith("file://"),name:d().optional(),_meta:pe(d(),Te()).optional()}),gg=qt.extend({method:M("roots/list"),params:cr.optional()}),_g=Lt.extend({roots:L(t8)}),r8=br.extend({method:M("notifications/roots/list_changed"),params:wr.optional()});ae([Vc,ZS,e8,SI,hI,dI,eI,tI,nI,aI,iI,kI,wI,Hc,Jc,Gc,Kc]),ae([Fc,Zc,X2,r8,Us]),ae([Kn,iu,fg,cu,_g,Bc,Wc,Ta]),ae([Vc,su,lu,gg,Hc,Jc,Gc,Kc]),ae([Fc,Zc,hg,ig,Xc,au,ou,Us,KI]),ae([Kn,Q2,mg,cg,lg,og,ag,sg,Sa,dg,Bc,Wc,Ta]);class Ce extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===$e.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new n8(o.elicitations,r)}return new Ce(t,r,n)}}class n8 extends Ce{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super($e.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const jt=D3().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Mh.custom,message:"URL must be parseable",fatal:!0}),Pp}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),o8=dt({resource:d().url(),authorization_servers:L(jt).optional(),jwks_uri:d().url().optional(),scopes_supported:L(d()).optional(),bearer_methods_supported:L(d()).optional(),resource_signing_alg_values_supported:L(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:_e().optional(),authorization_details_types_supported:L(d()).optional(),dpop_signing_alg_values_supported:L(d()).optional(),dpop_bound_access_tokens_required:_e().optional()}),yg=dt({issuer:d(),authorization_endpoint:jt,token_endpoint:jt,registration_endpoint:jt.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),response_modes_supported:L(d()).optional(),grant_types_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional(),service_documentation:jt.optional(),revocation_endpoint:jt.optional(),revocation_endpoint_auth_methods_supported:L(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:L(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:L(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:L(d()).optional(),code_challenge_methods_supported:L(d()).optional(),client_id_metadata_document_supported:_e().optional()}),a8=dt({issuer:d(),authorization_endpoint:jt,token_endpoint:jt,userinfo_endpoint:jt.optional(),jwks_uri:jt,registration_endpoint:jt.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),response_modes_supported:L(d()).optional(),grant_types_supported:L(d()).optional(),acr_values_supported:L(d()).optional(),subject_types_supported:L(d()),id_token_signing_alg_values_supported:L(d()),id_token_encryption_alg_values_supported:L(d()).optional(),id_token_encryption_enc_values_supported:L(d()).optional(),userinfo_signing_alg_values_supported:L(d()).optional(),userinfo_encryption_alg_values_supported:L(d()).optional(),userinfo_encryption_enc_values_supported:L(d()).optional(),request_object_signing_alg_values_supported:L(d()).optional(),request_object_encryption_alg_values_supported:L(d()).optional(),request_object_encryption_enc_values_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional(),display_values_supported:L(d()).optional(),claim_types_supported:L(d()).optional(),claims_supported:L(d()).optional(),service_documentation:d().optional(),claims_locales_supported:L(d()).optional(),ui_locales_supported:L(d()).optional(),claims_parameter_supported:_e().optional(),request_parameter_supported:_e().optional(),request_uri_parameter_supported:_e().optional(),require_request_uri_registration:_e().optional(),op_policy_uri:jt.optional(),op_tos_uri:jt.optional(),client_id_metadata_document_supported:_e().optional()}),s8=T({...a8.shape,...yg.pick({code_challenge_methods_supported:!0}).shape}),i8=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Oh().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),l8=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),vg=jt.optional().or(M("").transform(()=>{})),c8=T({redirect_uris:L(jt),token_endpoint_auth_method:d().optional(),grant_types:L(d()).optional(),response_types:L(d()).optional(),client_name:d().optional(),client_uri:jt.optional(),logo_uri:vg,scope:d().optional(),contacts:L(d()).optional(),tos_uri:vg,policy_uri:d().optional(),jwks_uri:jt.optional(),jwks:ut().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),u8=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),d8=c8.merge(u8);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function p8(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function h8({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(a)}class Rt extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class uu extends Rt{}uu.errorCode="invalid_request";class Fs extends Rt{}Fs.errorCode="invalid_client";class Vs extends Rt{}Vs.errorCode="invalid_grant";class Zs extends Rt{}Zs.errorCode="unauthorized_client";class du extends Rt{}du.errorCode="unsupported_grant_type";class pu extends Rt{}pu.errorCode="invalid_scope";class hu extends Rt{}hu.errorCode="access_denied";class $o extends Rt{}$o.errorCode="server_error";class fu extends Rt{}fu.errorCode="temporarily_unavailable";class mu extends Rt{}mu.errorCode="unsupported_response_type";class gu extends Rt{}gu.errorCode="unsupported_token_type";class _u extends Rt{}_u.errorCode="invalid_token";class yu extends Rt{}yu.errorCode="method_not_allowed";class vu extends Rt{}vu.errorCode="too_many_requests";class Hs extends Rt{}Hs.errorCode="invalid_client_metadata";class wu extends Rt{}wu.errorCode="insufficient_scope";class bu extends Rt{}bu.errorCode="invalid_target";const f8={[uu.errorCode]:uu,[Fs.errorCode]:Fs,[Vs.errorCode]:Vs,[Zs.errorCode]:Zs,[du.errorCode]:du,[pu.errorCode]:pu,[hu.errorCode]:hu,[$o.errorCode]:$o,[fu.errorCode]:fu,[mu.errorCode]:mu,[gu.errorCode]:gu,[_u.errorCode]:_u,[yu.errorCode]:yu,[vu.errorCode]:vu,[Hs.errorCode]:Hs,[wu.errorCode]:wu,[bu.errorCode]:bu};class kr extends Error{constructor(t){super(t??"Unauthorized")}}function m8(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ku="code",Tu="S256";function g8(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&m8(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function _8(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":y8(o,a,r);return;case"client_secret_post":v8(o,a,n);return;case"none":w8(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function y8(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function v8(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function w8(e,t){t.set("client_id",e)}async function wg(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=l8.parse(JSON.parse(r)),{error:o,error_description:a,error_uri:i}=n,s=f8[o]||$o;return new s(a||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new $o(o)}}async function Yn(e,t){try{return await Cu(e,t)}catch(r){if(r instanceof Fs||r instanceof Zs)return await e.invalidateCredentials?.("all"),await Cu(e,t);if(r instanceof Vs)return await e.invalidateCredentials?.("tokens"),await Cu(e,t);throw r}}async function Cu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:a}){let i,s;try{i=await T8(t,{resourceMetadataUrl:o},a),i.authorization_servers&&i.authorization_servers.length>0&&(s=i.authorization_servers[0])}catch{}s||(s=new URL("/",t));const l=await k8(t,e,i),c=await E8(s,{fetchFn:a});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const w=c?.client_id_metadata_document_supported===!0,C=e.clientMetadataUrl;if(C&&!b8(C))throw new Hs(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${C}`);if(w&&C)u={client_id:C},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const g=await O8(s,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(g),u=g}}const h=!e.redirectUrl;if(r!==void 0||h){const w=await M8(e,s,{metadata:c,resource:l,authorizationCode:r,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const w=await P8(s,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Rt)||w instanceof $o))throw w}const m=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:b}=await $8(s,{metadata:c,clientInformation:u,state:m,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(f),"REDIRECT"}function b8(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function k8(e,t,r){const n=p8(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!h8({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Bs(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Su(e,"resource_metadata")||void 0;let a;if(o)try{a=new URL(o)}catch{}const i=Su(e,"scope")||void 0,s=Su(e,"error")||void 0;return{resourceMetadataUrl:a,scope:i,error:s}}function Su(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function T8(e,t,r=fetch){const n=await I8(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return o8.parse(await n.json())}async function Iu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Iu(e,void 0,r):void 0;throw n}}function C8(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function bg(e,t,r=fetch){return await Iu(e,{"MCP-Protocol-Version":t},r)}function S8(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function I8(e,t,r,n){const o=new URL(e),a=n?.protocolVersion??Ls;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=C8(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let s=await bg(i,a,r);if(!n?.metadataUrl&&S8(s,o.pathname)){const l=new URL(`/.well-known/${t}`,o);s=await bg(l,a,r)}return s}function x8(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function E8(e,{fetchFn:t=fetch,protocolVersion:r=Ls}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=x8(e);for(const{url:a,type:i}of o){const s=await Iu(a,n,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?yg.parse(await s.json()):s8.parse(await s.json())}}}async function $8(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:i}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ku))throw new Error(`Incompatible auth server: does not support response type ${ku}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Tu))throw new Error(`Incompatible auth server: does not support code challenge method ${Tu}`)}else s=new URL("/authorize",e);const l=await m2(),c=l.code_verifier,u=l.code_challenge;return s.searchParams.set("response_type",ku),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",u),s.searchParams.set("code_challenge_method",Tu),s.searchParams.set("redirect_uri",String(n)),a&&s.searchParams.set("state",a),o&&s.searchParams.set("scope",o),o?.includes("offline_access")&&s.searchParams.append("prompt","consent"),i&&s.searchParams.set("resource",i.href),{authorizationUrl:s,codeVerifier:c}}function R8(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function kg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:a,fetchFn:i}){const s=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),o)await o(l,r,s,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],h=g8(n,u);_8(h,n,l,r)}const c=await(i??fetch)(s,{method:"POST",headers:l,body:r});if(!c.ok)throw await wg(c);return i8.parse(await c.json())}async function P8(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:i}){const s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await kg(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:a,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function M8(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:a}={}){const i=e.clientMetadata.scope;let s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(i)),!s){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();s=R8(o,c,e.redirectUrl)}const l=await e.clientInformation();return kg(t,{metadata:r,tokenRequestParams:s,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:a})}async function O8(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const a=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await wg(a);return d8.parse(await a.json())}const A8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ro extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Js{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=B2(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??A8}async _authThenStart(){if(!this._authProvider)throw new kr("No auth provider");let t;try{t=await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new kr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=qs(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Ro(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:a}=r;let i,s=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new _o({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:f}=await u.read();if(f)break;if(m.id&&(i=m.id,s=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const b=Wn.parse(JSON.parse(m.data));ya(b)&&(l=!0,a!==void 0&&(b.id=a)),this.onmessage?.(b)}catch(b){this.onerror?.(b)}}(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:a},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:a},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new kr("No auth provider");if(await Yn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Dc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(t),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,i),l=s.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!s.ok){const p=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ro(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:f}=Bs(s);if(this._resourceMetadataUrl=m,this._scope=f,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(s.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:f,error:b}=Bs(s);if(b==="insufficient_scope"){const w=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Ro(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=w??void 0,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new kr;return this.send(t)}}throw new Ro(s.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),BS(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,h=s.headers.get("content-type");if(u)if(h?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:o},!1);else if(h?.includes("application/json")){const p=await s.json(),m=Array.isArray(p)?p.map(f=>Wn.parse(f)):[Wn.parse(p)];for(const f of m)this.onmessage?.(f)}else throw await s.body?.cancel(),new Ro(-1,`Unexpected content type: ${h}`);else await s.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ro(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class Tg extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(Cg(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Cg(this),r)}}function N8(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function xu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(xu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${xu(e.cause)}`:e.message:`${e}`}function Cg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Sg=e=>{throw TypeError(e)},Eu=(e,t,r)=>t.has(e)||Sg("Cannot "+r),qe=(e,t,r)=>(Eu(e,t,"read from private field"),r?r.call(e):t.get(e)),xt=(e,t,r)=>t.has(e)?Sg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),at=(e,t,r,n)=>(Eu(e,t,"write to private field"),t.set(e,r),r),en=(e,t,r)=>(Eu(e,t,"access private method"),r),er,Qn,Po,Gs,Ws,Ia,Mo,xa,wn,Oo,Ao,No,Ea,$r,$u,Ru,Pu,Ig,Mu,Ou,$a,Au,Nu;class Ks extends EventTarget{constructor(t,r){var n,o;super(),xt(this,$r),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,xt(this,er),xt(this,Qn),xt(this,Po),xt(this,Gs),xt(this,Ws),xt(this,Ia),xt(this,Mo),xt(this,xa,null),xt(this,wn),xt(this,Oo),xt(this,Ao,null),xt(this,No,null),xt(this,Ea,null),xt(this,Ru,async a=>{var i;qe(this,Oo).reset();const{body:s,redirected:l,status:c,headers:u}=a;if(c===204){en(this,$r,$a).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?at(this,Po,new URL(a.url)):at(this,Po,void 0),c!==200){en(this,$r,$a).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){en(this,$r,$a).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,er)===this.CLOSED)return;at(this,er,this.OPEN);const h=new Event("open");if((i=qe(this,Ea))==null||i.call(this,h),this.dispatchEvent(h),typeof s!="object"||!s||!("getReader"in s)){en(this,$r,$a).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,m=s.getReader();let f=!0;do{const{done:b,value:w}=await m.read();w&&qe(this,Oo).feed(p.decode(w,{stream:!b})),b&&(f=!1,qe(this,Oo).reset(),en(this,$r,Au).call(this))}while(f)}),xt(this,Pu,a=>{at(this,wn,void 0),!(a.name==="AbortError"||a.type==="aborted")&&en(this,$r,Au).call(this,xu(a))}),xt(this,Mu,a=>{typeof a.id=="string"&&at(this,xa,a.id);const i=new MessageEvent(a.event||"message",{data:a.data,origin:qe(this,Po)?qe(this,Po).origin:qe(this,Qn).origin,lastEventId:a.id||""});qe(this,No)&&(!a.event||a.event==="message")&&qe(this,No).call(this,i),this.dispatchEvent(i)}),xt(this,Ou,a=>{at(this,Ia,a)}),xt(this,Nu,()=>{at(this,Mo,void 0),qe(this,er)===this.CONNECTING&&en(this,$r,$u).call(this)});try{if(t instanceof URL)at(this,Qn,t);else if(typeof t=="string")at(this,Qn,new URL(t,q8()));else throw new Error("Invalid URL")}catch{throw N8("An invalid or illegal string was specified")}at(this,Oo,Qh({onEvent:qe(this,Mu),onRetry:qe(this,Ou)})),at(this,er,this.CONNECTING),at(this,Ia,3e3),at(this,Ws,(n=r?.fetch)!=null?n:globalThis.fetch),at(this,Gs,(o=r?.withCredentials)!=null?o:!1),en(this,$r,$u).call(this)}get readyState(){return qe(this,er)}get url(){return qe(this,Qn).href}get withCredentials(){return qe(this,Gs)}get onerror(){return qe(this,Ao)}set onerror(t){at(this,Ao,t)}get onmessage(){return qe(this,No)}set onmessage(t){at(this,No,t)}get onopen(){return qe(this,Ea)}set onopen(t){at(this,Ea,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){qe(this,Mo)&&clearTimeout(qe(this,Mo)),qe(this,er)!==this.CLOSED&&(qe(this,wn)&&qe(this,wn).abort(),at(this,er,this.CLOSED),at(this,wn,void 0))}}er=new WeakMap,Qn=new WeakMap,Po=new WeakMap,Gs=new WeakMap,Ws=new WeakMap,Ia=new WeakMap,Mo=new WeakMap,xa=new WeakMap,wn=new WeakMap,Oo=new WeakMap,Ao=new WeakMap,No=new WeakMap,Ea=new WeakMap,$r=new WeakSet,$u=function(){at(this,er,this.CONNECTING),at(this,wn,new AbortController),qe(this,Ws)(qe(this,Qn),en(this,$r,Ig).call(this)).then(qe(this,Ru)).catch(qe(this,Pu))},Ru=new WeakMap,Pu=new WeakMap,Ig=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,xa)?{"Last-Event-ID":qe(this,xa)}:void 0},cache:"no-store",signal:(e=qe(this,wn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Mu=new WeakMap,Ou=new WeakMap,$a=function(e,t){var r;qe(this,er)!==this.CLOSED&&at(this,er,this.CLOSED);const n=new Tg("error",{code:t,message:e});(r=qe(this,Ao))==null||r.call(this,n),this.dispatchEvent(n)},Au=function(e,t){var r;if(qe(this,er)===this.CLOSED)return;at(this,er,this.CONNECTING);const n=new Tg("error",{code:t,message:e});(r=qe(this,Ao))==null||r.call(this,n),this.dispatchEvent(n),at(this,Mo,setTimeout(qe(this,Nu),qe(this,Ia)))},Nu=new WeakMap,Ks.CONNECTING=0,Ks.OPEN=1,Ks.CLOSED=2;function q8(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class L8 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ys{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=B2(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new kr("No auth provider");let t;try{t=await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new kr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=qs(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Ks(this._url.href,{...this._eventSourceInit,fetch:async(o,a)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const s=await t(o,{...a,headers:i});if(s.status===401&&s.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=Bs(s);this._resourceMetadataUrl=l,this._scope=c}return s}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const a=new L8(o.code,o.message,o);n(a),this.onerror?.(a)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const a=o;try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{const a=o;let i;try{i=Wn.parse(JSON.parse(a.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new kr("No auth provider");if(await Yn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const a=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:s}=Bs(o);if(this._resourceMetadataUrl=i,this._scope=s,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${a}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Qs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Qs,r=new Qs;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var qu=T({error:T({message:d(),type:d().nullish(),param:ut().nullish(),code:ae([d(),q()]).nullish()})}),Rr=ir({errorSchema:qu,errorToMessage:e=>e.error.message});function xg(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4")||e.startsWith("gpt-5.5");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function Eg(e){var t,r,n,o,a,i;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(i=(a=e.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?i:0;return{inputTokens:{total:s,noCache:s-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function j8(e){return JSON.stringify(e===void 0?{}:e)}function D8({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:a,content:i}of e)switch(a){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const s=t;throw new Error(`Unsupported system message mode: ${s}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((s,l)=>{var c,u,h;switch(s.type){case"text":return{type:"text",text:s.text};case"file":if(s.mediaType.startsWith("image/")){const p=s.mediaType==="image/*"?"image/jpeg":s.mediaType;return{type:"image_url",image_url:{url:s.data instanceof URL?s.data.toString():`data:${p};base64,${vo(s.data)}`,detail:(u=(c=s.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(s.mediaType.startsWith("audio/")){if(s.data instanceof URL)throw new Tr({functionality:"audio file parts with URLs"});switch(s.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:vo(s.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:vo(s.data),format:"mp3"}};default:throw new Tr({functionality:`audio content parts with media type ${s.mediaType}`})}}else if(s.mediaType==="application/pdf"){if(s.data instanceof URL)throw new Tr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof s.data=="string"&&s.data.startsWith("file-")?{file_id:s.data}:{filename:(h=s.filename)!=null?h:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${vo(s.data)}`}}}else throw new Tr({functionality:`file part media type ${s.mediaType}`})}})});break}case"assistant":{let s="";const l=[];for(const c of i)switch(c.type){case"text":{s+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:j8(c.input)}});break}}n.push({role:"assistant",content:l.length>0?s||null:s,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const s of i){if(s.type==="tool-approval-response")continue;const l=s.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:s.toolCallId,content:c})}break}default:{const s=a;throw new Error(`Unsupported role: ${s}`)}}return{messages:n,warnings:o}}function Lu({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function $g(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var U8=ye(()=>me(T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({message:T({role:M("assistant").nullish(),content:d().nullish(),tool_calls:L(T({id:d().nullish(),type:M("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:L(T({type:M("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:d(),title:d()})})).nullish()}),index:q(),logprobs:T({content:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}))),z8=ye(()=>me(ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({delta:T({role:le(["assistant"]).nullish(),content:d().nullish(),tool_calls:L(T({index:q(),id:d().nullish(),type:M("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:L(T({type:M("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:q()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}),qu]))),F8=ye(()=>me(T({logitBias:pe(Oh(),q()).optional(),logprobs:ae([_e(),q()]).optional(),parallelToolCalls:_e().optional(),user:d().optional(),reasoningEffort:le(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:q().optional(),store:_e().optional(),metadata:pe(d().max(64),d().max(512)).optional(),prediction:pe(d(),ut()).optional(),serviceTier:le(["auto","flex","priority","default"]).optional(),strictJsonSchema:_e().optional(),textVerbosity:le(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:le(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:le(["system","developer","remove"]).optional(),forceReasoning:_e().optional()})));function V8({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const a of e)switch(a.type){case"function":n.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,...a.strict!=null?{strict:a.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${a.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const a=o;throw new Tr({functionality:`tool choice type: ${a}`})}}}var Z8=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:p}){var m,f,b,w,C;const v=[],g=(m=await Ir({provider:"openai",providerOptions:p,schema:F8}))!=null?m:{},I=xg(this.modelId),y=(f=g.forceReasoning)!=null?f:I.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:_,warnings:k}=D8({prompt:e,systemMessageMode:(b=g.systemMessageMode)!=null?b:y?"developer":I.systemMessageMode});v.push(...k);const S=(w=g.strictJsonSchema)!=null?w:!0,E={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs=="number"?!0:void 0,top_logprobs:typeof g.logprobs=="number"?g.logprobs:typeof g.logprobs=="boolean"&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:S,name:(C=l.name)!=null?C:"response",description:l.description}}:{type:"json_object"}:void 0,stop:s,seed:c,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:g.reasoningEffort,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:_};y?((g.reasoningEffort!=="none"||!I.supportsNonReasoningParameters)&&(E.temperature!=null&&(E.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),E.top_p!=null&&(E.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),E.logprobs!=null&&(E.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),E.frequency_penalty!=null&&(E.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),E.presence_penalty!=null&&(E.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),E.logit_bias!=null&&(E.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),E.top_logprobs!=null&&(E.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),E.max_tokens!=null&&(E.max_completion_tokens==null&&(E.max_completion_tokens=E.max_tokens),E.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&E.temperature!=null&&(E.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!I.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0),g.serviceTier==="priority"&&!I.supportsPriorityProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),E.service_tier=void 0);const{tools:R,toolChoice:x,toolWarnings:N}=V8({tools:u,toolChoice:h});return{args:{...E,tools:R,tool_choice:x},warnings:[...v,...N]}}async doGenerate(e){var t,r,n,o,a,i,s;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:h,rawValue:p}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:l,failedResponseHandler:Rr,successfulResponseHandler:At(U8),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=h.choices[0],f=[],b=m.message.content;b!=null&&b.length>0&&f.push({type:"text",text:b});for(const v of(t=m.message.tool_calls)!=null?t:[])f.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:Kt(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=m.message.annotations)!=null?n:[])f.push({type:"source",sourceType:"url",id:Kt(),url:v.url_citation.url,title:v.url_citation.title});const w=(o=h.usage)==null?void 0:o.completion_tokens_details;(a=h.usage)==null||a.prompt_tokens_details;const C={openai:{}};return w?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=w?.accepted_prediction_tokens),w?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=w?.rejected_prediction_tokens),((i=m.logprobs)==null?void 0:i.content)!=null&&(C.openai.logprobs=m.logprobs.content),{content:f,finishReason:{unified:$g(m.finish_reason),raw:(s=m.finish_reason)!=null?s:void 0},usage:Eg(h.usage),request:{body:l},response:{...Lu(h),headers:u,body:p},warnings:c,providerMetadata:C}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:a}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:_s(z8),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let s={unified:"other",raw:void 0},l,c=!1,u=!1;const h={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,m){var f,b,w,C,v,g,I,y,_,k,S,E,R,x,N,U,z;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){s={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}const ee=p.value;if("error"in ee){s={unified:"error",raw:void 0},m.enqueue({type:"error",error:ee.error});return}if(!c){const re=Lu(ee);Object.values(re).some(Boolean)&&(c=!0,m.enqueue({type:"response-metadata",...Lu(ee)}))}ee.usage!=null&&(l=ee.usage,((f=ee.usage.completion_tokens_details)==null?void 0:f.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(b=ee.usage.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((w=ee.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(C=ee.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens));const Q=ee.choices[0];if(Q?.finish_reason!=null&&(s={unified:$g(Q.finish_reason),raw:Q.finish_reason}),((v=Q?.logprobs)==null?void 0:v.content)!=null&&(h.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const se=Q.delta;if(se.content!=null&&(u||(m.enqueue({type:"text-start",id:"0"}),u=!0),m.enqueue({type:"text-delta",id:"0",delta:se.content})),se.tool_calls!=null)for(const re of se.tool_calls){const Se=re.index;if(i[Se]==null){if(re.type!=null&&re.type!=="function")throw new cl({data:re,message:"Expected 'function' type."});if(re.id==null)throw new cl({data:re,message:"Expected 'id' to be a string."});if(((g=re.function)==null?void 0:g.name)==null)throw new cl({data:re,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),i[Se]={id:re.id,type:"function",function:{name:re.function.name,arguments:(I=re.function.arguments)!=null?I:""},hasFinished:!1};const D=i[Se];((y=D.function)==null?void 0:y.name)!=null&&((_=D.function)==null?void 0:_.arguments)!=null&&(D.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),bf(D.function.arguments)&&(m.enqueue({type:"tool-input-end",id:D.id}),m.enqueue({type:"tool-call",toolCallId:(k=D.id)!=null?k:Kt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0));continue}const H=i[Se];H.hasFinished||(((S=re.function)==null?void 0:S.arguments)!=null&&(H.function.arguments+=(R=(E=re.function)==null?void 0:E.arguments)!=null?R:""),m.enqueue({type:"tool-input-delta",id:H.id,delta:(x=re.function.arguments)!=null?x:""}),((N=H.function)==null?void 0:N.name)!=null&&((U=H.function)==null?void 0:U.arguments)!=null&&bf(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(z=H.id)!=null?z:Kt(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(se.annotations!=null)for(const re of se.annotations)m.enqueue({type:"source",sourceType:"url",id:Kt(),url:re.url_citation.url,title:re.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:s,usage:Eg(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function Rg(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const a=(t=e.prompt_tokens)!=null?t:0,i=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:a,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:i,reasoning:void 0},raw:e}}function H8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
77
|
-
|
|
78
|
-
`,e=e.slice(1));for(const{role:o,content:a}of e)switch(o){case"system":throw new un({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const i=a.map(s=>{switch(s.type){case"text":return s.text}}).filter(Boolean).join("");n+=`${t}:
|
|
79
|
-
${i}
|
|
80
|
-
|
|
81
|
-
`;break}case"assistant":{const i=a.map(s=>{switch(s.type){case"text":return s.text;case"tool-call":throw new Tr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
|
|
82
|
-
${i}
|
|
83
|
-
|
|
84
|
-
`;break}case"tool":throw new Tr({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
|
|
85
|
-
`,{prompt:n,stopSequences:[`
|
|
86
|
-
${t}:`]}}function Pg({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Mg(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var B8=ye(()=>me(T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d(),logprobs:T({tokens:L(d()),token_logprobs:L(q()),top_logprobs:L(pe(d(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}))),J8=ye(()=>me(ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d().nullish(),index:q(),logprobs:T({tokens:L(d()),token_logprobs:L(q()),top_logprobs:L(pe(d(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}),qu]))),Og=ye(()=>me(T({echo:_e().optional(),logitBias:pe(d(),q()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([_e(),q()]).optional()}))),G8=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:p}){const m=[],f={...await Ir({provider:"openai",providerOptions:p,schema:Og}),...await Ir({provider:this.providerOptionsName,providerOptions:p,schema:Og})};o!=null&&m.push({type:"unsupported",feature:"topK"}),c?.length&&m.push({type:"unsupported",feature:"tools"}),u!=null&&m.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&m.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:w}=H8({prompt:e}),C=[...w??[],...s??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,seed:h,prompt:b,stop:C.length>0?C:void 0},warnings:m}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:a,rawValue:i}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:r,failedResponseHandler:Rr,successfulResponseHandler:At(B8),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],l={openai:{}};return s.logprobs!=null&&(l.openai.logprobs=s.logprobs),{content:[{type:"text",text:s.text}],usage:Rg(a.usage),finishReason:{unified:Mg(s.finish_reason),raw:(t=s.finish_reason)!=null?t:void 0},request:{body:r},response:{...Pg(a),headers:o,body:i},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:a}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:_s(J8),abortSignal:e.abortSignal,fetch:this.config.fetch});let i={unified:"other",raw:void 0};const s={openai:{}};let l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...Pg(p)}),h.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const m=p.choices[0];m?.finish_reason!=null&&(i={unified:Mg(m.finish_reason),raw:m.finish_reason}),m?.logprobs!=null&&(s.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:i,providerMetadata:s,usage:Rg(l)})}})),request:{body:n},response:{headers:o}}}},W8=ye(()=>me(T({dimensions:q().optional(),user:d().optional()}))),K8=ye(()=>me(T({data:L(T({embedding:L(q())})),usage:T({prompt_tokens:q()}).nullish()}))),Y8=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new P1({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const a=(o=await Ir({provider:"openai",providerOptions:n,schema:W8}))!=null?o:{},{responseHeaders:i,value:s,rawValue:l}=await Ot({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:It(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:Rr,successfulResponseHandler:At(K8),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:s.data.map(c=>c.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},Ag=ye(()=>me(T({created:q().nullish(),data:L(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:q().nullish(),output_tokens:q().nullish(),total_tokens:q().nullish(),input_tokens_details:T({image_tokens:q().nullish(),text_tokens:q().nullish()}).nullish()}).nullish()}))),Q8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},X8=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function ex(e){return X8.some(t=>e.startsWith(t))}var Ng=T({quality:le(["standard","hd","low","medium","high","auto"]).optional(),background:le(["transparent","opaque","auto"]).optional(),outputFormat:le(["png","jpeg","webp"]).optional(),outputCompression:q().int().min(0).max(100).optional(),user:d().optional()}),tx=ye(()=>me(Ng.extend({style:le(["vivid","natural"]).optional(),moderation:le(["auto","low"]).optional()}))),rx=ye(()=>me(Ng.extend({inputFidelity:le(["high","low"]).optional()}))),nx=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=Q8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:a,seed:i,providerOptions:s,headers:l,abortSignal:c}){var u,h,p,m,f,b,w,C,v,g,I;const y=[];a!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&y.push({type:"unsupported",feature:"seed"});const _=(p=(h=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:h.call(u))!=null?p:new Date;if(t!=null){const R=(m=await Ir({provider:"openai",providerOptions:s,schema:rx}))!=null?m:{},{value:x,responseHeaders:N}=await Tf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:It(this.config.headers(),l),formData:i4({model:this.modelId,prompt:e,image:await Promise.all(t.map(U=>U.type==="file"?new Blob([U.data instanceof Uint8Array?new Blob([U.data],{type:U.mediaType}):new Blob([Un(U.data)],{type:U.mediaType})],{type:U.mediaType}):uf(U.url))),mask:r!=null?await ox(r):void 0,n,size:o,quality:R.quality,background:R.background,output_format:R.outputFormat,output_compression:R.outputCompression,input_fidelity:R.inputFidelity,user:R.user}),failedResponseHandler:Rr,successfulResponseHandler:At(Ag),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(U=>U.b64_json),warnings:y,usage:x.usage!=null?{inputTokens:(f=x.usage.input_tokens)!=null?f:void 0,outputTokens:(b=x.usage.output_tokens)!=null?b:void 0,totalTokens:(w=x.usage.total_tokens)!=null?w:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:N},providerMetadata:{openai:{images:x.data.map((U,z)=>{var ee,Q,se,re,Se,H;return{...U.revised_prompt?{revisedPrompt:U.revised_prompt}:{},created:(ee=x.created)!=null?ee:void 0,size:(Q=x.size)!=null?Q:void 0,quality:(se=x.quality)!=null?se:void 0,background:(re=x.background)!=null?re:void 0,outputFormat:(Se=x.output_format)!=null?Se:void 0,...qg((H=x.usage)==null?void 0:H.input_tokens_details,z,x.data.length)}})}}}}const k=(C=await Ir({provider:"openai",providerOptions:s,schema:tx}))!=null?C:{},{value:S,responseHeaders:E}=await Ot({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:It(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,quality:k.quality,style:k.style,background:k.background,moderation:k.moderation,output_format:k.outputFormat,output_compression:k.outputCompression,user:k.user,...ex(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Rr,successfulResponseHandler:At(Ag),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(R=>R.b64_json),warnings:y,usage:S.usage!=null?{inputTokens:(v=S.usage.input_tokens)!=null?v:void 0,outputTokens:(g=S.usage.output_tokens)!=null?g:void 0,totalTokens:(I=S.usage.total_tokens)!=null?I:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:E},providerMetadata:{openai:{images:S.data.map((R,x)=>{var N,U,z,ee,Q,se;return{...R.revised_prompt?{revisedPrompt:R.revised_prompt}:{},created:(N=S.created)!=null?N:void 0,size:(U=S.size)!=null?U:void 0,quality:(z=S.quality)!=null?z:void 0,background:(ee=S.background)!=null?ee:void 0,outputFormat:(Q=S.output_format)!=null?Q:void 0,...qg((se=S.usage)==null?void 0:se.input_tokens_details,x,S.data.length)}})}}}}};function qg(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),a=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?a:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),a=e.text_tokens-o*(r-1);n.textTokens=t===r-1?a:o}return n}async function ox(e){if(!e)return;if(e.type==="url")return uf(e.url);const t=e.data instanceof Uint8Array?e.data:Un(e.data);return new Blob([t],{type:e.mediaType})}var Lg=ye(()=>me(T({callId:d(),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}))),jg=ye(()=>me(T({status:le(["completed","failed"]),output:d().optional()}))),ax=sr({id:"openai.apply_patch",inputSchema:Lg,outputSchema:jg}),sx=ax,ix=ye(()=>me(T({code:d().nullish(),containerId:d()}))),lx=ye(()=>me(T({outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullish()}))),cx=ye(()=>me(T({container:ae([d(),T({fileIds:L(d()).optional()})]).optional()}))),ux=sr({id:"openai.code_interpreter",inputSchema:ix,outputSchema:lx}),dx=(e={})=>ux(e),px=ye(()=>me(T({name:d(),description:d().optional(),format:ae([T({type:M("grammar"),syntax:le(["regex","lark"]),definition:d()}),T({type:M("text")})]).optional()}))),hx=ye(()=>me(d())),fx=_6({id:"openai.custom",inputSchema:hx}),mx=e=>fx(e),Dg=T({key:d(),type:le(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),q(),_e(),L(d())])}),Ug=T({type:le(["and","or"]),filters:L(ae([Dg,ss(()=>Ug)]))}),gx=ye(()=>me(T({vectorStoreIds:L(d()),maxNumResults:q().optional(),ranking:T({ranker:d().optional(),scoreThreshold:q().optional()}).optional(),filters:ae([Dg,Ug]).optional()}))),_x=ye(()=>me(T({queries:L(d()),results:L(T({attributes:pe(d(),Te()),fileId:d(),filename:d(),score:q(),text:d()})).nullable()}))),yx=sr({id:"openai.file_search",inputSchema:T({}),outputSchema:_x}),vx=ye(()=>me(T({background:le(["auto","opaque","transparent"]).optional(),inputFidelity:le(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:le(["auto"]).optional(),outputCompression:q().int().min(0).max(100).optional(),outputFormat:le(["png","jpeg","webp"]).optional(),partialImages:q().int().min(0).max(3).optional(),quality:le(["auto","low","medium","high"]).optional(),size:le(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),wx=ye(()=>me(T({}))),bx=ye(()=>me(T({result:d()}))),kx=sr({id:"openai.image_generation",inputSchema:wx,outputSchema:bx}),Tx=(e={})=>kx(e),zg=ye(()=>me(T({action:T({type:M("exec"),command:L(d()),timeoutMs:q().optional(),user:d().optional(),workingDirectory:d().optional(),env:pe(d(),d()).optional()})}))),Fg=ye(()=>me(T({output:d()}))),Cx=sr({id:"openai.local_shell",inputSchema:zg,outputSchema:Fg}),Vg=ye(()=>me(T({action:T({commands:L(d()),timeoutMs:q().optional(),maxOutputLength:q().optional()})}))),ju=ye(()=>me(T({output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exitCode:q()})])}))}))),Sx=L(Le("type",[T({type:M("skillReference"),skillId:d(),version:d().optional()}),T({type:M("inline"),name:d(),description:d(),source:T({type:M("base64"),mediaType:M("application/zip"),data:d()})})])).optional(),Ix=ye(()=>me(T({environment:ae([T({type:M("containerAuto"),fileIds:L(d()).optional(),memoryLimit:le(["1g","4g","16g","64g"]).optional(),networkPolicy:Le("type",[T({type:M("disabled")}),T({type:M("allowlist"),allowedDomains:L(d()),domainSecrets:L(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:Sx}),T({type:M("containerReference"),containerId:d()}),T({type:M("local").optional(),skills:L(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),xx=sr({id:"openai.shell",inputSchema:Vg,outputSchema:ju}),Ex=ye(()=>me(T({execution:le(["server","client"]).optional(),description:d().optional(),parameters:pe(d(),Te()).optional()}))),Du=ye(()=>me(T({arguments:Te().optional(),call_id:d().nullish()}))),Uu=ye(()=>me(T({tools:L(pe(d(),Te()))}))),$x=sr({id:"openai.tool_search",inputSchema:Du,outputSchema:Uu}),Rx=(e={})=>$x(e),Px=ye(()=>me(T({externalWebAccess:_e().optional(),filters:T({allowedDomains:L(d()).optional()}).optional(),searchContextSize:le(["low","medium","high"]).optional(),userLocation:T({type:M("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Mx=ye(()=>me(T({}))),Ox=ye(()=>me(T({action:Le("type",[T({type:M("search"),query:d().optional(),queries:L(d()).optional()}),T({type:M("openPage"),url:d().nullish()}),T({type:M("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).optional()}))),Ax=sr({id:"openai.web_search",inputSchema:Mx,outputSchema:Ox}),Nx=(e={})=>Ax(e),qx=ye(()=>me(T({searchContextSize:le(["low","medium","high"]).optional(),userLocation:T({type:M("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Lx=ye(()=>me(T({}))),jx=ye(()=>me(T({action:Le("type",[T({type:M("search"),query:d().optional()}),T({type:M("openPage"),url:d().nullish()}),T({type:M("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),Dx=sr({id:"openai.web_search_preview",inputSchema:Lx,outputSchema:jx}),zu=ss(()=>ae([d(),q(),_e(),Qo(),L(zu),pe(d(),zu)])),Ux=ye(()=>me(T({serverLabel:d(),allowedTools:ae([L(d()),T({readOnly:_e().optional(),toolNames:L(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:pe(d(),d()).optional(),requireApproval:ae([le(["always","never"]),T({never:T({toolNames:L(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),zx=ye(()=>me(T({}))),Fx=ye(()=>me(T({type:M("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),zu]).optional()}))),Vx=sr({id:"openai.mcp",inputSchema:zx,outputSchema:Fx}),Zx=e=>Vx(e),Hx={applyPatch:sx,customTool:mx,codeInterpreter:dx,fileSearch:yx,imageGeneration:Tx,localShell:Cx,shell:xx,webSearchPreview:Dx,webSearch:Nx,mcp:Zx,toolSearch:Rx};function Zg(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const a=e.input_tokens,i=e.output_tokens,s=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i,text:i-l,reasoning:l},raw:e}}function Bx(e){return JSON.stringify(e===void 0?{}:e)}function Hg(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function Jx({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,passThroughUnsupportedFiles:a=!1,store:i,hasConversation:s=!1,hasPreviousResponseId:l=!1,hasLocalShellTool:c=!1,hasShellTool:u=!1,hasApplyPatchTool:h=!1,customProviderToolNames:p}){var m,f,b,w,C,v,g,I,y,_,k,S,E,R,x,N,U,z,ee,Q,se,re,Se;let H=[];const D=[],B=new Set;for(const{role:F,content:$}of e)switch(F){case"system":{switch(r){case"system":{H.push({role:"system",content:$});break}case"developer":{H.push({role:"developer",content:$});break}case"remove":{D.push({type:"other",message:"system messages are removed for this model"});break}default:{const O=r;throw new Error(`Unsupported system message mode: ${O}`)}}break}case"user":{H.push({role:"user",content:$.map((O,j)=>{var G,Y,W;switch(O.type){case"text":return{type:"input_text",text:O.text};case"file":{const V=O.mediaType==="image/*"?"image/jpeg":O.mediaType;if(V.startsWith("image/"))return{type:"input_image",...O.data instanceof URL?{image_url:O.data.toString()}:typeof O.data=="string"&&Hg(O.data,o)?{file_id:O.data}:{image_url:`data:${V};base64,${vo(O.data)}`},detail:(Y=(G=O.providerOptions)==null?void 0:G[n])==null?void 0:Y.imageDetail};if(O.data instanceof URL)return{type:"input_file",file_url:O.data.toString()};if(V!=="application/pdf"&&!a)throw new Tr({functionality:`file part media type ${V}`});return{type:"input_file",...typeof O.data=="string"&&Hg(O.data,o)?{file_id:O.data}:{filename:(W=O.filename)!=null?W:V==="application/pdf"?`part-${j}.pdf`:`part-${j}`,file_data:`data:${V};base64,${vo(O.data)}`}}}}})});break}case"assistant":{const O={};for(const j of $)switch(j.type){case"text":{const G=(m=j.providerOptions)==null?void 0:m[n],Y=G?.itemId,W=G?.phase;if(s&&Y!=null)break;if(i&&Y!=null){H.push({type:"item_reference",id:Y});break}H.push({role:"assistant",content:[{type:"output_text",text:j.text}],id:Y,...W!=null&&{phase:W}});break}case"tool-call":{const G=(v=(b=(f=j.providerOptions)==null?void 0:f[n])==null?void 0:b.itemId)!=null?v:(C=(w=j.providerMetadata)==null?void 0:w[n])==null?void 0:C.itemId,Y=(k=(I=(g=j.providerOptions)==null?void 0:g[n])==null?void 0:I.namespace)!=null?k:(_=(y=j.providerMetadata)==null?void 0:y[n])==null?void 0:_.namespace;if(s&&G!=null)break;const W=t.toProviderToolName(j.toolName);if(W==="tool_search"){if(i&&G!=null){H.push({type:"item_reference",id:G});break}const A=typeof j.input=="string"?await gs({text:j.input,schema:Du}):await _t({value:j.input,schema:Du}),Z=A.call_id!=null?"client":"server";H.push({type:"tool_search_call",id:G??j.toolCallId,execution:Z,call_id:(S=A.call_id)!=null?S:null,status:"completed",arguments:A.arguments});break}if(j.providerExecuted){i&&G!=null&&H.push({type:"item_reference",id:G});break}if(l&&i&&G!=null)break;const V=c&&W==="local_shell"||u&&W==="shell"||h&&W==="apply_patch"||((E=p?.has(W))!=null?E:!1);if(i&&G!=null&&V){H.push({type:"item_reference",id:G});break}if(c&&W==="local_shell"){const A=await _t({value:j.input,schema:zg});H.push({type:"local_shell_call",call_id:j.toolCallId,id:G,action:{type:"exec",command:A.action.command,timeout_ms:A.action.timeoutMs,user:A.action.user,working_directory:A.action.workingDirectory,env:A.action.env}});break}if(u&&W==="shell"){const A=await _t({value:j.input,schema:Vg});H.push({type:"shell_call",call_id:j.toolCallId,id:G,status:"completed",action:{commands:A.action.commands,timeout_ms:A.action.timeoutMs,max_output_length:A.action.maxOutputLength}});break}if(h&&W==="apply_patch"){const A=await _t({value:j.input,schema:Lg});H.push({type:"apply_patch_call",call_id:A.callId,id:G,status:"completed",operation:A.operation});break}if(p?.has(W)){H.push({type:"custom_tool_call",call_id:j.toolCallId,name:W,input:typeof j.input=="string"?j.input:JSON.stringify(j.input),id:G});break}H.push({type:"function_call",call_id:j.toolCallId,name:W,arguments:Bx(j.input),...Y!=null&&{namespace:Y}});break}case"tool-result":{if(j.output.type==="execution-denied"||j.output.type==="json"&&typeof j.output.value=="object"&&j.output.value!=null&&"type"in j.output.value&&j.output.value.type==="execution-denied"||s)break;const G=t.toProviderToolName(j.toolName);if(G==="tool_search"){const Y=(N=(x=(R=j.providerOptions)==null?void 0:R[n])==null?void 0:x.itemId)!=null?N:j.toolCallId;if(i)H.push({type:"item_reference",id:Y});else if(j.output.type==="json"){const W=await _t({value:j.output.value,schema:Uu});H.push({type:"tool_search_output",id:Y,execution:"server",call_id:null,status:"completed",tools:W.tools})}break}if(u&&G==="shell"){if(j.output.type==="json"){const Y=await _t({value:j.output.value,schema:ju});H.push({type:"shell_call_output",call_id:j.toolCallId,output:Y.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:W.outcome.exitCode}}))})}break}if(i){const Y=(ee=(z=(U=j.providerOptions)==null?void 0:U[n])==null?void 0:z.itemId)!=null?ee:j.toolCallId;H.push({type:"item_reference",id:Y})}else D.push({type:"other",message:`Results for OpenAI tool ${j.toolName} are not sent to the API when store is false`});break}case"reasoning":{const G=await Ir({provider:n,providerOptions:j.providerOptions,schema:Gx}),Y=G?.itemId;if((s||l)&&Y!=null)break;if(Y!=null){const W=O[Y];if(i)W===void 0&&(H.push({type:"item_reference",id:Y}),O[Y]={type:"reasoning",id:Y,summary:[]});else{const V=[];j.text.length>0?V.push({type:"summary_text",text:j.text}):W!==void 0&&D.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(j)}.`}),W===void 0?(O[Y]={type:"reasoning",id:Y,encrypted_content:G?.reasoningEncryptedContent,summary:V},H.push(O[Y])):(W.summary.push(...V),G?.reasoningEncryptedContent!=null&&(W.encrypted_content=G.reasoningEncryptedContent))}}else{const W=G?.reasoningEncryptedContent;if(W!=null){const V=[];j.text.length>0&&V.push({type:"summary_text",text:j.text}),H.push({type:"reasoning",encrypted_content:W,summary:V})}else D.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(j)}.`})}break}}break}case"tool":{for(const O of $){if(O.type==="tool-approval-response"){const W=O;if(B.has(W.approvalId))continue;B.add(W.approvalId),i&&H.push({type:"item_reference",id:W.approvalId}),H.push({type:"mcp_approval_response",approval_request_id:W.approvalId,approve:W.approved});continue}const j=O.output;if(j.type==="execution-denied"&&((se=(Q=j.providerOptions)==null?void 0:Q.openai)==null?void 0:se.approvalId))continue;const G=t.toProviderToolName(O.toolName);if(G==="tool_search"&&j.type==="json"){const W=await _t({value:j.value,schema:Uu});H.push({type:"tool_search_output",execution:"client",call_id:O.toolCallId,status:"completed",tools:W.tools});continue}if(c&&G==="local_shell"&&j.type==="json"){const W=await _t({value:j.value,schema:Fg});H.push({type:"local_shell_call_output",call_id:O.toolCallId,output:W.output});continue}if(u&&G==="shell"&&j.type==="json"){const W=await _t({value:j.value,schema:ju});H.push({type:"shell_call_output",call_id:O.toolCallId,output:W.output.map(V=>({stdout:V.stdout,stderr:V.stderr,outcome:V.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:V.outcome.exitCode}}))});continue}if(h&&O.toolName==="apply_patch"&&j.type==="json"){const W=await _t({value:j.value,schema:jg});H.push({type:"apply_patch_call_output",call_id:O.toolCallId,status:W.status,output:W.output});continue}if(p?.has(G)){let W;switch(j.type){case"text":case"error-text":W=j.value;break;case"execution-denied":W=(re=j.reason)!=null?re:"Tool execution denied.";break;case"json":case"error-json":W=JSON.stringify(j.value);break;case"content":W=j.value.map(V=>{var A,Z,J,te,de;switch(V.type){case"text":return{type:"input_text",text:V.text};case"image-data":return{type:"input_image",image_url:`data:${V.mediaType};base64,${V.data}`,detail:(Z=(A=V.providerOptions)==null?void 0:A[n])==null?void 0:Z.imageDetail};case"image-url":return{type:"input_image",image_url:V.url,detail:(te=(J=V.providerOptions)==null?void 0:J[n])==null?void 0:te.imageDetail};case"file-data":return{type:"input_file",filename:(de=V.filename)!=null?de:"data",file_data:`data:${V.mediaType};base64,${V.data}`};case"file-url":return{type:"input_file",file_url:V.url};default:D.push({type:"other",message:`unsupported custom tool content part type: ${V.type}`});return}}).filter(hf);break;default:W=""}H.push({type:"custom_tool_call_output",call_id:O.toolCallId,output:W});continue}let Y;switch(j.type){case"text":case"error-text":Y=j.value;break;case"execution-denied":Y=(Se=j.reason)!=null?Se:"Tool execution denied.";break;case"json":case"error-json":Y=JSON.stringify(j.value);break;case"content":Y=j.value.map(W=>{var V,A,Z,J,te;switch(W.type){case"text":return{type:"input_text",text:W.text};case"image-data":return{type:"input_image",image_url:`data:${W.mediaType};base64,${W.data}`,detail:(A=(V=W.providerOptions)==null?void 0:V[n])==null?void 0:A.imageDetail};case"image-url":return{type:"input_image",image_url:W.url,detail:(J=(Z=W.providerOptions)==null?void 0:Z[n])==null?void 0:J.imageDetail};case"file-data":return{type:"input_file",filename:(te=W.filename)!=null?te:"data",file_data:`data:${W.mediaType};base64,${W.data}`};case"file-url":return{type:"input_file",file_url:W.url};default:{D.push({type:"other",message:`unsupported tool content part type: ${W.type}`});return}}}).filter(hf);break}H.push({type:"function_call_output",call_id:O.toolCallId,output:Y})}break}default:{const O=F;throw new Error(`Unsupported role: ${O}`)}}return!i&&H.some(F=>"type"in F&&F.type==="reasoning"&&F.encrypted_content==null)&&(D.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),H=H.filter(F=>!("type"in F)||F.type!=="reasoning"||F.encrypted_content!=null)),{input:H,warnings:D}}var Gx=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Fu({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var Ra=ss(()=>ae([d(),q(),_e(),Qo(),L(Ra),pe(d(),Ra.optional())])),Wx=ye(()=>me(ae([T({type:M("response.output_text.delta"),item_id:d(),delta:d(),logprobs:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}),T({type:le(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:M("response.failed"),response:T({error:T({code:d().nullish(),message:d()}).nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),T({type:M("response.created"),response:T({id:d(),created_at:q(),model:d(),service_tier:d().nullish()})}),T({type:M("response.output_item.added"),output_index:q(),item:Le("type",[T({type:M("message"),id:d(),phase:le(["commentary","final_answer"]).nullish()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:M("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),namespace:d().nullish()}),T({type:M("web_search_call"),id:d(),status:d()}),T({type:M("computer_call"),id:d(),status:d()}),T({type:M("file_search_call"),id:d()}),T({type:M("image_generation_call"),id:d()}),T({type:M("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable(),status:d()}),T({type:M("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d()}),T({type:M("mcp_approval_request"),id:d()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])}),T({type:M("response.output_item.done"),output_index:q(),item:Le("type",[T({type:M("message"),id:d(),phase:le(["commentary","final_answer"]).nullish()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:M("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:M("completed"),namespace:d().nullish()}),T({type:M("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:M("completed")}),T({type:M("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable()}),T({type:M("image_generation_call"),id:d(),result:d()}),T({type:M("web_search_call"),id:d(),status:d(),action:Le("type",[T({type:M("search"),query:d().nullish(),queries:L(d()).nullish(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).nullish()}),T({type:M("open_page"),url:d().nullish()}),T({type:M("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:M("file_search_call"),id:d(),queries:L(d()),results:L(T({attributes:pe(d(),ae([d(),q(),_e()])),file_id:d(),filename:d(),score:q(),text:d()})).nullish()}),T({type:M("local_shell_call"),id:d(),call_id:d(),action:T({type:M("exec"),command:L(d()),timeout_ms:q().optional(),user:d().optional(),working_directory:d().optional(),env:pe(d(),d()).optional()})}),T({type:M("computer_call"),id:d(),status:M("completed")}),T({type:M("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d(),server_label:d(),tools:L(T({name:d(),description:d().optional(),input_schema:ut(),annotations:pe(d(),Te()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:M("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])}),T({type:M("response.function_call_arguments.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.custom_tool_call_input.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.image_generation_call.partial_image"),item_id:d(),output_index:q(),partial_image_b64:d()}),T({type:M("response.code_interpreter_call_code.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.code_interpreter_call_code.done"),item_id:d(),output_index:q(),code:d()}),T({type:M("response.output_text.annotation.added"),annotation:Le("type",[T({type:M("url_citation"),start_index:q(),end_index:q(),url:d(),title:d()}),T({type:M("file_citation"),file_id:d(),filename:d(),index:q()}),T({type:M("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:q(),end_index:q()}),T({type:M("file_path"),file_id:d(),index:q()})])}),T({type:M("response.reasoning_summary_part.added"),item_id:d(),summary_index:q()}),T({type:M("response.reasoning_summary_text.delta"),item_id:d(),summary_index:q(),delta:d()}),T({type:M("response.reasoning_summary_part.done"),item_id:d(),summary_index:q()}),T({type:M("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:q(),delta:d(),obfuscation:d().nullish()}),T({type:M("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:q(),diff:d()}),T({type:M("error"),sequence_number:q(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Kx=ye(()=>me(T({id:d().optional(),created_at:q().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:L(Le("type",[T({type:M("message"),role:M("assistant"),id:d(),phase:le(["commentary","final_answer"]).nullish(),content:L(T({type:M("output_text"),text:d(),logprobs:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish(),annotations:L(Le("type",[T({type:M("url_citation"),start_index:q(),end_index:q(),url:d(),title:d()}),T({type:M("file_citation"),file_id:d(),filename:d(),index:q()}),T({type:M("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:q(),end_index:q()}),T({type:M("file_path"),file_id:d(),index:q()})]))}))}),T({type:M("web_search_call"),id:d(),status:d(),action:Le("type",[T({type:M("search"),query:d().nullish(),queries:L(d()).nullish(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).nullish()}),T({type:M("open_page"),url:d().nullish()}),T({type:M("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:M("file_search_call"),id:d(),queries:L(d()),results:L(T({attributes:pe(d(),ae([d(),q(),_e()])),file_id:d(),filename:d(),score:q(),text:d()})).nullish()}),T({type:M("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable()}),T({type:M("image_generation_call"),id:d(),result:d()}),T({type:M("local_shell_call"),id:d(),call_id:d(),action:T({type:M("exec"),command:L(d()),timeout_ms:q().optional(),user:d().optional(),working_directory:d().optional(),env:pe(d(),d()).optional()})}),T({type:M("function_call"),call_id:d(),name:d(),arguments:d(),id:d(),namespace:d().nullish()}),T({type:M("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),T({type:M("computer_call"),id:d(),status:d().optional()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish(),summary:L(T({type:M("summary_text"),text:d()}))}),T({type:M("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d(),server_label:d(),tools:L(T({name:d(),description:d().optional(),input_schema:ut(),annotations:pe(d(),Te()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:M("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}).optional()}))),Bg=20,Jg=ye(()=>me(T({conversation:d().nullish(),include:L(le(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([_e(),q().min(1).max(Bg)]).optional(),maxToolCalls:q().nullish(),metadata:ut().nullish(),parallelToolCalls:_e().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:le(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:le(["auto","flex","priority","default"]).nullish(),store:_e().nullish(),passThroughUnsupportedFiles:_e().optional(),strictJsonSchema:_e().nullish(),textVerbosity:le(["low","medium","high"]).nullish(),truncation:le(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:le(["system","developer","remove"]).optional(),forceReasoning:_e().optional(),allowedTools:T({toolNames:L(d()).min(1),mode:le(["auto","required"]).optional()}).optional()})));async function Yx({tools:e,toolChoice:t,allowedTools:r,toolNameMapping:n,customProviderToolNames:o}){var a,i,s;e=e?.length?e:void 0;const l=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:l};const c=[],u=new Map,h=o??new Set;for(const m of e)switch(m.type){case"function":{const f=(a=m.providerOptions)==null?void 0:a.openai,b=Qx({tool:m,options:f}),w=f?.namespace;if(w==null)c.push(b);else{let C=u.get(w.name);if(C==null)C={type:"namespace",name:w.name,description:w.description,tools:[]},u.set(w.name,C),c.push(C);else if(C.description!==w.description)throw new Tr({functionality:`conflicting descriptions for OpenAI tool namespace "${w.name}"`});C.tools.push(b)}break}case"provider":{switch(m.id){case"openai.file_search":{const f=await _t({value:m.args,schema:gx});c.push({type:"file_search",vector_store_ids:f.vectorStoreIds,max_num_results:f.maxNumResults,ranking_options:f.ranking?{ranker:f.ranking.ranker,score_threshold:f.ranking.scoreThreshold}:void 0,filters:f.filters});break}case"openai.local_shell":{c.push({type:"local_shell"});break}case"openai.shell":{const f=await _t({value:m.args,schema:Ix});c.push({type:"shell",...f.environment&&{environment:Xx(f.environment)}});break}case"openai.apply_patch":{c.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await _t({value:m.args,schema:qx});c.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await _t({value:m.args,schema:Px});c.push({type:"web_search",filters:f.filters!=null?{allowed_domains:f.filters.allowedDomains}:void 0,external_web_access:f.externalWebAccess,search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.code_interpreter":{const f=await _t({value:m.args,schema:cx});c.push({type:"code_interpreter",container:f.container==null?{type:"auto",file_ids:void 0}:typeof f.container=="string"?f.container:{type:"auto",file_ids:f.container.fileIds}});break}case"openai.image_generation":{const f=await _t({value:m.args,schema:vx});c.push({type:"image_generation",background:f.background,input_fidelity:f.inputFidelity,input_image_mask:f.inputImageMask?{file_id:f.inputImageMask.fileId,image_url:f.inputImageMask.imageUrl}:void 0,model:f.model,moderation:f.moderation,partial_images:f.partialImages,quality:f.quality,output_compression:f.outputCompression,output_format:f.outputFormat,size:f.size});break}case"openai.mcp":{const f=await _t({value:m.args,schema:Ux}),b=v=>({tool_names:v.toolNames}),w=f.requireApproval,C=w==null?void 0:typeof w=="string"?w:w.never!=null?{never:b(w.never)}:void 0;c.push({type:"mcp",server_label:f.serverLabel,allowed_tools:Array.isArray(f.allowedTools)?f.allowedTools:f.allowedTools?{read_only:f.allowedTools.readOnly,tool_names:f.allowedTools.toolNames}:void 0,authorization:f.authorization,connector_id:f.connectorId,headers:f.headers,require_approval:C??"never",server_description:f.serverDescription,server_url:f.serverUrl});break}case"openai.custom":{const f=await _t({value:m.args,schema:px});c.push({type:"custom",name:f.name,description:f.description,format:f.format}),h.add(f.name);break}case"openai.tool_search":{const f=await _t({value:m.args,schema:Ex});c.push({type:"tool_search",...f.execution!=null?{execution:f.execution}:{},...f.description!=null?{description:f.description}:{},...f.parameters!=null?{parameters:f.parameters}:{}});break}}break}default:l.push({type:"unsupported",feature:`function tool ${m}`});break}if(r!=null)return{tools:c,toolChoice:{type:"allowed_tools",mode:(i=r.mode)!=null?i:"auto",tools:r.toolNames.map(m=>{var f;return{type:"function",name:(f=n?.toProviderToolName(m))!=null?f:m}})},toolWarnings:l};if(t==null)return{tools:c,toolChoice:void 0,toolWarnings:l};const p=t.type;switch(p){case"auto":case"none":case"required":return{tools:c,toolChoice:p,toolWarnings:l};case"tool":{const m=(s=n?.toProviderToolName(t.toolName))!=null?s:t.toolName;return{tools:c,toolChoice:m==="code_interpreter"||m==="file_search"||m==="image_generation"||m==="web_search_preview"||m==="web_search"||m==="mcp"||m==="apply_patch"?{type:m}:h.has(m)?{type:"custom",name:m}:{type:"function",name:m},toolWarnings:l}}default:{const m=p;throw new Tr({functionality:`tool choice type: ${m}`})}}}function Qx({tool:e,options:t}){const r=t?.deferLoading;return{type:"function",name:e.name,description:e.description,parameters:e.inputSchema,...e.strict!=null?{strict:e.strict}:{},...r!=null?{defer_loading:r}:{}}}function Xx(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:e7(r.skills)}}return{type:"local",skills:e.skills}}function e7(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function Gg(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const a of o.content){if(a.type!=="tool-call")continue;const i=(r=(t=a.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;i!=null&&(n[i]=a.toolCallId)}return n}var t7=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:a,frequencyPenalty:i,seed:s,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:p}){var m,f,b,w,C,v,g,I,y,_,k;const S=[],E=xg(this.modelId);o!=null&&S.push({type:"unsupported",feature:"topK"}),s!=null&&S.push({type:"unsupported",feature:"seed"}),a!=null&&S.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&S.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&S.push({type:"unsupported",feature:"stopSequences"});const R=this.config.provider.includes("azure")?"azure":"openai";let x=await Ir({provider:R,providerOptions:c,schema:Jg});x==null&&R!=="openai"&&(x=await Ir({provider:"openai",providerOptions:c,schema:Jg}));const N=(m=x?.forceReasoning)!=null?m:E.isReasoningModel;x?.conversation&&x?.previousResponseId&&S.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const U=n4({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:V=>V.id==="openai.custom"?V.args.name:void 0}),z=new Set,{tools:ee,toolChoice:Q,toolWarnings:se}=await Yx({tools:u,toolChoice:h,allowedTools:(f=x?.allowedTools)!=null?f:void 0,toolNameMapping:U,customProviderToolNames:z}),{input:re,warnings:Se}=await Jx({prompt:l,toolNameMapping:U,systemMessageMode:(b=x?.systemMessageMode)!=null?b:N?"developer":E.systemMessageMode,providerOptionsName:R,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(w=x?.passThroughUnsupportedFiles)!=null?w:!1,store:(C=x?.store)!=null?C:!0,hasConversation:x?.conversation!=null,hasPreviousResponseId:x?.previousResponseId!=null,hasLocalShellTool:F("openai.local_shell"),hasShellTool:F("openai.shell"),hasApplyPatchTool:F("openai.apply_patch"),customProviderToolNames:z.size>0?z:void 0});S.push(...Se);const H=(v=x?.strictJsonSchema)!=null?v:!0;let D=x?.include;function B(V){D==null?D=[V]:D.includes(V)||(D=[...D,V])}function F(V){return u?.find(A=>A.type==="provider"&&A.id===V)!=null}const $=typeof x?.logprobs=="number"?x?.logprobs:x?.logprobs===!0?Bg:void 0;$&&B("message.output_text.logprobs");const O=(g=u?.find(V=>V.type==="provider"&&(V.id==="openai.web_search"||V.id==="openai.web_search_preview")))==null?void 0:g.name;O&&B("web_search_call.action.sources"),F("openai.code_interpreter")&&B("code_interpreter_call.outputs");const j=x?.store;j===!1&&N&&B("reasoning.encrypted_content");const G={model:this.modelId,input:re,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||x?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:H,name:(I=p.name)!=null?I:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...x?.textVerbosity&&{verbosity:x.textVerbosity}}},conversation:x?.conversation,max_tool_calls:x?.maxToolCalls,metadata:x?.metadata,parallel_tool_calls:x?.parallelToolCalls,previous_response_id:x?.previousResponseId,store:j,user:x?.user,instructions:x?.instructions,service_tier:x?.serviceTier,include:D,prompt_cache_key:x?.promptCacheKey,prompt_cache_retention:x?.promptCacheRetention,safety_identifier:x?.safetyIdentifier,top_logprobs:$,truncation:x?.truncation,...N&&(x?.reasoningEffort!=null||x?.reasoningSummary!=null)&&{reasoning:{...x?.reasoningEffort!=null&&{effort:x.reasoningEffort},...x?.reasoningSummary!=null&&{summary:x.reasoningSummary}}}};N?x?.reasoningEffort==="none"&&E.supportsNonReasoningParameters||(G.temperature!=null&&(G.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),G.top_p!=null&&(G.top_p=void 0,S.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(x?.reasoningEffort!=null&&S.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),x?.reasoningSummary!=null&&S.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),x?.serviceTier==="flex"&&!E.supportsFlexProcessing&&(S.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete G.service_tier),x?.serviceTier==="priority"&&!E.supportsPriorityProcessing&&(S.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete G.service_tier);const Y=(k=(_=(y=u?.find(V=>V.type==="provider"&&V.id==="openai.shell"))==null?void 0:y.args)==null?void 0:_.environment)==null?void 0:k.type,W=Y==="containerAuto"||Y==="containerReference";return{webSearchToolName:O,args:{...G,tools:ee,tool_choice:Q},warnings:[...S,...se],store:j,toolNameMapping:U,providerOptionsName:R,isShellProviderExecuted:W}}async doGenerate(e){var t,r,n,o,a,i,s,l,c,u,h,p,m,f,b,w,C,v,g,I,y,_,k,S,E,R,x,N;const{args:U,warnings:z,webSearchToolName:ee,toolNameMapping:Q,providerOptionsName:se,isShellProviderExecuted:re}=await this.getArgs(e),Se=this.config.url({path:"/responses",modelId:this.modelId}),H=Gg(e.prompt),{responseHeaders:D,value:B,rawValue:F}=await Ot({url:Se,headers:It(this.config.headers(),e.headers),body:U,failedResponseHandler:Rr,successfulResponseHandler:At(Kx),abortSignal:e.abortSignal,fetch:this.config.fetch});if(B.error)throw new tt({message:B.error.message,url:Se,requestBodyValues:U,statusCode:400,responseHeaders:D,responseBody:F,isRetryable:!1});const $=[],O=[];let j=!1;const G=[];for(const V of B.output)switch(V.type){case"reasoning":{V.summary.length===0&&V.summary.push({type:"summary_text",text:""});for(const A of V.summary)$.push({type:"reasoning",text:A.text,providerMetadata:{[se]:{itemId:V.id,reasoningEncryptedContent:(t=V.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("image_generation"),result:{result:V.result}});break}case"tool_search_call":{const A=(r=V.call_id)!=null?r:V.id,Z=V.execution==="server";Z&&G.push(A),$.push({type:"tool-call",toolCallId:A,toolName:Q.toCustomToolName("tool_search"),input:JSON.stringify({arguments:V.arguments,call_id:V.call_id}),...Z?{providerExecuted:!0}:{},providerMetadata:{[se]:{itemId:V.id}}});break}case"tool_search_output":{const A=(o=(n=V.call_id)!=null?n:G.shift())!=null?o:V.id;$.push({type:"tool-result",toolCallId:A,toolName:Q.toCustomToolName("tool_search"),result:{tools:V.tools},providerMetadata:{[se]:{itemId:V.id}}});break}case"local_shell_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("local_shell"),input:JSON.stringify({action:V.action}),providerMetadata:{[se]:{itemId:V.id}}});break}case"shell_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("shell"),input:JSON.stringify({action:{commands:V.action.commands}}),...re&&{providerExecuted:!0},providerMetadata:{[se]:{itemId:V.id}}});break}case"shell_call_output":{$.push({type:"tool-result",toolCallId:V.call_id,toolName:Q.toCustomToolName("shell"),result:{output:V.output.map(A=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="exit"?{type:"exit",exitCode:A.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const A of V.content){(i=(a=e.providerOptions)==null?void 0:a[se])!=null&&i.logprobs&&A.logprobs&&O.push(A.logprobs);const Z={itemId:V.id,...V.phase!=null&&{phase:V.phase},...A.annotations.length>0&&{annotations:A.annotations}};$.push({type:"text",text:A.text,providerMetadata:{[se]:Z}});for(const J of A.annotations)J.type==="url_citation"?$.push({type:"source",sourceType:"url",id:(c=(l=(s=this.config).generateId)==null?void 0:l.call(s))!=null?c:Kt(),url:J.url,title:J.title}):J.type==="file_citation"?$.push({type:"source",sourceType:"document",id:(p=(h=(u=this.config).generateId)==null?void 0:h.call(u))!=null?p:Kt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,index:J.index}}}):J.type==="container_file_citation"?$.push({type:"source",sourceType:"document",id:(b=(f=(m=this.config).generateId)==null?void 0:f.call(m))!=null?b:Kt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,containerId:J.container_id}}}):J.type==="file_path"&&$.push({type:"source",sourceType:"document",id:(v=(C=(w=this.config).generateId)==null?void 0:C.call(w))!=null?v:Kt(),mediaType:"application/octet-stream",title:J.file_id,filename:J.file_id,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,index:J.index}}})}break}case"function_call":{j=!0,$.push({type:"tool-call",toolCallId:V.call_id,toolName:V.name,input:V.arguments,providerMetadata:{[se]:{itemId:V.id,...V.namespace!=null&&{namespace:V.namespace}}}});break}case"custom_tool_call":{j=!0;const A=Q.toCustomToolName(V.name);$.push({type:"tool-call",toolCallId:V.call_id,toolName:A,input:JSON.stringify(V.input),providerMetadata:{[se]:{itemId:V.id}}});break}case"web_search_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName(ee??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName(ee??"web_search"),result:Kg(V.action)});break}case"mcp_call":{const A=V.approval_request_id!=null&&(g=H[V.approval_request_id])!=null?g:V.id,Z=`mcp.${V.name}`;$.push({type:"tool-call",toolCallId:A,toolName:Z,input:V.arguments,providerExecuted:!0,dynamic:!0}),$.push({type:"tool-result",toolCallId:A,toolName:Z,result:{type:"call",serverLabel:V.server_label,name:V.name,arguments:V.arguments,...V.output!=null?{output:V.output}:{},...V.error!=null?{error:V.error}:{}},providerMetadata:{[se]:{itemId:V.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(I=V.approval_request_id)!=null?I:V.id,Z=(k=(_=(y=this.config).generateId)==null?void 0:_.call(y))!=null?k:Kt(),J=`mcp.${V.name}`;$.push({type:"tool-call",toolCallId:Z,toolName:J,input:V.arguments,providerExecuted:!0,dynamic:!0}),$.push({type:"tool-approval-request",approvalId:A,toolCallId:Z});break}case"computer_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:V.status||"completed"}});break}case"file_search_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("file_search"),result:{queries:V.queries,results:(E=(S=V.results)==null?void 0:S.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?E:null}});break}case"code_interpreter_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("code_interpreter"),input:JSON.stringify({code:V.code,containerId:V.container_id}),providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("code_interpreter"),result:{outputs:V.outputs}});break}case"apply_patch_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("apply_patch"),input:JSON.stringify({callId:V.call_id,operation:V.operation}),providerMetadata:{[se]:{itemId:V.id}}});break}}const Y={[se]:{responseId:B.id,...O.length>0?{logprobs:O}:{},...typeof B.service_tier=="string"?{serviceTier:B.service_tier}:{}}},W=B.usage;return{content:$,finishReason:{unified:Fu({finishReason:(R=B.incomplete_details)==null?void 0:R.reason,hasFunctionCall:j}),raw:(N=(x=B.incomplete_details)==null?void 0:x.reason)!=null?N:void 0},usage:Zg(W),request:{body:U},response:{id:B.id,timestamp:new Date(B.created_at*1e3),modelId:B.model,headers:D,body:F},providerMetadata:Y,warnings:z}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:a,providerOptionsName:i,isShellProviderExecuted:s}=await this.getArgs(e),l=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:c,value:u}=await Ot({url:l,headers:It(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Rr,successfulResponseHandler:_s(Wx),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=this,p=Gg(e.prompt),m=new Map;let f={unified:"other",raw:void 0},b;const w=[];let C=null;const v={},g=[];let I,y=!1;const _={};let k;const S=[];return{stream:u.pipeThrough(new TransformStream({start(E){E.enqueue({type:"stream-start",warnings:r})},transform(E,R){var x,N,U,z,ee,Q,se,re,Se,H,D,B,F,$,O,j,G,Y,W,V,A,Z,J,te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr,rr,Lr,pr;if(e.includeRawChunks&&R.enqueue({type:"raw",rawValue:E.rawValue}),!E.success){const X=n7(E.rawValue)?o7({value:E.rawValue,cause:E.error,url:l,requestBodyValues:t,responseHeaders:c}):E.error;f={unified:"error",raw:void 0},R.enqueue({type:"error",error:X});return}const P=E.value;if(Wg(P)){if(P.item.type==="function_call")v[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},R.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="custom_tool_call"){const X=o.toCustomToolName(P.item.name);v[P.output_index]={toolName:X,toolCallId:P.item.call_id},R.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:X})}else if(P.item.type==="web_search_call")v[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),R.enqueue({type:"tool-input-end",id:P.item.id}),R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(P.item.type==="computer_call")v[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")v[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),R.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(P.item.type==="tool_search_call"){const X=P.item.id,Ie=o.toCustomToolName("tool_search"),We=P.item.execution==="server";v[P.output_index]={toolName:Ie,toolCallId:X,toolSearchExecution:(x=P.item.execution)!=null?x:"server"},We&&R.enqueue({type:"tool-input-start",id:X,toolName:Ie,providerExecuted:!0})}else if(P.item.type!=="tool_search_output"){if(!(P.item.type==="mcp_call"||P.item.type==="mcp_list_tools"||P.item.type==="mcp_approval_request"))if(P.item.type==="apply_patch_call"){const{call_id:X,operation:Ie}=P.item;if(v[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:X,applyPatch:{hasDiff:Ie.type==="delete_file",endEmitted:Ie.type==="delete_file"}},R.enqueue({type:"tool-input-start",id:X,toolName:o.toCustomToolName("apply_patch")}),Ie.type==="delete_file"){const We=JSON.stringify({callId:X,operation:Ie});R.enqueue({type:"tool-input-delta",id:X,delta:We}),R.enqueue({type:"tool-input-end",id:X})}else R.enqueue({type:"tool-input-delta",id:X,delta:`{"callId":"${Xn(X)}","operation":{"type":"${Xn(Ie.type)}","path":"${Xn(Ie.path)}","diff":"`})}else P.item.type==="shell_call"?v[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(g.splice(0,g.length),I=(N=P.item.phase)!=null?N:void 0,R.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[i]:{itemId:P.item.id,...P.item.phase!=null&&{phase:P.item.phase}}}})):Wg(P)&&P.item.type==="reasoning"&&(_[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},R.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[i]:{itemId:P.item.id,reasoningEncryptedContent:(U=P.item.encrypted_content)!=null?U:null}}})))}}else if(s7(P)){if(P.item.type==="message"){const X=(z=P.item.phase)!=null?z:I;I=void 0,R.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[i]:{itemId:P.item.id,...X!=null&&{phase:X},...g.length>0&&{annotations:g}}}})}else if(P.item.type==="function_call")v[P.output_index]=void 0,y=!0,R.enqueue({type:"tool-input-end",id:P.item.call_id,...P.item.namespace!=null&&{providerMetadata:{[i]:{namespace:P.item.namespace}}}}),R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[i]:{itemId:P.item.id,...P.item.namespace!=null&&{namespace:P.item.namespace}}}});else if(P.item.type==="custom_tool_call"){v[P.output_index]=void 0,y=!0;const X=o.toCustomToolName(P.item.name);R.enqueue({type:"tool-input-end",id:P.item.call_id}),R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:X,input:JSON.stringify(P.item.input),providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="web_search_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:Kg(P.item.action)});else if(P.item.type==="computer_call")v[P.output_index]=void 0,R.enqueue({type:"tool-input-end",id:P.item.id}),R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:P.item.status||"completed"}});else if(P.item.type==="file_search_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(Q=(ee=P.item.results)==null?void 0:ee.map(X=>({attributes:X.attributes,fileId:X.file_id,filename:X.filename,score:X.score,text:X.text})))!=null?Q:null}});else if(P.item.type==="code_interpreter_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:P.item.outputs}});else if(P.item.type==="image_generation_call")R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:P.item.result}});else if(P.item.type==="tool_search_call"){const X=v[P.output_index],Ie=P.item.execution==="server";if(X!=null){const We=Ie?X.toolCallId:(se=P.item.call_id)!=null?se:P.item.id;Ie?S.push(We):R.enqueue({type:"tool-input-start",id:We,toolName:X.toolName}),R.enqueue({type:"tool-input-end",id:We}),R.enqueue({type:"tool-call",toolCallId:We,toolName:X.toolName,input:JSON.stringify({arguments:P.item.arguments,call_id:Ie?null:We}),...Ie?{providerExecuted:!0}:{},providerMetadata:{[i]:{itemId:P.item.id}}})}v[P.output_index]=void 0}else if(P.item.type==="tool_search_output"){const X=(Se=(re=P.item.call_id)!=null?re:S.shift())!=null?Se:P.item.id;R.enqueue({type:"tool-result",toolCallId:X,toolName:o.toCustomToolName("tool_search"),result:{tools:P.item.tools},providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_call"){v[P.output_index]=void 0;const X=(H=P.item.approval_request_id)!=null?H:void 0,Ie=X!=null&&(B=(D=m.get(X))!=null?D:p[X])!=null?B:P.item.id,We=`mcp.${P.item.name}`;R.enqueue({type:"tool-call",toolCallId:Ie,toolName:We,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),R.enqueue({type:"tool-result",toolCallId:Ie,toolName:We,result:{type:"call",serverLabel:P.item.server_label,name:P.item.name,arguments:P.item.arguments,...P.item.output!=null?{output:P.item.output}:{},...P.item.error!=null?{error:P.item.error}:{}},providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")v[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const X=v[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(X.applyPatch.hasDiff||R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.item.operation.diff)}),R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0),X&&P.item.status==="completed"&&R.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[i]:{itemId:P.item.id}}}),v[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){v[P.output_index]=void 0;const X=(O=($=(F=h.config).generateId)==null?void 0:$.call(F))!=null?O:Kt(),Ie=(j=P.item.approval_request_id)!=null?j:P.item.id;m.set(Ie,X);const We=`mcp.${P.item.name}`;R.enqueue({type:"tool-call",toolCallId:X,toolName:We,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),R.enqueue({type:"tool-approval-request",approvalId:Ie,toolCallId:X})}else if(P.item.type==="local_shell_call")v[P.output_index]=void 0,R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{[i]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")v[P.output_index]=void 0,R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...s&&{providerExecuted:!0},providerMetadata:{[i]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")R.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(X=>({stdout:X.stdout,stderr:X.stderr,outcome:X.outcome.type==="exit"?{type:"exit",exitCode:X.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const X=_[P.item.id],Ie=Object.entries(X.summaryParts).filter(([We,ln])=>ln==="active"||ln==="can-conclude").map(([We])=>We);for(const We of Ie)R.enqueue({type:"reasoning-end",id:`${P.item.id}:${We}`,providerMetadata:{[i]:{itemId:P.item.id,reasoningEncryptedContent:(G=P.item.encrypted_content)!=null?G:null}}});delete _[P.item.id]}}else if(u7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:P.delta})}else if(d7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:P.delta})}else if(m7(P)){const X=v[P.output_index];X?.applyPatch&&(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.delta)}),X.applyPatch.hasDiff=!0)}else if(g7(P)){const X=v[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&(X.applyPatch.hasDiff||(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.diff)}),X.applyPatch.hasDiff=!0),R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0)}else if(p7(P))R.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(h7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.delta)})}else if(f7(P)){const X=v[P.output_index];X!=null&&(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),R.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:X.codeInterpreter.containerId}),providerExecuted:!0}))}else if(c7(P))C=P.response.id,R.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(r7(P))R.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(W=(Y=e.providerOptions)==null?void 0:Y[i])!=null&&W.logprobs&&P.logprobs&&w.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const X=_[P.item_id];X.summaryParts[P.summary_index]="active";for(const Ie of Object.keys(X.summaryParts))X.summaryParts[Ie]==="can-conclude"&&(R.enqueue({type:"reasoning-end",id:`${P.item_id}:${Ie}`,providerMetadata:{[i]:{itemId:P.item_id}}}),X.summaryParts[Ie]="concluded");R.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[i]:{itemId:P.item_id,reasoningEncryptedContent:(A=(V=_[P.item_id])==null?void 0:V.encryptedContent)!=null?A:null}}})}}else if(P.type==="response.reasoning_summary_text.delta")R.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[i]:{itemId:P.item_id}}});else if(P.type==="response.reasoning_summary_part.done")a?(R.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[i]:{itemId:P.item_id}}}),_[P.item_id].summaryParts[P.summary_index]="concluded"):_[P.item_id].summaryParts[P.summary_index]="can-conclude";else if(i7(P))f={unified:Fu({finishReason:(Z=P.response.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:y}),raw:(te=(J=P.response.incomplete_details)==null?void 0:J.reason)!=null?te:void 0},b=P.response.usage,typeof P.response.service_tier=="string"&&(k=P.response.service_tier);else if(l7(P)){const X=(de=P.response.incomplete_details)==null?void 0:de.reason;f={unified:X?Fu({finishReason:X,hasFunctionCall:y}):"error",raw:X??"error"},b=(fe=P.response.usage)!=null?fe:void 0}else _7(P)?(g.push(P.annotation),P.annotation.type==="url_citation"?R.enqueue({type:"source",sourceType:"url",id:(st=(wt=(Ye=h.config).generateId)==null?void 0:wt.call(Ye))!=null?st:Kt(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?R.enqueue({type:"source",sourceType:"document",id:(tr=(Be=(et=h.config).generateId)==null?void 0:Be.call(et))!=null?tr:Kt(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?R.enqueue({type:"source",sourceType:"document",id:(dr=(qr=(it=h.config).generateId)==null?void 0:qr.call(it))!=null?dr:Kt(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&R.enqueue({type:"source",sourceType:"document",id:(pr=(Lr=(rr=h.config).generateId)==null?void 0:Lr.call(rr))!=null?pr:Kt(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):y7(P)&&R.enqueue({type:"error",error:P})},flush(E){const R={[i]:{responseId:C,...w.length>0?{logprobs:w}:{},...k!==void 0?{serviceTier:k}:{}}};E.enqueue({type:"finish",finishReason:f,usage:Zg(b),providerMetadata:R})}})),request:{body:t},response:{headers:c}}}};function r7(e){return e.type==="response.output_text.delta"}function n7(e){const t=a7(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!="string"}function o7({value:e,cause:t,url:r,requestBodyValues:n,responseHeaders:o}){return new tt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:r,requestBodyValues:n,responseHeaders:o,responseBody:JSON.stringify(e),cause:t,data:e,isRetryable:!1})}function a7(e){return typeof e=="object"&&e!=null?e:void 0}function s7(e){return e.type==="response.output_item.done"}function i7(e){return e.type==="response.completed"||e.type==="response.incomplete"}function l7(e){return e.type==="response.failed"}function c7(e){return e.type==="response.created"}function u7(e){return e.type==="response.function_call_arguments.delta"}function d7(e){return e.type==="response.custom_tool_call_input.delta"}function p7(e){return e.type==="response.image_generation_call.partial_image"}function h7(e){return e.type==="response.code_interpreter_call_code.delta"}function f7(e){return e.type==="response.code_interpreter_call_code.done"}function m7(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function g7(e){return e.type==="response.apply_patch_call_operation_diff.done"}function Wg(e){return e.type==="response.output_item.added"}function _7(e){return e.type==="response.output_text.annotation.added"}function y7(e){return e.type==="error"}function Kg(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0,...e.queries!=null&&{queries:e.queries}},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function Xn(e){return JSON.stringify(e).slice(1,-1)}var v7=ye(()=>me(T({instructions:d().nullish(),speed:q().min(.25).max(4).default(1).nullish()}))),w7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:a,providerOptions:i}){const s=[],l=await Ir({provider:"openai",providerOptions:i,schema:v7}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:s.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const h in u){const p=u[h];p!==void 0&&(c[h]=p)}}return a&&s.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:c,warnings:s}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:a,warnings:i}=await this.getArgs(e),{value:s,responseHeaders:l,rawValue:c}=await Ot({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:a,failedResponseHandler:Rr,successfulResponseHandler:v6(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:i,request:{body:JSON.stringify(a)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},b7=ye(()=>me(T({text:d(),language:d().nullish(),duration:q().nullish(),words:L(T({word:d(),start:q(),end:q()})).nullish(),segments:L(T({id:q(),seek:q(),start:q(),end:q(),text:d(),tokens:L(q()),temperature:q(),avg_logprob:q(),compression_ratio:q(),no_speech_prob:q()})).nullish()}))),k7=ye(()=>me(T({include:L(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:q().min(0).max(1).default(0).optional(),timestampGranularities:L(le(["word","segment"])).default(["segment"]).optional()}))),Yg={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},T7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await Ir({provider:"openai",providerOptions:r,schema:k7}),a=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Un(e)]);a.append("model",this.modelId);const s=b4(t);if(a.append("file",new File([i],"audio",{type:t}),`audio.${s}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const h of u)a.append(`${c}[]`,String(h));else a.append(c,String(u))}return{formData:a,warnings:n}}async doGenerate(e){var t,r,n,o,a,i,s,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:h}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:f}=await Tf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),formData:u,failedResponseHandler:Rr,successfulResponseHandler:At(b7),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=p.language!=null&&p.language in Yg?Yg[p.language]:void 0;return{text:p.text,segments:(s=(i=(o=p.segments)==null?void 0:o.map(w=>({text:w.text,startSecond:w.start,endSecond:w.end})))!=null?i:(a=p.words)==null?void 0:a.map(w=>({text:w.word,startSecond:w.start,endSecond:w.end})))!=null?s:[],language:b,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:m,body:f}}}},C7="3.0.78";function Qg(e={}){var t,r;const n=(t=If(wo({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",a=()=>_n({Authorization:`Bearer ${w4({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${C7}`),i=b=>new Z8(b,{provider:`${o}.chat`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),s=b=>new G8(b,{provider:`${o}.completion`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),l=b=>new Y8(b,{provider:`${o}.embedding`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),c=b=>new nx(b,{provider:`${o}.image`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),u=b=>new T7(b,{provider:`${o}.transcription`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),h=b=>new w7(b,{provider:`${o}.speech`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),p=b=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return m(b)},m=b=>new t7(b,{provider:`${o}.responses`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(b){return p(b)};return f.specificationVersion="v3",f.languageModel=p,f.chat=i,f.completion=s,f.responses=m,f.embedding=l,f.embeddingModel=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=u,f.transcriptionModel=u,f.speech=h,f.speechModel=h,f.tools=Hx,f}Qg();var Xg="vercel.ai.error",S7=Symbol.for(Xg),e_,I7=class w1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[e_]=!0,this.name=t,this.cause=n}static isInstance(t){return w1.hasMarker(t,Xg)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};e_=S7;var Pt=I7,t_="AI_APICallError",r_=`vercel.ai.error.${t_}`,x7=Symbol.for(r_),n_,tn=class extends Pt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:a,cause:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:t_,message:e,cause:i}),this[n_]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=a,this.isRetryable=s,this.data=l}static isInstance(e){return Pt.hasMarker(e,r_)}};n_=x7;var o_="AI_EmptyResponseBodyError",a_=`vercel.ai.error.${o_}`,E7=Symbol.for(a_),s_,$7=class extends Pt{constructor({message:e="Empty response body"}={}){super({name:o_,message:e}),this[s_]=!0}static isInstance(e){return Pt.hasMarker(e,a_)}};s_=E7;function i_(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var l_="AI_InvalidArgumentError",c_=`vercel.ai.error.${l_}`,R7=Symbol.for(c_),u_,d_=class extends Pt{constructor({message:e,cause:t,argument:r}){super({name:l_,message:e,cause:t}),this[u_]=!0,this.argument=r}static isInstance(e){return Pt.hasMarker(e,c_)}};u_=R7;var p_="AI_InvalidResponseDataError",h_=`vercel.ai.error.${p_}`,P7=Symbol.for(h_),f_,m_=class extends Pt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:p_,message:t}),this[f_]=!0,this.data=e}static isInstance(e){return Pt.hasMarker(e,h_)}};f_=P7;var g_="AI_JSONParseError",__=`vercel.ai.error.${g_}`,M7=Symbol.for(__),y_,Xs=class extends Pt{constructor({text:e,cause:t}){super({name:g_,message:`JSON parsing failed: Text: ${e}.
|
|
87
|
-
Error message: ${i_(t)}`,cause:t}),this[y_]=!0,this.text=e}static isInstance(e){return Pt.hasMarker(e,__)}};y_=M7;var v_="AI_LoadAPIKeyError",w_=`vercel.ai.error.${v_}`,O7=Symbol.for(w_),b_,ei=class extends Pt{constructor({message:e}){super({name:v_,message:e}),this[b_]=!0}static isInstance(e){return Pt.hasMarker(e,w_)}};b_=O7;var k_="AI_NoSuchModelError",T_=`vercel.ai.error.${k_}`,A7=Symbol.for(T_),C_,S_=class extends Pt{constructor({errorName:e=k_,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[C_]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Pt.hasMarker(e,T_)}};C_=A7;var I_="AI_TypeValidationError",x_=`vercel.ai.error.${I_}`,N7=Symbol.for(x_),E_,q7=class zd extends Pt{constructor({value:t,cause:r}){super({name:I_,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
88
|
-
Error message: ${i_(r)}`,cause:r}),this[E_]=!0,this.value=t}static isInstance(t){return Pt.hasMarker(t,x_)}static wrap({value:t,cause:r}){return zd.isInstance(r)&&r.value===t?r:new zd({value:t,cause:r})}};E_=N7;var Pa=q7,$_="AI_UnsupportedFunctionalityError",R_=`vercel.ai.error.${$_}`,L7=Symbol.for(R_),P_,M_=class extends Pt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:$_,message:t}),this[P_]=!0,this.functionality=e}static isInstance(e){return Pt.hasMarker(e,R_)}};P_=L7;function O_(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function ti(e){return Object.fromEntries([...e.headers])}var j7=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,i=new Array(t);for(let s=0;s<t;s++)i[s]=r[Math.random()*a|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new d_({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},ri=j7();function Vu(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var D7=["fetch failed","failed to fetch"];function U7({error:e,url:t,requestBodyValues:r}){if(Vu(e))return e;if(e instanceof TypeError&&D7.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new tn({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function z7(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function F7(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function A_(e,...t){const r=new Headers(F7(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var V7="3.0.18";function Z7({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ei({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ei({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ei({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ei({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var H7=/"__proto__"\s*:/,B7=/"constructor"\s*:/;function N_(e){const t=JSON.parse(e);return t===null||typeof t!="object"||H7.test(e)===!1&&B7.test(e)===!1?t:J7(t)}function J7(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const a=n[o];a&&typeof a=="object"&&t.push(a)}}}return e}function Zu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return N_(e)}try{return N_(e)}finally{Error.stackTraceLimit=t}}var Hu=Symbol.for("vercel.ai.validator");function G7(e){return{[Hu]:!0,validate:e}}function W7(e){return typeof e=="object"&&e!==null&&Hu in e&&e[Hu]===!0&&"validate"in e}function K7(e){return W7(e)?e:typeof e=="function"?e():Y7(e)}function Y7(e){return G7(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Pa({value:t,cause:r.issues})}})}async function Q7({value:e,schema:t}){const r=await Ma({value:e,schema:t});if(!r.success)throw Pa.wrap({value:e,cause:r.error});return r.value}async function Ma({value:e,schema:t}){const r=K7(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:Pa.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Pa.wrap({value:e,cause:n}),rawValue:e}}}async function X7({text:e,schema:t}){try{const r=Zu(e);return t==null?r:Q7({value:r,schema:t})}catch(r){throw Xs.isInstance(r)||Pa.isInstance(r)?r:new Xs({text:e,cause:r})}}async function q_({text:e,schema:t}){try{const r=Zu(e);return t==null?{success:!0,value:r,rawValue:r}:await Ma({value:r,schema:t})}catch(r){return{success:!1,error:Xs.isInstance(r)?r:new Xs({text:e,cause:r}),rawValue:void 0}}}function L_(e){try{return Zu(e),!0}catch{return!1}}function eE({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await q_({text:r,schema:t}))}}))}async function j_({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ma({value:t[e],schema:r});if(!n.success)throw new d_({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var tE=()=>globalThis.fetch,D_=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>rE({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),rE=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=tE()})=>{try{const s=await i(e,{method:"POST",headers:A_(t,`ai-sdk/provider-utils/${V7}`,z7()),body:r.content,signal:a}),l=ti(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:r.values})}catch(u){throw Vu(u)||tn.isInstance(u)?u:new tn({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Vu(c)||tn.isInstance(c))?c:new tn({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw U7({error:s,url:e,requestBodyValues:r.values})}},nE=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const i=await n.text(),s=ti(n);if(i.trim()==="")return{responseHeaders:s,value:new tn({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{const l=await X7({text:i,schema:e});return{responseHeaders:s,value:new tn({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new tn({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},oE=e=>async({response:t})=>{const r=ti(t);if(t.body==null)throw new $7({});return{responseHeaders:r,value:eE({stream:t.body,schema:e})}},aE=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),a=await q_({text:o,schema:e}),i=ti(t);if(!a.success)throw new tn({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:sE}=globalThis;function iE(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return sE(t)}function lE(e){return e instanceof Uint8Array?iE(e):e}function cE(e){return e?.replace(/\/$/,"")}function Oa(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function uE(e){const t=[];for(const{role:r,content:n,...o}of e){const a=Oa({...o});switch(r){case"system":{t.push({role:"system",content:n,...a});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Oa(n[0])});break}t.push({role:"user",content:n.map(i=>{const s=Oa(i);switch(i.type){case"text":return{type:"text",text:i.text,...s};case"file":if(i.mediaType.startsWith("image/")){const l=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${l};base64,${lE(i.data)}`},...s}}else throw new M_({functionality:`file part media type ${i.mediaType}`})}}),...a});break}case"assistant":{let i="";const s=[];for(const l of n){const c=Oa(l);switch(l.type){case"text":{i+=l.text;break}case"tool-call":{s.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:i,tool_calls:s.length>0?s:void 0,...a});break}case"tool":{for(const i of n){const s=i.output;let l;switch(s.type){case"text":case"error-text":l=s.value;break;case"content":case"json":case"error-json":l=JSON.stringify(s.value);break}const c=Oa(i);t.push({role:"tool",tool_call_id:i.toolCallId,content:l,...c})}break}default:{const i=r;throw new Error(`Unsupported role: ${i}`)}}}return t}function U_({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function z_(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Bu=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),dE=T({error:T({message:d(),type:d().nullish(),param:ut().nullish(),code:ae([d(),q()]).nullish()})}),pE={errorSchema:dE,errorToMessage:e=>e.error.message};function hE({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const a of e)a.type==="provider-defined"?r.push({type:"unsupported-tool",tool:a}):n.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const a=o;throw new M_({functionality:`tool choice type: ${a}`})}}}var fE=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:pE;this.chunkSchema=gE(o.errorSchema),this.failedResponseHandler=nE(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,providerOptions:s,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:p}){var m,f,b,w;const C=[],v=Object.assign((m=await j_({provider:"openai-compatible",providerOptions:s,schema:Bu}))!=null?m:{},(f=await j_({provider:this.providerOptionsName,providerOptions:s,schema:Bu}))!=null?f:{});o!=null&&C.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&C.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:g,toolChoice:I,toolWarnings:y}=hE({tools:p,toolChoice:h});return{args:{model:this.modelId,user:v.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(b=c.name)!=null?b:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((w=s?.[this.providerOptionsName])!=null?w:{}).filter(([_])=>!Object.keys(Bu.shape).includes(_))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:uE(e),tools:g,tool_choice:I},warnings:[...C,...y]}}async doGenerate(e){var t,r,n,o,a,i,s,l,c,u,h,p,m,f,b,w,C;const{args:v,warnings:g}=await this.getArgs({...e}),I=JSON.stringify(v),{responseHeaders:y,value:_,rawValue:k}=await D_({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:O_(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:aE(mE),abortSignal:e.abortSignal,fetch:this.config.fetch}),S=_.choices[0],E=[],R=S.message.content;R!=null&&R.length>0&&E.push({type:"text",text:R});const x=(t=S.message.reasoning_content)!=null?t:S.message.reasoning;if(x!=null&&x.length>0&&E.push({type:"reasoning",text:x}),S.message.tool_calls!=null)for(const z of S.message.tool_calls)E.push({type:"tool-call",toolCallId:(r=z.id)!=null?r:ri(),toolName:z.function.name,input:z.function.arguments});const N={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:k}))},U=(a=_.usage)==null?void 0:a.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(N[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(N[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:E,finishReason:z_(S.finish_reason),usage:{inputTokens:(s=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?s:void 0,outputTokens:(c=(l=_.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=_.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(f=(m=(p=_.usage)==null?void 0:p.completion_tokens_details)==null?void 0:m.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(C=(w=(b=_.usage)==null?void 0:b.prompt_tokens_details)==null?void 0:w.cached_tokens)!=null?C:void 0},providerMetadata:N,request:{body:I},response:{...U_(_),headers:y,body:k},warnings:g}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},a=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:i,value:s}=await D_({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:O_(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:oE(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const p=this.providerOptionsName;let m=!1,f=!1;return{stream:s.pipeThrough(new TransformStream({start(b){b.enqueue({type:"stream-start",warnings:n})},transform(b,w){var C,v,g,I,y,_,k,S,E,R,x,N,U;if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){c="error",w.enqueue({type:"error",error:b.error});return}const z=b.value;if(a?.processChunk(b.rawValue),"error"in z){c="error",w.enqueue({type:"error",error:z.error.message});return}if(h&&(h=!1,w.enqueue({type:"response-metadata",...U_(z)})),z.usage!=null){const{prompt_tokens:re,completion_tokens:Se,total_tokens:H,prompt_tokens_details:D,completion_tokens_details:B}=z.usage;u.promptTokens=re??void 0,u.completionTokens=Se??void 0,u.totalTokens=H??void 0,B?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=B?.rejected_prediction_tokens),D?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=D?.cached_tokens)}const ee=z.choices[0];if(ee?.finish_reason!=null&&(c=z_(ee.finish_reason)),ee?.delta==null)return;const Q=ee.delta,se=(C=Q.reasoning_content)!=null?C:Q.reasoning;if(se&&(m||(w.enqueue({type:"reasoning-start",id:"reasoning-0"}),m=!0),w.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:se})),Q.content&&(f||(w.enqueue({type:"text-start",id:"txt-0"}),f=!0),w.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const re of Q.tool_calls){const Se=re.index;if(l[Se]==null){if(re.id==null)throw new m_({data:re,message:"Expected 'id' to be a string."});if(((v=re.function)==null?void 0:v.name)==null)throw new m_({data:re,message:"Expected 'function.name' to be a string."});w.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[Se]={id:re.id,type:"function",function:{name:re.function.name,arguments:(g=re.function.arguments)!=null?g:""},hasFinished:!1};const D=l[Se];((I=D.function)==null?void 0:I.name)!=null&&((y=D.function)==null?void 0:y.arguments)!=null&&(D.function.arguments.length>0&&w.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),L_(D.function.arguments)&&(w.enqueue({type:"tool-input-end",id:D.id}),w.enqueue({type:"tool-call",toolCallId:(_=D.id)!=null?_:ri(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0));continue}const H=l[Se];H.hasFinished||(((k=re.function)==null?void 0:k.arguments)!=null&&(H.function.arguments+=(E=(S=re.function)==null?void 0:S.arguments)!=null?E:""),w.enqueue({type:"tool-input-delta",id:H.id,delta:(R=re.function.arguments)!=null?R:""}),((x=H.function)==null?void 0:x.name)!=null&&((N=H.function)==null?void 0:N.arguments)!=null&&L_(H.function.arguments)&&(w.enqueue({type:"tool-input-end",id:H.id}),w.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:ri(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(b){var w,C,v,g,I,y;m&&b.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&b.enqueue({type:"text-end",id:"txt-0"});for(const k of l.filter(S=>!S.hasFinished))b.enqueue({type:"tool-input-end",id:k.id}),b.enqueue({type:"tool-call",toolCallId:(w=k.id)!=null?w:ri(),toolName:k.function.name,input:k.function.arguments});const _={[p]:{},...a?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(_[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(_[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),b.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(C=u.promptTokens)!=null?C:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(I=u.completionTokensDetails.reasoningTokens)!=null?I:void 0,cachedInputTokens:(y=u.promptTokensDetails.cachedTokens)!=null?y:void 0},providerMetadata:_})}})),request:{body:o},response:{headers:i}}}},F_=T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish(),mE=T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({message:T({role:M("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:L(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:F_}),gE=e=>ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({delta:T({role:le(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:L(T({index:q(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:F_}),e]);T({echo:_e().optional(),logitBias:pe(d(),q()).optional(),suffix:d().optional(),user:d().optional()});var _E=T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()});T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d()})),usage:_E.nullish()}),T({dimensions:q().optional(),user:d().optional()}),T({data:L(T({embedding:L(q())})),usage:T({prompt_tokens:q()}).nullish(),providerMetadata:pe(d(),pe(d(),ut())).optional()}),T({data:L(T({b64_json:d()}))});var V_=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},yE={extractMetadata:async({parsedBody:e})=>{const t=await Ma({value:e,schema:vE});return!t.success||t.value.usage==null?void 0:V_(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ma({value:t,schema:wE});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>V_(e)}}},Z_=T({prompt_cache_hit_tokens:q().nullish(),prompt_cache_miss_tokens:q().nullish()}),vE=T({usage:Z_.nullish()}),wE=T({choices:L(T({finish_reason:d().nullish()})).nullish(),usage:Z_.nullish()}),bE="1.0.30";function H_(e={}){var t;const r=cE((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>A_({Authorization:`Bearer ${Z7({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${bE}`);class o extends fE{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const a=s=>new o(s,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:yE}),i=s=>a(s);return i.languageModel=a,i.chat=a,i.textEmbeddingModel=s=>{throw new S_({modelId:s,modelType:"textEmbeddingModel"})},i.imageModel=s=>{throw new S_({modelId:s,modelType:"imageModel"})},i}H_();const kE=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},TE=(e,t,r,n)=>{const o=(a,i,s)=>{if(a.type===e&&a.direction===r){const{data:l}=a;t(l,i,s),s(i)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class CE{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=TE("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Wn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->bg")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");let n;if(chrome.sessionRegistry){const o=chrome.sessionRegistry.get(this.targetSessionId);o&&o.tabIds.length>0&&(n=o.tabIds[o.tabIds.length-1])}n==null&&(n=await chrome.runtime.sendMessage({type:"get-session-tab-id",sessionId:this.targetSessionId})),this._throwError(()=>n==null,`【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`),kE("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:t},"bg->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}function ni(e){return!!e._zod}function bn(e,t){return ni(e)?Dp(e,t):e.safeParse(t)}function B_(e){if(!e)return;let t;if(ni(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function SE(e){if(ni(e)){const a=e._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}function eo(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J_(e){const r=B_(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=SE(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function G_(e,t){const r=bn(e,t);if(!r.success)throw r.error;return r.data}const IE=6e4;class xE{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Fc,r=>{this._oncancel(r)}),this.setNotificationHandler(Zc,r=>{this._onprogress(r)}),this.setRequestHandler(Vc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Hc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce($e.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Jc,async(r,n)=>{const o=async()=>{const a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){const l=s.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(l);else{const h=l,p=new Ce(h.error.code,h.error.message,h.error.data);u(p)}else{const h=s.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new Ce($e.InvalidParams,`Task not found: ${a}`);if(!eo(i.status))return await this._waitForTaskUpdate(a,n.signal),await o();if(eo(i.status)){const s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[Gn]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(Gc,async(r,n)=>{try{const{tasks:o,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:a,_meta:{}}}catch(o){throw new Ce($e.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Kc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce($e.InvalidParams,`Task not found: ${r.params.taskId}`);if(eo(o.status))throw new Ce($e.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Ce($e.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(o){throw o instanceof Ce?o:new Ce($e.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Ce.fromError($e.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};const o=this._transport?.onmessage;this._transport.onmessage=(a,i)=>{o?.(a,i),ya(a)||NS(a)?this._onresponse(a):Dc(a)?this._onrequest(a,i):AS(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=Ce.fromError($e.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,a=t.params?._meta?.[Gn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:$e.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const s=OS(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const h={relatedRequestId:t.id};a&&(h.relatedTask={taskId:a}),await this.notification(u,h)},sendRequest:async(u,h,p)=>{const m={...p,relatedRequestId:t.id};a&&!m.relatedTask&&(m.relatedTask={taskId:a});const f=m.relatedTask?.taskId??a;return f&&l&&await l.updateTaskStatus(f,"input_required"),await this.request(u,h,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:t.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async u=>{if(i.signal.aborted)return;const h={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:$e.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),a=this._progressHandlers.get(o);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}a(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ya(t))n(t);else{const i=new Ce(t.error.code,t.error.message,t.error.data);n(i)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(ya(t)&&t.result&&typeof t.result=="object"){const i=t.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),ya(t))o(t);else{const i=Ce.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof Ce?i:new Ce($e.InternalError,String(i))}}return}let a;try{const i=await this.request(t,Ta,n);if(i.task)a=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ce($e.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},eo(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new Ce($e.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Ce($e.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}const l=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ce?i:new Ce($e.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i,task:s,relatedTask:l}=n??{};return new Promise((c,u)=>{const h=v=>{u(v)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){h(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),l&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Gn]:l}});const f=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const g=v instanceof Ce?v:new Ce($e.RequestTimeout,String(v));u(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const g=bn(r,v.result);g.success?c(g.data):u(g.error)}catch(g){u(g)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});const b=n?.timeout??IE,w=()=>f(Ce.fromError($e.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(p,b,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);const C=l?.taskId;if(C){const v=g=>{const I=this._responseHandlers.get(p);I?I(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(C,{type:"request",message:m,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),u(g)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Bc,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Wc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},QS,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gn]:r.relatedTask}}}),this._transport?.send(s,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Gn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=J_(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,a)=>{const i=G_(t,o);return Promise.resolve(r(i,a))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=J_(t);this._notificationHandlers.set(n,o=>{const a=G_(t,o);return Promise.resolve(r(a))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&Dc(o.message)){const a=o.message.id,i=this._requestResolvers.get(a);i?(i(new Ce($e.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,a)=>{if(r.aborted){a(new Ce($e.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),a(new Ce($e.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const a=await n.getTask(o,r);if(!a)throw new Ce($e.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(o,a,i)=>{await n.storeTaskResult(o,a,i,r);const s=await n.getTask(o,r);if(s){const l=Us.parse({method:"notifications/tasks/status",params:s});await this.notification(l),eo(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,a,i)=>{const s=await n.getTask(o,r);if(!s)throw new Ce($e.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(eo(s.status))throw new Ce($e.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,a,i,r);const l=await n.getTask(o,r);if(l){const c=Us.parse({method:"notifications/tasks/status",params:l});await this.notification(c),eo(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function W_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function EE(e,t){const r={...e};for(const n in t){const o=n,a=t[o];if(a===void 0)continue;const i=r[o];W_(i)&&W_(a)?r[o]={...i,...a}:r[o]=a}return r}var oi={exports:{}},Ju={},rn={},to={},Gu={},Wu={},Ku={},K_;function ai(){return K_||(K_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((g,I)=>`${g}${I}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((g,I)=>(I instanceof r&&(g[I.str]=(g[I.str]||0)+1),g),{})}}e._Code=n,e.nil=new n("");function o(C,...v){const g=[C[0]];let I=0;for(;I<v.length;)s(g,v[I]),g.push(C[++I]);return new n(g)}e._=o;const a=new n("+");function i(C,...v){const g=[m(C[0])];let I=0;for(;I<v.length;)g.push(a),s(g,v[I]),g.push(a,m(C[++I]));return l(g),new n(g)}e.str=i;function s(C,v){v instanceof n?C.push(...v._items):v instanceof r?C.push(v):C.push(h(v))}e.addCodeArg=s;function l(C){let v=1;for(;v<C.length-1;){if(C[v]===a){const g=c(C[v-1],C[v+1]);if(g!==void 0){C.splice(v-1,3,g);continue}C[v++]="+"}v++}}function c(C,v){if(v==='""')return C;if(C==='""')return v;if(typeof C=="string")return v instanceof r||C[C.length-1]!=='"'?void 0:typeof v!="string"?`${C.slice(0,-1)}${v}"`:v[0]==='"'?C.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(C instanceof r))return`"${C}${v.slice(1)}`}function u(C,v){return v.emptyStr()?C:C.emptyStr()?v:i`${C}${v}`}e.strConcat=u;function h(C){return typeof C=="number"||typeof C=="boolean"||C===null?C:m(Array.isArray(C)?C.join(","):C)}function p(C){return new n(m(C))}e.stringify=p;function m(C){return JSON.stringify(C).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function f(C){return typeof C=="string"&&e.IDENTIFIER.test(C)?new n(`.${C}`):o`[${C}]`}e.getProperty=f;function b(C){if(typeof C=="string"&&e.IDENTIFIER.test(C))return new n(`${C}`);throw new Error(`CodeGen: invalid export name: ${C}, use explicit $id name mapping`)}e.getEsmExportName=b;function w(C){return new n(C.toString())}e.regexpCode=w})(Ku)),Ku}var Yu={},Y_;function Q_(){return Y_||(Y_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ai();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class a extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${h}]`}}e.ValueScopeName=a;const i=(0,t._)`\n`;class s extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i:t.nil}}get(){return this._scope}name(c){return new a(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:m}=p,f=(h=u.key)!==null&&h!==void 0?h:u.ref;let b=this._values[m];if(b){const v=b.get(f);if(v)return v}else b=this._values[m]=new Map;b.set(f,p);const w=this._scope[m]||(this._scope[m]=[]),C=w.length;return w[C]=u.ref,p.setValue(u,{property:m,itemIndex:C}),p}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,t._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,h)}_reduceValues(c,u,h={},p){let m=t.nil;for(const f in c){const b=c[f];if(!b)continue;const w=h[f]=h[f]||new Map;b.forEach(C=>{if(w.has(C))return;w.set(C,n.Started);let v=u(C);if(v){const g=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${g} ${C} = ${v};${this.opts._n}`}else if(v=p?.(C))m=(0,t._)`${m}${v}${this.opts._n}`;else throw new r(C);w.set(C,n.Completed)})}return m}}e.ValueScope=s})(Yu)),Yu}var X_;function Oe(){return X_||(X_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=ai(),r=Q_();var n=ai();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=Q_();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class a{optimizeNodes(){return this}optimizeNames($,O){return this}}class i extends a{constructor($,O,j){super(),this.varKind=$,this.name=O,this.rhs=j}render({es5:$,_n:O}){const j=$?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${j} ${this.name}${G};`+O}optimizeNames($,O){if($[this.name.str])return this.rhs&&(this.rhs=z(this.rhs,$,O)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends a{constructor($,O,j){super(),this.lhs=$,this.rhs=O,this.sideEffects=j}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,O){if(!(this.lhs instanceof t.Name&&!$[this.lhs.str]&&!this.sideEffects))return this.rhs=z(this.rhs,$,O),this}get names(){const $=this.lhs instanceof t.Name?{}:{...this.lhs.names};return U($,this.rhs)}}class l extends s{constructor($,O,j,G){super($,j,G),this.op=O}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class c extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class u extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class h extends a{constructor($){super(),this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class p extends a{constructor($){super(),this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,O){return this.code=z(this.code,$,O),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends a{constructor($=[]){super(),this.nodes=$}render($){return this.nodes.reduce((O,j)=>O+j.render($),"")}optimizeNodes(){const{nodes:$}=this;let O=$.length;for(;O--;){const j=$[O].optimizeNodes();Array.isArray(j)?$.splice(O,1,...j):j?$[O]=j:$.splice(O,1)}return $.length>0?this:void 0}optimizeNames($,O){const{nodes:j}=this;let G=j.length;for(;G--;){const Y=j[G];Y.optimizeNames($,O)||(ee($,Y.names),j.splice(G,1))}return j.length>0?this:void 0}get names(){return this.nodes.reduce(($,O)=>N($,O.names),{})}}class f extends m{render($){return"{"+$._n+super.render($)+"}"+$._n}}class b extends m{}class w extends f{}w.kind="else";class C extends f{constructor($,O){super(O),this.condition=$}render($){let O=`if(${this.condition})`+super.render($);return this.else&&(O+="else "+this.else.render($)),O}optimizeNodes(){super.optimizeNodes();const $=this.condition;if($===!0)return this.nodes;let O=this.else;if(O){const j=O.optimizeNodes();O=this.else=Array.isArray(j)?new w(j):j}if(O)return $===!1?O instanceof C?O:O.nodes:this.nodes.length?this:new C(Q($),O instanceof C?[O]:O.nodes);if(!($===!1||!this.nodes.length))return this}optimizeNames($,O){var j;if(this.else=(j=this.else)===null||j===void 0?void 0:j.optimizeNames($,O),!!(super.optimizeNames($,O)||this.else))return this.condition=z(this.condition,$,O),this}get names(){const $=super.names;return U($,this.condition),this.else&&N($,this.else.names),$}}C.kind="if";class v extends f{}v.kind="for";class g extends v{constructor($){super(),this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,O){if(super.optimizeNames($,O))return this.iteration=z(this.iteration,$,O),this}get names(){return N(super.names,this.iteration.names)}}class I extends v{constructor($,O,j,G){super(),this.varKind=$,this.name=O,this.from=j,this.to=G}render($){const O=$.es5?r.varKinds.var:this.varKind,{name:j,from:G,to:Y}=this;return`for(${O} ${j}=${G}; ${j}<${Y}; ${j}++)`+super.render($)}get names(){const $=U(super.names,this.from);return U($,this.to)}}class y extends v{constructor($,O,j,G){super(),this.loop=$,this.varKind=O,this.name=j,this.iterable=G}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,O){if(super.optimizeNames($,O))return this.iterable=z(this.iterable,$,O),this}get names(){return N(super.names,this.iterable.names)}}class _ extends f{constructor($,O,j){super(),this.name=$,this.args=O,this.async=j}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}_.kind="func";class k extends m{render($){return"return "+super.render($)}}k.kind="return";class S extends f{render($){let O="try"+super.render($);return this.catch&&(O+=this.catch.render($)),this.finally&&(O+=this.finally.render($)),O}optimizeNodes(){var $,O;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(O=this.finally)===null||O===void 0||O.optimizeNodes(),this}optimizeNames($,O){var j,G;return super.optimizeNames($,O),(j=this.catch)===null||j===void 0||j.optimizeNames($,O),(G=this.finally)===null||G===void 0||G.optimizeNames($,O),this}get names(){const $=super.names;return this.catch&&N($,this.catch.names),this.finally&&N($,this.finally.names),$}}class E extends f{constructor($){super(),this.error=$}render($){return`catch(${this.error})`+super.render($)}}E.kind="catch";class R extends f{render($){return"finally"+super.render($)}}R.kind="finally";class x{constructor($,O={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...O,_n:O.lines?`
|
|
89
|
-
`:""},this._extScope=$,this._scope=new r.Scope({parent:$}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,O){const j=this._extScope.value($,O);return(this._values[j.prefix]||(this._values[j.prefix]=new Set)).add(j),j}getScopeValue($,O){return this._extScope.getValue($,O)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,O,j,G){const Y=this._scope.toName(O);return j!==void 0&&G&&(this._constants[Y.str]=j),this._leafNode(new i($,Y,j)),Y}const($,O,j){return this._def(r.varKinds.const,$,O,j)}let($,O,j){return this._def(r.varKinds.let,$,O,j)}var($,O,j){return this._def(r.varKinds.var,$,O,j)}assign($,O,j){return this._leafNode(new s($,O,j))}add($,O){return this._leafNode(new l($,e.operators.ADD,O))}code($){return typeof $=="function"?$():$!==t.nil&&this._leafNode(new p($)),this}object(...$){const O=["{"];for(const[j,G]of $)O.length>1&&O.push(","),O.push(j),(j!==G||this.opts.es5)&&(O.push(":"),(0,t.addCodeArg)(O,G));return O.push("}"),new t._Code(O)}if($,O,j){if(this._blockNode(new C($)),O&&j)this.code(O).else().code(j).endIf();else if(O)this.code(O).endIf();else if(j)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new C($))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(C,w)}_for($,O){return this._blockNode($),O&&this.code(O).endFor(),this}for($,O){return this._for(new g($),O)}forRange($,O,j,G,Y=this.opts.es5?r.varKinds.var:r.varKinds.let){const W=this._scope.toName($);return this._for(new I(Y,W,O,j),()=>G(W))}forOf($,O,j,G=r.varKinds.const){const Y=this._scope.toName($);if(this.opts.es5){const W=O instanceof t.Name?O:this.var("_arr",O);return this.forRange("_i",0,(0,t._)`${W}.length`,V=>{this.var(Y,(0,t._)`${W}[${V}]`),j(Y)})}return this._for(new y("of",G,Y,O),()=>j(Y))}forIn($,O,j,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,t._)`Object.keys(${O})`,j);const Y=this._scope.toName($);return this._for(new y("in",G,Y,O),()=>j(Y))}endFor(){return this._endBlockNode(v)}label($){return this._leafNode(new c($))}break($){return this._leafNode(new u($))}return($){const O=new k;if(this._blockNode(O),this.code($),O.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try($,O,j){if(!O&&!j)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new S;if(this._blockNode(G),this.code($),O){const Y=this.name("e");this._currNode=G.catch=new E(Y),O(Y)}return j&&(this._currNode=G.finally=new R,this.code(j)),this._endBlockNode(E,R)}throw($){return this._leafNode(new h($))}block($,O){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(O),this}endBlock($){const O=this._blockStarts.pop();if(O===void 0)throw new Error("CodeGen: not in self-balancing block");const j=this._nodes.length-O;if(j<0||$!==void 0&&j!==$)throw new Error(`CodeGen: wrong number of nodes: ${j} vs ${$} expected`);return this._nodes.length=O,this}func($,O=t.nil,j,G){return this._blockNode(new _($,O,j)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(_)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,O){const j=this._currNode;if(j instanceof $||O&&j instanceof O)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${O?`${$.kind}/${O.kind}`:$.kind}"`)}_elseNode($){const O=this._currNode;if(!(O instanceof C))throw new Error('CodeGen: "else" without "if"');return this._currNode=O.else=$,this}get _root(){return this._nodes[0]}get _currNode(){const $=this._nodes;return $[$.length-1]}set _currNode($){const O=this._nodes;O[O.length-1]=$}}e.CodeGen=x;function N(F,$){for(const O in $)F[O]=(F[O]||0)+($[O]||0);return F}function U(F,$){return $ instanceof t._CodeOrName?N(F,$.names):F}function z(F,$,O){if(F instanceof t.Name)return j(F);if(!G(F))return F;return new t._Code(F._items.reduce((Y,W)=>(W instanceof t.Name&&(W=j(W)),W instanceof t._Code?Y.push(...W._items):Y.push(W),Y),[]));function j(Y){const W=O[Y.str];return W===void 0||$[Y.str]!==1?Y:(delete $[Y.str],W)}function G(Y){return Y instanceof t._Code&&Y._items.some(W=>W instanceof t.Name&&$[W.str]===1&&O[W.str]!==void 0)}}function ee(F,$){for(const O in $)F[O]=(F[O]||0)-($[O]||0)}function Q(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${B(F)}`}e.not=Q;const se=D(e.operators.AND);function re(...F){return F.reduce(se)}e.and=re;const Se=D(e.operators.OR);function H(...F){return F.reduce(Se)}e.or=H;function D(F){return($,O)=>$===t.nil?O:O===t.nil?$:(0,t._)`${B($)} ${F} ${B(O)}`}function B(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Wu)),Wu}var Ae={},ey;function Fe(){if(ey)return Ae;ey=1,Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.checkStrictMode=Ae.getErrorPath=Ae.Type=Ae.useFunc=Ae.setEvaluated=Ae.evaluatedPropsToName=Ae.mergeEvaluated=Ae.eachItem=Ae.unescapeJsonPointer=Ae.escapeJsonPointer=Ae.escapeFragment=Ae.unescapeFragment=Ae.schemaRefOrVal=Ae.schemaHasRulesButRef=Ae.schemaHasRules=Ae.checkUnknownRules=Ae.alwaysValidSchema=Ae.toHash=void 0;const e=Oe(),t=ai();function r(y){const _={};for(const k of y)_[k]=!0;return _}Ae.toHash=r;function n(y,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(o(y,_),!a(_,y.self.RULES.all))}Ae.alwaysValidSchema=n;function o(y,_=y.schema){const{opts:k,self:S}=y;if(!k.strictSchema||typeof _=="boolean")return;const E=S.RULES.keywords;for(const R in _)E[R]||I(y,`unknown keyword: "${R}"`)}Ae.checkUnknownRules=o;function a(y,_){if(typeof y=="boolean")return!y;for(const k in y)if(_[k])return!0;return!1}Ae.schemaHasRules=a;function i(y,_){if(typeof y=="boolean")return!y;for(const k in y)if(k!=="$ref"&&_.all[k])return!0;return!1}Ae.schemaHasRulesButRef=i;function s({topSchemaRef:y,schemaPath:_},k,S,E){if(!E){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${y}${_}${(0,e.getProperty)(S)}`}Ae.schemaRefOrVal=s;function l(y){return h(decodeURIComponent(y))}Ae.unescapeFragment=l;function c(y){return encodeURIComponent(u(y))}Ae.escapeFragment=c;function u(y){return typeof y=="number"?`${y}`:y.replace(/~/g,"~0").replace(/\//g,"~1")}Ae.escapeJsonPointer=u;function h(y){return y.replace(/~1/g,"/").replace(/~0/g,"~")}Ae.unescapeJsonPointer=h;function p(y,_){if(Array.isArray(y))for(const k of y)_(k);else _(y)}Ae.eachItem=p;function m({mergeNames:y,mergeToName:_,mergeValues:k,resultToName:S}){return(E,R,x,N)=>{const U=x===void 0?R:x instanceof e.Name?(R instanceof e.Name?y(E,R,x):_(E,R,x),x):R instanceof e.Name?(_(E,x,R),R):k(R,x);return N===e.Name&&!(U instanceof e.Name)?S(E,U):U}}Ae.mergeEvaluated={props:m({mergeNames:(y,_,k)=>y.if((0,e._)`${k} !== true && ${_} !== undefined`,()=>{y.if((0,e._)`${_} === true`,()=>y.assign(k,!0),()=>y.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${_})`))}),mergeToName:(y,_,k)=>y.if((0,e._)`${k} !== true`,()=>{_===!0?y.assign(k,!0):(y.assign(k,(0,e._)`${k} || {}`),b(y,k,_))}),mergeValues:(y,_)=>y===!0?!0:{...y,..._},resultToName:f}),items:m({mergeNames:(y,_,k)=>y.if((0,e._)`${k} !== true && ${_} !== undefined`,()=>y.assign(k,(0,e._)`${_} === true ? true : ${k} > ${_} ? ${k} : ${_}`)),mergeToName:(y,_,k)=>y.if((0,e._)`${k} !== true`,()=>y.assign(k,_===!0?!0:(0,e._)`${k} > ${_} ? ${k} : ${_}`)),mergeValues:(y,_)=>y===!0?!0:Math.max(y,_),resultToName:(y,_)=>y.var("items",_)})};function f(y,_){if(_===!0)return y.var("props",!0);const k=y.var("props",(0,e._)`{}`);return _!==void 0&&b(y,k,_),k}Ae.evaluatedPropsToName=f;function b(y,_,k){Object.keys(k).forEach(S=>y.assign((0,e._)`${_}${(0,e.getProperty)(S)}`,!0))}Ae.setEvaluated=b;const w={};function C(y,_){return y.scopeValue("func",{ref:_,code:w[_.code]||(w[_.code]=new t._Code(_.code))})}Ae.useFunc=C;var v;(function(y){y[y.Num=0]="Num",y[y.Str=1]="Str"})(v||(Ae.Type=v={}));function g(y,_,k){if(y instanceof e.Name){const S=_===v.Num;return k?S?(0,e._)`"[" + ${y} + "]"`:(0,e._)`"['" + ${y} + "']"`:S?(0,e._)`"/" + ${y}`:(0,e._)`"/" + ${y}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(y).toString():"/"+u(y)}Ae.getErrorPath=g;function I(y,_,k=y.opts.strictSchema){if(k){if(_=`strict mode: ${_}`,k===!0)throw new Error(_);y.self.logger.warn(_)}}return Ae.checkStrictMode=I,Ae}var si={},ty;function kn(){if(ty)return si;ty=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Oe(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return si.default=t,si}var ry;function ii(){return ry||(ry=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Oe(),r=Fe(),n=kn();e.keywordError={message:({keyword:w})=>(0,t.str)`must pass "${w}" keyword validation`},e.keyword$DataError={message:({keyword:w,schemaType:C})=>C?(0,t.str)`"${w}" keyword must be ${C} ($data)`:(0,t.str)`"${w}" keyword is invalid ($data)`};function o(w,C=e.keywordError,v,g){const{it:I}=w,{gen:y,compositeRule:_,allErrors:k}=I,S=h(w,C,v);g??(_||k)?l(y,S):c(I,(0,t._)`[${S}]`)}e.reportError=o;function a(w,C=e.keywordError,v){const{it:g}=w,{gen:I,compositeRule:y,allErrors:_}=g,k=h(w,C,v);l(I,k),y||_||c(g,n.default.vErrors)}e.reportExtraError=a;function i(w,C){w.assign(n.default.errors,C),w.if((0,t._)`${n.default.vErrors} !== null`,()=>w.if(C,()=>w.assign((0,t._)`${n.default.vErrors}.length`,C),()=>w.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function s({gen:w,keyword:C,schemaValue:v,data:g,errsCount:I,it:y}){if(I===void 0)throw new Error("ajv implementation error");const _=w.name("err");w.forRange("i",I,n.default.errors,k=>{w.const(_,(0,t._)`${n.default.vErrors}[${k}]`),w.if((0,t._)`${_}.instancePath === undefined`,()=>w.assign((0,t._)`${_}.instancePath`,(0,t.strConcat)(n.default.instancePath,y.errorPath))),w.assign((0,t._)`${_}.schemaPath`,(0,t.str)`${y.errSchemaPath}/${C}`),y.opts.verbose&&(w.assign((0,t._)`${_}.schema`,v),w.assign((0,t._)`${_}.data`,g))})}e.extendErrors=s;function l(w,C){const v=w.const("err",C);w.if((0,t._)`${n.default.vErrors} === null`,()=>w.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),w.code((0,t._)`${n.default.errors}++`)}function c(w,C){const{gen:v,validateName:g,schemaEnv:I}=w;I.$async?v.throw((0,t._)`new ${w.ValidationError}(${C})`):(v.assign((0,t._)`${g}.errors`,C),v.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(w,C,v){const{createErrors:g}=w.it;return g===!1?(0,t._)`{}`:p(w,C,v)}function p(w,C,v={}){const{gen:g,it:I}=w,y=[m(I,v),f(w,v)];return b(w,C,y),g.object(...y)}function m({errorPath:w},{instancePath:C}){const v=C?(0,t.str)`${w}${(0,r.getErrorPath)(C,r.Type.Str)}`:w;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function f({keyword:w,it:{errSchemaPath:C}},{schemaPath:v,parentSchema:g}){let I=g?C:(0,t.str)`${C}/${w}`;return v&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,I]}function b(w,{params:C,message:v},g){const{keyword:I,data:y,schemaValue:_,it:k}=w,{opts:S,propertyName:E,topSchemaRef:R,schemaPath:x}=k;g.push([u.keyword,I],[u.params,typeof C=="function"?C(w):C||(0,t._)`{}`]),S.messages&&g.push([u.message,typeof v=="function"?v(w):v]),S.verbose&&g.push([u.schema,_],[u.parentSchema,(0,t._)`${R}${x}`],[n.default.data,y]),E&&g.push([u.propertyName,E])}})(Gu)),Gu}var ny;function $E(){if(ny)return to;ny=1,Object.defineProperty(to,"__esModule",{value:!0}),to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;const e=ii(),t=Oe(),r=kn(),n={message:"boolean schema is false"};function o(s){const{gen:l,schema:c,validateName:u}=s;c===!1?i(s,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}to.topBoolOrEmptySchema=o;function a(s,l){const{gen:c,schema:u}=s;u===!1?(c.var(l,!1),i(s)):c.var(l,!0)}to.boolOrEmptySchema=a;function i(s,l){const{gen:c,data:u}=s,h={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(h,n,void 0,l)}return to}var Dt={},ro={},oy;function ay(){if(oy)return ro;oy=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.getRules=ro.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}ro.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return ro.getRules=n,ro}var nn={},sy;function iy(){if(sy)return nn;sy=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.shouldUseRule=nn.shouldUseGroup=nn.schemaHasRulesForType=void 0;function e({schema:n,self:o},a){const i=o.RULES.types[a];return i&&i!==!0&&t(n,i)}nn.schemaHasRulesForType=e;function t(n,o){return o.rules.some(a=>r(n,a))}nn.shouldUseGroup=t;function r(n,o){var a;return n[o.keyword]!==void 0||((a=o.definition.implements)===null||a===void 0?void 0:a.some(i=>n[i]!==void 0))}return nn.shouldUseRule=r,nn}var ly;function li(){if(ly)return Dt;ly=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.reportTypeError=Dt.checkDataTypes=Dt.checkDataType=Dt.coerceAndCheckDataType=Dt.getJSONTypes=Dt.getSchemaTypes=Dt.DataType=void 0;const e=ay(),t=iy(),r=ii(),n=Oe(),o=Fe();var a;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(a||(Dt.DataType=a={}));function i(v){const g=s(v.type);if(g.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&g.push("null")}return g}Dt.getSchemaTypes=i;function s(v){const g=Array.isArray(v)?v:v?[v]:[];if(g.every(e.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}Dt.getJSONTypes=s;function l(v,g){const{gen:I,data:y,opts:_}=v,k=u(g,_.coerceTypes),S=g.length>0&&!(k.length===0&&g.length===1&&(0,t.schemaHasRulesForType)(v,g[0]));if(S){const E=f(g,y,_.strictNumbers,a.Wrong);I.if(E,()=>{k.length?h(v,g,k):w(v)})}return S}Dt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,g){return g?v.filter(I=>c.has(I)||g==="array"&&I==="array"):[]}function h(v,g,I){const{gen:y,data:_,opts:k}=v,S=y.let("dataType",(0,n._)`typeof ${_}`),E=y.let("coerced",(0,n._)`undefined`);k.coerceTypes==="array"&&y.if((0,n._)`${S} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>y.assign(_,(0,n._)`${_}[0]`).assign(S,(0,n._)`typeof ${_}`).if(f(g,_,k.strictNumbers),()=>y.assign(E,_))),y.if((0,n._)`${E} !== undefined`);for(const x of I)(c.has(x)||x==="array"&&k.coerceTypes==="array")&&R(x);y.else(),w(v),y.endIf(),y.if((0,n._)`${E} !== undefined`,()=>{y.assign(_,E),p(v,E)});function R(x){switch(x){case"string":y.elseIf((0,n._)`${S} == "number" || ${S} == "boolean"`).assign(E,(0,n._)`"" + ${_}`).elseIf((0,n._)`${_} === null`).assign(E,(0,n._)`""`);return;case"number":y.elseIf((0,n._)`${S} == "boolean" || ${_} === null
|
|
90
|
-
|| (${S} == "string" && ${_} && ${_} == +${_})`).assign(E,(0,n._)`+${_}`);return;case"integer":y.elseIf((0,n._)`${S} === "boolean" || ${_} === null
|
|
91
|
-
|| (${S} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(E,(0,n._)`+${_}`);return;case"boolean":y.elseIf((0,n._)`${_} === "false" || ${_} === 0 || ${_} === null`).assign(E,!1).elseIf((0,n._)`${_} === "true" || ${_} === 1`).assign(E,!0);return;case"null":y.elseIf((0,n._)`${_} === "" || ${_} === 0 || ${_} === false`),y.assign(E,null);return;case"array":y.elseIf((0,n._)`${S} === "string" || ${S} === "number"
|
|
92
|
-
|| ${S} === "boolean" || ${_} === null`).assign(E,(0,n._)`[${_}]`)}}}function p({gen:v,parentData:g,parentDataProperty:I},y){v.if((0,n._)`${g} !== undefined`,()=>v.assign((0,n._)`${g}[${I}]`,y))}function m(v,g,I,y=a.Correct){const _=y===a.Correct?n.operators.EQ:n.operators.NEQ;let k;switch(v){case"null":return(0,n._)`${g} ${_} null`;case"array":k=(0,n._)`Array.isArray(${g})`;break;case"object":k=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":k=S((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":k=S();break;default:return(0,n._)`typeof ${g} ${_} ${v}`}return y===a.Correct?k:(0,n.not)(k);function S(E=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,E,I?(0,n._)`isFinite(${g})`:n.nil)}}Dt.checkDataType=m;function f(v,g,I,y){if(v.length===1)return m(v[0],g,I,y);let _;const k=(0,o.toHash)(v);if(k.array&&k.object){const S=(0,n._)`typeof ${g} != "object"`;_=k.null?S:(0,n._)`!${g} || ${S}`,delete k.null,delete k.array,delete k.object}else _=n.nil;k.number&&delete k.integer;for(const S in k)_=(0,n.and)(_,m(S,g,I,y));return _}Dt.checkDataTypes=f;const b={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:g})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${g}}`};function w(v){const g=C(v);(0,r.reportError)(g,b)}Dt.reportTypeError=w;function C(v){const{gen:g,data:I,schema:y}=v,_=(0,o.schemaRefOrVal)(v,y,"type");return{gen:g,keyword:"type",data:I,schema:y.type,schemaCode:_,schemaValue:_,parentSchema:y,params:{},it:v}}return Dt}var Aa={},cy;function RE(){if(cy)return Aa;cy=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.assignDefaults=void 0;const e=Oe(),t=Fe();function r(o,a){const{properties:i,items:s}=o.schema;if(a==="object"&&i)for(const l in i)n(o,l,i[l].default);else a==="array"&&Array.isArray(s)&&s.forEach((l,c)=>n(o,c,l.default))}Aa.assignDefaults=r;function n(o,a,i){const{gen:s,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const h=(0,e._)`${c}${(0,e.getProperty)(a)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${h}`);return}let p=(0,e._)`${h} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${h} === null || ${h} === ""`),s.if(p,(0,e._)`${h} = ${(0,e.stringify)(i)}`)}return Aa}var Pr={},Ge={},uy;function Mr(){if(uy)return Ge;uy=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.validateUnion=Ge.validateArray=Ge.usePattern=Ge.callValidateCode=Ge.schemaProperties=Ge.allSchemaProperties=Ge.noPropertyInData=Ge.propertyInData=Ge.isOwnProperty=Ge.hasPropFunc=Ge.reportMissingProp=Ge.checkMissingProp=Ge.checkReportMissingProp=void 0;const e=Oe(),t=Fe(),r=kn(),n=Fe();function o(v,g){const{gen:I,data:y,it:_}=v;I.if(u(I,y,g,_.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${g}`},!0),v.error()})}Ge.checkReportMissingProp=o;function a({gen:v,data:g,it:{opts:I}},y,_){return(0,e.or)(...y.map(k=>(0,e.and)(u(v,g,k,I.ownProperties),(0,e._)`${_} = ${k}`)))}Ge.checkMissingProp=a;function i(v,g){v.setParams({missingProperty:g},!0),v.error()}Ge.reportMissingProp=i;function s(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ge.hasPropFunc=s;function l(v,g,I){return(0,e._)`${s(v)}.call(${g}, ${I})`}Ge.isOwnProperty=l;function c(v,g,I,y){const _=(0,e._)`${g}${(0,e.getProperty)(I)} !== undefined`;return y?(0,e._)`${_} && ${l(v,g,I)}`:_}Ge.propertyInData=c;function u(v,g,I,y){const _=(0,e._)`${g}${(0,e.getProperty)(I)} === undefined`;return y?(0,e.or)(_,(0,e.not)(l(v,g,I))):_}Ge.noPropertyInData=u;function h(v){return v?Object.keys(v).filter(g=>g!=="__proto__"):[]}Ge.allSchemaProperties=h;function p(v,g){return h(g).filter(I=>!(0,t.alwaysValidSchema)(v,g[I]))}Ge.schemaProperties=p;function m({schemaCode:v,data:g,it:{gen:I,topSchemaRef:y,schemaPath:_,errorPath:k},it:S},E,R,x){const N=x?(0,e._)`${v}, ${g}, ${y}${_}`:g,U=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,k)],[r.default.parentData,S.parentData],[r.default.parentDataProperty,S.parentDataProperty],[r.default.rootData,r.default.rootData]];S.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const z=(0,e._)`${N}, ${I.object(...U)}`;return R!==e.nil?(0,e._)`${E}.call(${R}, ${z})`:(0,e._)`${E}(${z})`}Ge.callValidateCode=m;const f=(0,e._)`new RegExp`;function b({gen:v,it:{opts:g}},I){const y=g.unicodeRegExp?"u":"",{regExp:_}=g.code,k=_(I,y);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${_.code==="new RegExp"?f:(0,n.useFunc)(v,_)}(${I}, ${y})`})}Ge.usePattern=b;function w(v){const{gen:g,data:I,keyword:y,it:_}=v,k=g.name("valid");if(_.allErrors){const E=g.let("valid",!0);return S(()=>g.assign(E,!1)),E}return g.var(k,!0),S(()=>g.break()),k;function S(E){const R=g.const("len",(0,e._)`${I}.length`);g.forRange("i",0,R,x=>{v.subschema({keyword:y,dataProp:x,dataPropType:t.Type.Num},k),g.if((0,e.not)(k),E)})}}Ge.validateArray=w;function C(v){const{gen:g,schema:I,keyword:y,it:_}=v;if(!Array.isArray(I))throw new Error("ajv implementation error");if(I.some(R=>(0,t.alwaysValidSchema)(_,R))&&!_.opts.unevaluated)return;const S=g.let("valid",!1),E=g.name("_valid");g.block(()=>I.forEach((R,x)=>{const N=v.subschema({keyword:y,schemaProp:x,compositeRule:!0},E);g.assign(S,(0,e._)`${S} || ${E}`),v.mergeValidEvaluated(N,E)||g.if((0,e.not)(S))})),v.result(S,()=>v.reset(),()=>v.error(!0))}return Ge.validateUnion=C,Ge}var dy;function PE(){if(dy)return Pr;dy=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.validateKeywordUsage=Pr.validSchemaType=Pr.funcKeywordCode=Pr.macroKeywordCode=void 0;const e=Oe(),t=kn(),r=Mr(),n=ii();function o(p,m){const{gen:f,keyword:b,schema:w,parentSchema:C,it:v}=p,g=m.macro.call(v.self,w,C,v),I=c(f,b,g);v.opts.validateSchema!==!1&&v.self.validateSchema(g,!0);const y=f.name("valid");p.subschema({schema:g,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${b}`,topSchemaRef:I,compositeRule:!0},y),p.pass(y,()=>p.error(!0))}Pr.macroKeywordCode=o;function a(p,m){var f;const{gen:b,keyword:w,schema:C,parentSchema:v,$data:g,it:I}=p;l(I,m);const y=!g&&m.compile?m.compile.call(I.self,C,v,I):m.validate,_=c(b,w,y),k=b.let("valid");p.block$data(k,S),p.ok((f=m.valid)!==null&&f!==void 0?f:k);function S(){if(m.errors===!1)x(),m.modifying&&i(p),N(()=>p.error());else{const U=m.async?E():R();m.modifying&&i(p),N(()=>s(p,U))}}function E(){const U=b.let("ruleErrs",null);return b.try(()=>x((0,e._)`await `),z=>b.assign(k,!1).if((0,e._)`${z} instanceof ${I.ValidationError}`,()=>b.assign(U,(0,e._)`${z}.errors`),()=>b.throw(z))),U}function R(){const U=(0,e._)`${_}.errors`;return b.assign(U,null),x(e.nil),U}function x(U=m.async?(0,e._)`await `:e.nil){const z=I.opts.passContext?t.default.this:t.default.self,ee=!("compile"in m&&!g||m.schema===!1);b.assign(k,(0,e._)`${U}${(0,r.callValidateCode)(p,_,z,ee)}`,m.modifying)}function N(U){var z;b.if((0,e.not)((z=m.valid)!==null&&z!==void 0?z:k),U)}}Pr.funcKeywordCode=a;function i(p){const{gen:m,data:f,it:b}=p;m.if(b.parentData,()=>m.assign(f,(0,e._)`${b.parentData}[${b.parentDataProperty}]`))}function s(p,m){const{gen:f}=p;f.if((0,e._)`Array.isArray(${m})`,()=>{f.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${m} : ${t.default.vErrors}.concat(${m})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},m){if(m.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,m,f){if(f===void 0)throw new Error(`keyword "${m}" failed to compile`);return p.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,e.stringify)(f)})}function u(p,m,f=!1){return!m.length||m.some(b=>b==="array"?Array.isArray(p):b==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==b||f&&typeof p>"u")}Pr.validSchemaType=u;function h({schema:p,opts:m,self:f,errSchemaPath:b},w,C){if(Array.isArray(w.keyword)?!w.keyword.includes(C):w.keyword!==C)throw new Error("ajv implementation error");const v=w.dependencies;if(v?.some(g=>!Object.prototype.hasOwnProperty.call(p,g)))throw new Error(`parent schema must have dependencies of ${C}: ${v.join(",")}`);if(w.validateSchema&&!w.validateSchema(p[C])){const I=`keyword "${C}" value is invalid at path "${b}": `+f.errorsText(w.validateSchema.errors);if(m.validateSchema==="log")f.logger.error(I);else throw new Error(I)}}return Pr.validateKeywordUsage=h,Pr}var on={},py;function ME(){if(py)return on;py=1,Object.defineProperty(on,"__esModule",{value:!0}),on.extendSubschemaMode=on.extendSubschemaData=on.getSubschema=void 0;const e=Oe(),t=Fe();function r(a,{keyword:i,schemaProp:s,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:h}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=a.schema[i];return s===void 0?{schema:p,schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${a.errSchemaPath}/${i}`}:{schema:p[s],schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${i}/${(0,t.escapeFragment)(s)}`}}if(l!==void 0){if(c===void 0||u===void 0||h===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:h,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}on.getSubschema=r;function n(a,i,{dataProp:s,dataPropType:l,data:c,dataTypes:u,propertyName:h}){if(c!==void 0&&s!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(s!==void 0){const{errorPath:f,dataPathArr:b,opts:w}=i,C=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(s)}`,!0);m(C),a.errorPath=(0,e.str)`${f}${(0,t.getErrorPath)(s,l,w.jsPropertySyntax)}`,a.parentDataProperty=(0,e._)`${s}`,a.dataPathArr=[...b,a.parentDataProperty]}if(c!==void 0){const f=c instanceof e.Name?c:p.let("data",c,!0);m(f),h!==void 0&&(a.propertyName=h)}u&&(a.dataTypes=u);function m(f){a.data=f,a.dataLevel=i.dataLevel+1,a.dataTypes=[],i.definedProperties=new Set,a.parentData=i.data,a.dataNames=[...i.dataNames,f]}}on.extendSubschemaData=n;function o(a,{jtdDiscriminator:i,jtdMetadata:s,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(a.compositeRule=l),c!==void 0&&(a.createErrors=c),u!==void 0&&(a.allErrors=u),a.jtdDiscriminator=i,a.jtdMetadata=s}return on.extendSubschemaMode=o,on}var Qt={},Qu,hy;function fy(){return hy||(hy=1,Qu=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,a;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(a=Object.keys(t),n=a.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return!1;for(o=n;o--!==0;){var i=a[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}),Qu}var Xu={exports:{}},my;function OE(){if(my)return Xu.exports;my=1;var e=Xu.exports=function(n,o,a){typeof o=="function"&&(a=o,o={}),a=o.cb||a;var i=typeof a=="function"?a:a.pre||function(){},s=a.post||function(){};t(o,i,s,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,a,i,s,l,c,u,h,p){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,s,l,c,u,h,p);for(var m in i){var f=i[m];if(Array.isArray(f)){if(m in e.arrayKeywords)for(var b=0;b<f.length;b++)t(n,o,a,f[b],s+"/"+m+"/"+b,l,s,m,i,b)}else if(m in e.propsKeywords){if(f&&typeof f=="object")for(var w in f)t(n,o,a,f[w],s+"/"+m+"/"+r(w),l,s,m,i,w)}else(m in e.keywords||n.allKeys&&!(m in e.skipKeywords))&&t(n,o,a,f,s+"/"+m,l,s,m,i)}a(i,s,l,c,u,h,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Xu.exports}var gy;function ci(){if(gy)return Qt;gy=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.getSchemaRefs=Qt.resolveUrl=Qt.normalizeId=Qt._getFullPath=Qt.getFullPath=Qt.inlineRef=void 0;const e=Fe(),t=fy(),r=OE(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(b,w=!0){return typeof b=="boolean"?!0:w===!0?!i(b):w?s(b)<=w:!1}Qt.inlineRef=o;const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(b){for(const w in b){if(a.has(w))return!0;const C=b[w];if(Array.isArray(C)&&C.some(i)||typeof C=="object"&&i(C))return!0}return!1}function s(b){let w=0;for(const C in b){if(C==="$ref")return 1/0;if(w++,!n.has(C)&&(typeof b[C]=="object"&&(0,e.eachItem)(b[C],v=>w+=s(v)),w===1/0))return 1/0}return w}function l(b,w="",C){C!==!1&&(w=h(w));const v=b.parse(w);return c(b,v)}Qt.getFullPath=l;function c(b,w){return b.serialize(w).split("#")[0]+"#"}Qt._getFullPath=c;const u=/#\/?$/;function h(b){return b?b.replace(u,""):""}Qt.normalizeId=h;function p(b,w,C){return C=h(C),b.resolve(w,C)}Qt.resolveUrl=p;const m=/^[a-z_][-a-z0-9._]*$/i;function f(b,w){if(typeof b=="boolean")return{};const{schemaId:C,uriResolver:v}=this.opts,g=h(b[C]||w),I={"":g},y=l(v,g,!1),_={},k=new Set;return r(b,{allKeys:!0},(R,x,N,U)=>{if(U===void 0)return;const z=y+x;let ee=I[U];typeof R[C]=="string"&&(ee=Q.call(this,R[C])),se.call(this,R.$anchor),se.call(this,R.$dynamicAnchor),I[x]=ee;function Q(re){const Se=this.opts.uriResolver.resolve;if(re=h(ee?Se(ee,re):re),k.has(re))throw E(re);k.add(re);let H=this.refs[re];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?S(R,H.schema,re):re!==h(z)&&(re[0]==="#"?(S(R,_[re],re),_[re]=R):this.refs[re]=z),re}function se(re){if(typeof re=="string"){if(!m.test(re))throw new Error(`invalid anchor "${re}"`);Q.call(this,`#${re}`)}}}),_;function S(R,x,N){if(x!==void 0&&!t(R,x))throw E(N)}function E(R){return new Error(`reference "${R}" resolves to more than one schema`)}}return Qt.getSchemaRefs=f,Qt}var _y;function ui(){if(_y)return rn;_y=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.getData=rn.KeywordCxt=rn.validateFunctionCode=void 0;const e=$E(),t=li(),r=iy(),n=li(),o=RE(),a=PE(),i=ME(),s=Oe(),l=kn(),c=ci(),u=Fe(),h=ii();function p(A){if(y(A)&&(k(A),I(A))){w(A);return}m(A,()=>(0,e.topBoolOrEmptySchema)(A))}rn.validateFunctionCode=p;function m({gen:A,validateName:Z,schema:J,schemaEnv:te,opts:de},fe){de.code.es5?A.func(Z,(0,s._)`${l.default.data}, ${l.default.valCxt}`,te.$async,()=>{A.code((0,s._)`"use strict"; ${v(J,de)}`),b(A,de),A.code(fe)}):A.func(Z,(0,s._)`${l.default.data}, ${f(de)}`,te.$async,()=>A.code(v(J,de)).code(fe))}function f(A){return(0,s._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${A.dynamicRef?(0,s._)`, ${l.default.dynamicAnchors}={}`:s.nil}}={}`}function b(A,Z){A.if(l.default.valCxt,()=>{A.var(l.default.instancePath,(0,s._)`${l.default.valCxt}.${l.default.instancePath}`),A.var(l.default.parentData,(0,s._)`${l.default.valCxt}.${l.default.parentData}`),A.var(l.default.parentDataProperty,(0,s._)`${l.default.valCxt}.${l.default.parentDataProperty}`),A.var(l.default.rootData,(0,s._)`${l.default.valCxt}.${l.default.rootData}`),Z.dynamicRef&&A.var(l.default.dynamicAnchors,(0,s._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{A.var(l.default.instancePath,(0,s._)`""`),A.var(l.default.parentData,(0,s._)`undefined`),A.var(l.default.parentDataProperty,(0,s._)`undefined`),A.var(l.default.rootData,l.default.data),Z.dynamicRef&&A.var(l.default.dynamicAnchors,(0,s._)`{}`)})}function w(A){const{schema:Z,opts:J,gen:te}=A;m(A,()=>{J.$comment&&Z.$comment&&U(A),R(A),te.let(l.default.vErrors,null),te.let(l.default.errors,0),J.unevaluated&&C(A),S(A),z(A)})}function C(A){const{gen:Z,validateName:J}=A;A.evaluated=Z.const("evaluated",(0,s._)`${J}.evaluated`),Z.if((0,s._)`${A.evaluated}.dynamicProps`,()=>Z.assign((0,s._)`${A.evaluated}.props`,(0,s._)`undefined`)),Z.if((0,s._)`${A.evaluated}.dynamicItems`,()=>Z.assign((0,s._)`${A.evaluated}.items`,(0,s._)`undefined`))}function v(A,Z){const J=typeof A=="object"&&A[Z.schemaId];return J&&(Z.code.source||Z.code.process)?(0,s._)`/*# sourceURL=${J} */`:s.nil}function g(A,Z){if(y(A)&&(k(A),I(A))){_(A,Z);return}(0,e.boolOrEmptySchema)(A,Z)}function I({schema:A,self:Z}){if(typeof A=="boolean")return!A;for(const J in A)if(Z.RULES.all[J])return!0;return!1}function y(A){return typeof A.schema!="boolean"}function _(A,Z){const{schema:J,gen:te,opts:de}=A;de.$comment&&J.$comment&&U(A),x(A),N(A);const fe=te.const("_errs",l.default.errors);S(A,fe),te.var(Z,(0,s._)`${fe} === ${l.default.errors}`)}function k(A){(0,u.checkUnknownRules)(A),E(A)}function S(A,Z){if(A.opts.jtd)return Q(A,[],!1,Z);const J=(0,t.getSchemaTypes)(A.schema),te=(0,t.coerceAndCheckDataType)(A,J);Q(A,J,!te,Z)}function E(A){const{schema:Z,errSchemaPath:J,opts:te,self:de}=A;Z.$ref&&te.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,de.RULES)&&de.logger.warn(`$ref: keywords ignored in schema at path "${J}"`)}function R(A){const{schema:Z,opts:J}=A;Z.default!==void 0&&J.useDefaults&&J.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function x(A){const Z=A.schema[A.opts.schemaId];Z&&(A.baseId=(0,c.resolveUrl)(A.opts.uriResolver,A.baseId,Z))}function N(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:A,schemaEnv:Z,schema:J,errSchemaPath:te,opts:de}){const fe=J.$comment;if(de.$comment===!0)A.code((0,s._)`${l.default.self}.logger.log(${fe})`);else if(typeof de.$comment=="function"){const Ye=(0,s.str)`${te}/$comment`,wt=A.scopeValue("root",{ref:Z.root});A.code((0,s._)`${l.default.self}.opts.$comment(${fe}, ${Ye}, ${wt}.schema)`)}}function z(A){const{gen:Z,schemaEnv:J,validateName:te,ValidationError:de,opts:fe}=A;J.$async?Z.if((0,s._)`${l.default.errors} === 0`,()=>Z.return(l.default.data),()=>Z.throw((0,s._)`new ${de}(${l.default.vErrors})`)):(Z.assign((0,s._)`${te}.errors`,l.default.vErrors),fe.unevaluated&&ee(A),Z.return((0,s._)`${l.default.errors} === 0`))}function ee({gen:A,evaluated:Z,props:J,items:te}){J instanceof s.Name&&A.assign((0,s._)`${Z}.props`,J),te instanceof s.Name&&A.assign((0,s._)`${Z}.items`,te)}function Q(A,Z,J,te){const{gen:de,schema:fe,data:Ye,allErrors:wt,opts:st,self:et}=A,{RULES:Be}=et;if(fe.$ref&&(st.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(fe,Be))){de.block(()=>G(A,"$ref",Be.all.$ref.definition));return}st.jtd||re(A,Z),de.block(()=>{for(const it of Be.rules)tr(it);tr(Be.post)});function tr(it){(0,r.shouldUseGroup)(fe,it)&&(it.type?(de.if((0,n.checkDataType)(it.type,Ye,st.strictNumbers)),se(A,it),Z.length===1&&Z[0]===it.type&&J&&(de.else(),(0,n.reportTypeError)(A)),de.endIf()):se(A,it),wt||de.if((0,s._)`${l.default.errors} === ${te||0}`))}}function se(A,Z){const{gen:J,schema:te,opts:{useDefaults:de}}=A;de&&(0,o.assignDefaults)(A,Z.type),J.block(()=>{for(const fe of Z.rules)(0,r.shouldUseRule)(te,fe)&&G(A,fe.keyword,fe.definition,Z.type)})}function re(A,Z){A.schemaEnv.meta||!A.opts.strictTypes||(Se(A,Z),A.opts.allowUnionTypes||H(A,Z),D(A,A.dataTypes))}function Se(A,Z){if(Z.length){if(!A.dataTypes.length){A.dataTypes=Z;return}Z.forEach(J=>{F(A.dataTypes,J)||O(A,`type "${J}" not allowed by context "${A.dataTypes.join(",")}"`)}),$(A,Z)}}function H(A,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&O(A,"use allowUnionTypes to allow union type keyword")}function D(A,Z){const J=A.self.RULES.all;for(const te in J){const de=J[te];if(typeof de=="object"&&(0,r.shouldUseRule)(A.schema,de)){const{type:fe}=de.definition;fe.length&&!fe.some(Ye=>B(Z,Ye))&&O(A,`missing type "${fe.join(",")}" for keyword "${te}"`)}}}function B(A,Z){return A.includes(Z)||Z==="number"&&A.includes("integer")}function F(A,Z){return A.includes(Z)||Z==="integer"&&A.includes("number")}function $(A,Z){const J=[];for(const te of A.dataTypes)F(Z,te)?J.push(te):Z.includes("integer")&&te==="number"&&J.push("integer");A.dataTypes=J}function O(A,Z){const J=A.schemaEnv.baseId+A.errSchemaPath;Z+=` at "${J}" (strictTypes)`,(0,u.checkStrictMode)(A,Z,A.opts.strictTypes)}class j{constructor(Z,J,te){if((0,a.validateKeywordUsage)(Z,J,te),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=te,this.data=Z.data,this.schema=Z.schema[te],this.$data=J.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,te,this.$data),this.schemaType=J.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=J,this.$data)this.schemaCode=Z.gen.const("vSchema",V(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw new Error(`${te} value must be ${JSON.stringify(J.schemaType)}`);("code"in J?J.trackErrors:J.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",l.default.errors))}result(Z,J,te){this.failResult((0,s.not)(Z),J,te)}failResult(Z,J,te){this.gen.if(Z),te?te():this.error(),J?(this.gen.else(),J(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,J){this.failResult((0,s.not)(Z),void 0,J)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:J}=this;this.fail((0,s._)`${J} !== undefined && (${(0,s.or)(this.invalid$data(),Z)})`)}error(Z,J,te){if(J){this.setParams(J),this._error(Z,te),this.setParams({});return}this._error(Z,te)}_error(Z,J){(Z?h.reportExtraError:h.reportError)(this,this.def.error,J)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,J){J?Object.assign(this.params,Z):this.params=Z}block$data(Z,J,te=s.nil){this.gen.block(()=>{this.check$data(Z,te),J()})}check$data(Z=s.nil,J=s.nil){if(!this.$data)return;const{gen:te,schemaCode:de,schemaType:fe,def:Ye}=this;te.if((0,s.or)((0,s._)`${de} === undefined`,J)),Z!==s.nil&&te.assign(Z,!0),(fe.length||Ye.validateSchema)&&(te.elseIf(this.invalid$data()),this.$dataError(),Z!==s.nil&&te.assign(Z,!1)),te.else()}invalid$data(){const{gen:Z,schemaCode:J,schemaType:te,def:de,it:fe}=this;return(0,s.or)(Ye(),wt());function Ye(){if(te.length){if(!(J instanceof s.Name))throw new Error("ajv implementation error");const st=Array.isArray(te)?te:[te];return(0,s._)`${(0,n.checkDataTypes)(st,J,fe.opts.strictNumbers,n.DataType.Wrong)}`}return s.nil}function wt(){if(de.validateSchema){const st=Z.scopeValue("validate$data",{ref:de.validateSchema});return(0,s._)`!${st}(${J})`}return s.nil}}subschema(Z,J){const te=(0,i.getSubschema)(this.it,Z);(0,i.extendSubschemaData)(te,this.it,Z),(0,i.extendSubschemaMode)(te,Z);const de={...this.it,...te,items:void 0,props:void 0};return g(de,J),de}mergeEvaluated(Z,J){const{it:te,gen:de}=this;te.opts.unevaluated&&(te.props!==!0&&Z.props!==void 0&&(te.props=u.mergeEvaluated.props(de,Z.props,te.props,J)),te.items!==!0&&Z.items!==void 0&&(te.items=u.mergeEvaluated.items(de,Z.items,te.items,J)))}mergeValidEvaluated(Z,J){const{it:te,gen:de}=this;if(te.opts.unevaluated&&(te.props!==!0||te.items!==!0))return de.if(J,()=>this.mergeEvaluated(Z,s.Name)),!0}}rn.KeywordCxt=j;function G(A,Z,J,te){const de=new j(A,J,Z);"code"in J?J.code(de,te):de.$data&&J.validate?(0,a.funcKeywordCode)(de,J):"macro"in J?(0,a.macroKeywordCode)(de,J):(J.compile||J.validate)&&(0,a.funcKeywordCode)(de,J)}const Y=/^\/(?:[^~]|~0|~1)*$/,W=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function V(A,{dataLevel:Z,dataNames:J,dataPathArr:te}){let de,fe;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!Y.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);de=A,fe=l.default.rootData}else{const et=W.exec(A);if(!et)throw new Error(`Invalid JSON-pointer: ${A}`);const Be=+et[1];if(de=et[2],de==="#"){if(Be>=Z)throw new Error(st("property/index",Be));return te[Z-Be]}if(Be>Z)throw new Error(st("data",Be));if(fe=J[Z-Be],!de)return fe}let Ye=fe;const wt=de.split("/");for(const et of wt)et&&(fe=(0,s._)`${fe}${(0,s.getProperty)((0,u.unescapeJsonPointer)(et))}`,Ye=(0,s._)`${Ye} && ${fe}`);return Ye;function st(et,Be){return`Cannot access ${et} ${Be} levels up, current level is ${Z}`}}return rn.getData=V,rn}var di={},yy;function ed(){if(yy)return di;yy=1,Object.defineProperty(di,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return di.default=e,di}var pi={},vy;function hi(){if(vy)return pi;vy=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=ci();class t extends Error{constructor(n,o,a,i){super(i||`can't resolve reference ${a} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,a),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return pi.default=t,pi}var ur={},wy;function td(){if(wy)return ur;wy=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;const e=Oe(),t=ed(),r=kn(),n=ci(),o=Fe(),a=ui();class i{constructor(C){var v;this.refs={},this.dynamicAnchors={};let g;typeof C.schema=="object"&&(g=C.schema),this.schema=C.schema,this.schemaId=C.schemaId,this.root=C.root||this,this.baseId=(v=C.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(g?.[C.schemaId||"$id"]),this.schemaPath=C.schemaPath,this.localRefs=C.localRefs,this.meta=C.meta,this.$async=g?.$async,this.refs={}}}ur.SchemaEnv=i;function s(w){const C=u.call(this,w);if(C)return C;const v=(0,n.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:g,lines:I}=this.opts.code,{ownProperties:y}=this.opts,_=new e.CodeGen(this.scope,{es5:g,lines:I,ownProperties:y});let k;w.$async&&(k=_.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const S=_.scopeName("validate");w.validateName=S;const E={gen:_,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:_.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,e.stringify)(w.schema)}:{ref:w.schema}),validateName:S,ValidationError:k,schema:w.schema,schemaEnv:w,rootId:v,baseId:w.baseId||v,schemaPath:e.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let R;try{this._compilations.add(w),(0,a.validateFunctionCode)(E),_.optimize(this.opts.code.optimize);const x=_.toString();R=`${_.scopeRefs(r.default.scope)}return ${x}`,this.opts.code.process&&(R=this.opts.code.process(R,w));const U=new Function(`${r.default.self}`,`${r.default.scope}`,R)(this,this.scope.get());if(this.scope.value(S,{ref:U}),U.errors=null,U.schema=w.schema,U.schemaEnv=w,w.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:S,validateCode:x,scopeValues:_._values}),this.opts.unevaluated){const{props:z,items:ee}=E;U.evaluated={props:z instanceof e.Name?void 0:z,items:ee instanceof e.Name?void 0:ee,dynamicProps:z instanceof e.Name,dynamicItems:ee instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return w.validate=U,w}catch(x){throw delete w.validate,delete w.validateName,R&&this.logger.error("Error compiling schema, function code:",R),x}finally{this._compilations.delete(w)}}ur.compileSchema=s;function l(w,C,v){var g;v=(0,n.resolveUrl)(this.opts.uriResolver,C,v);const I=w.refs[v];if(I)return I;let y=p.call(this,w,v);if(y===void 0){const _=(g=w.localRefs)===null||g===void 0?void 0:g[v],{schemaId:k}=this.opts;_&&(y=new i({schema:_,schemaId:k,root:w,baseId:C}))}if(y!==void 0)return w.refs[v]=c.call(this,y)}ur.resolveRef=l;function c(w){return(0,n.inlineRef)(w.schema,this.opts.inlineRefs)?w.schema:w.validate?w:s.call(this,w)}function u(w){for(const C of this._compilations)if(h(C,w))return C}ur.getCompilingSchema=u;function h(w,C){return w.schema===C.schema&&w.root===C.root&&w.baseId===C.baseId}function p(w,C){let v;for(;typeof(v=this.refs[C])=="string";)C=v;return v||this.schemas[C]||m.call(this,w,C)}function m(w,C){const v=this.opts.uriResolver.parse(C),g=(0,n._getFullPath)(this.opts.uriResolver,v);let I=(0,n.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&g===I)return b.call(this,v,w);const y=(0,n.normalizeId)(g),_=this.refs[y]||this.schemas[y];if(typeof _=="string"){const k=m.call(this,w,_);return typeof k?.schema!="object"?void 0:b.call(this,v,k)}if(typeof _?.schema=="object"){if(_.validate||s.call(this,_),y===(0,n.normalizeId)(C)){const{schema:k}=_,{schemaId:S}=this.opts,E=k[S];return E&&(I=(0,n.resolveUrl)(this.opts.uriResolver,I,E)),new i({schema:k,schemaId:S,root:w,baseId:I})}return b.call(this,v,_)}}ur.resolveSchema=m;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(w,{baseId:C,schema:v,root:g}){var I;if(((I=w.fragment)===null||I===void 0?void 0:I[0])!=="/")return;for(const k of w.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const S=v[(0,o.unescapeFragment)(k)];if(S===void 0)return;v=S;const E=typeof v=="object"&&v[this.opts.schemaId];!f.has(k)&&E&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,E))}let y;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const k=(0,n.resolveUrl)(this.opts.uriResolver,C,v.$ref);y=m.call(this,g,k)}const{schemaId:_}=this.opts;if(y=y||new i({schema:v,schemaId:_,root:g,baseId:C}),y.schema!==y.root.schema)return y}return ur}const AE={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var fi={},Na={exports:{}},rd,by;function ky(){if(by)return rd;by=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),r=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),n=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function a(y){let _="",k=0,S=0;for(S=0;S<y.length;S++)if(k=y[S].charCodeAt(0),k!==48){if(!(k>=48&&k<=57||k>=65&&k<=70||k>=97&&k<=102))return"";_+=y[S];break}for(S+=1;S<y.length;S++){if(k=y[S].charCodeAt(0),!(k>=48&&k<=57||k>=65&&k<=70||k>=97&&k<=102))return"";_+=y[S]}return _}const i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(y){return y.length=0,!0}function l(y,_,k){if(y.length){const S=a(y);if(S!=="")_.push(S);else return k.error=!0,!1;y.length=0}return!0}function c(y){let _=0;const k={error:!1,address:"",zone:""},S=[],E=[];let R=!1,x=!1,N=l;for(let U=0;U<y.length;U++){const z=y[U];if(!(z==="["||z==="]"))if(z===":"){if(R===!0&&(x=!0),!N(E,S,k))break;if(++_>7){k.error=!0;break}U>0&&y[U-1]===":"&&(R=!0),S.push(":");continue}else if(z==="%"){if(!N(E,S,k))break;N=s}else{E.push(z);continue}}return E.length&&(N===s?k.zone=E.join(""):x?S.push(E.join("")):S.push(a(E))),k.address=S.join(""),k}function u(y){if(h(y,":")<2)return{host:y,isIPV6:!1};const _=c(y);if(_.error)return{host:y,isIPV6:!1};{let k=_.address,S=_.address;return _.zone&&(k+="%"+_.zone,S+="%25"+_.zone),{host:k,isIPV6:!0,escapedHost:S}}}function h(y,_){let k=0;for(let S=0;S<y.length;S++)y[S]===_&&k++;return k}function p(y){let _=y;const k=[];let S=-1,E=0;for(;E=_.length;){if(E===1){if(_===".")break;if(_==="/"){k.push("/");break}else{k.push(_);break}}else if(E===2){if(_[0]==="."){if(_[1]===".")break;if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&(_[1]==="."||_[1]==="/")){k.push("/");break}}else if(E===3&&_==="/.."){k.length!==0&&k.pop(),k.push("/");break}if(_[0]==="."){if(_[1]==="."){if(_[2]==="/"){_=_.slice(3);continue}}else if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&_[1]==="."){if(_[2]==="/"){_=_.slice(2);continue}else if(_[2]==="."&&_[3]==="/"){_=_.slice(3),k.length!==0&&k.pop();continue}}if((S=_.indexOf("/",1))===-1){k.push(_);break}else k.push(_.slice(0,S)),_=_.slice(S)}return k.join("")}const m={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},f=/[@/?#:]/g,b=/[@/?#]/g;function w(y,_){const k=_?b:f;return k.lastIndex=0,y.replace(k,S=>m[S])}function C(y,_=!1){if(y.indexOf("%")===-1)return y;let k="";for(let S=0;S<y.length;S++){if(y[S]==="%"&&S+2<y.length){const E=y.slice(S+1,S+3);if(r(E)){const R=E.toUpperCase(),x=String.fromCharCode(parseInt(R,16));_&&n(x)?k+=x:k+="%"+R,S+=2;continue}}k+=y[S]}return k}function v(y){let _="";for(let k=0;k<y.length;k++){if(y[k]==="%"&&k+2<y.length){const S=y.slice(k+1,k+3);if(r(S)){const E=S.toUpperCase(),R=String.fromCharCode(parseInt(E,16));R!=="."&&n(R)?_+=R:_+="%"+E,k+=2;continue}}o(y[k])?_+=y[k]:_+=escape(y[k])}return _}function g(y){let _="";for(let k=0;k<y.length;k++){if(y[k]==="%"&&k+2<y.length){const S=y.slice(k+1,k+3);if(r(S)){_+="%"+S.toUpperCase(),k+=2;continue}}_+=escape(y[k])}return _}function I(y){const _=[];if(y.userinfo!==void 0&&(_.push(y.userinfo),_.push("@")),y.host!==void 0){let k=unescape(y.host);if(!t(k)){const S=u(k);S.isIPV6===!0?k=`[${S.escapedHost}]`:k=w(k,!1)}_.push(k)}return(typeof y.port=="number"||typeof y.port=="string")&&(_.push(":"),_.push(String(y.port))),_.length?_.join(""):void 0}return rd={nonSimpleDomain:i,recomposeAuthority:I,reescapeHostDelimiters:w,normalizePercentEncoding:C,normalizePathEncoding:v,escapePreservingEscapes:g,removeDotSegments:p,isIPv4:t,isUUID:e,normalizeIPv6:u,stringArrayToHexStripped:a},rd}var nd,Ty;function NE(){if(Ty)return nd;Ty=1;const{isUUID:e}=ky(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(y){return r.indexOf(y)!==-1}function o(y){return y.secure===!0?!0:y.secure===!1?!1:y.scheme?y.scheme.length===3&&(y.scheme[0]==="w"||y.scheme[0]==="W")&&(y.scheme[1]==="s"||y.scheme[1]==="S")&&(y.scheme[2]==="s"||y.scheme[2]==="S"):!1}function a(y){return y.host||(y.error=y.error||"HTTP URIs must have a host."),y}function i(y){const _=String(y.scheme).toLowerCase()==="https";return(y.port===(_?443:80)||y.port==="")&&(y.port=void 0),y.path||(y.path="/"),y}function s(y){return y.secure=o(y),y.resourceName=(y.path||"/")+(y.query?"?"+y.query:""),y.path=void 0,y.query=void 0,y}function l(y){if((y.port===(o(y)?443:80)||y.port==="")&&(y.port=void 0),typeof y.secure=="boolean"&&(y.scheme=y.secure?"wss":"ws",y.secure=void 0),y.resourceName){const[_,k]=y.resourceName.split("?");y.path=_&&_!=="/"?_:void 0,y.query=k,y.resourceName=void 0}return y.fragment=void 0,y}function c(y,_){if(!y.path)return y.error="URN can not be parsed",y;const k=y.path.match(t);if(k){const S=_.scheme||y.scheme||"urn";y.nid=k[1].toLowerCase(),y.nss=k[2];const E=`${S}:${_.nid||y.nid}`,R=I(E);y.path=void 0,R&&(y=R.parse(y,_))}else y.error=y.error||"URN can not be parsed.";return y}function u(y,_){if(y.nid===void 0)throw new Error("URN without nid cannot be serialized");const k=_.scheme||y.scheme||"urn",S=y.nid.toLowerCase(),E=`${k}:${_.nid||S}`,R=I(E);R&&(y=R.serialize(y,_));const x=y,N=y.nss;return x.path=`${S||_.nid}:${N}`,_.skipEscape=!0,x}function h(y,_){const k=y;return k.uuid=k.nss,k.nss=void 0,!_.tolerant&&(!k.uuid||!e(k.uuid))&&(k.error=k.error||"UUID is not valid."),k}function p(y){const _=y;return _.nss=(y.uuid||"").toLowerCase(),_}const m={scheme:"http",domainHost:!0,parse:a,serialize:i},f={scheme:"https",domainHost:m.domainHost,parse:a,serialize:i},b={scheme:"ws",domainHost:!0,parse:s,serialize:l},w={scheme:"wss",domainHost:b.domainHost,parse:b.parse,serialize:b.serialize},g={http:m,https:f,ws:b,wss:w,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(g,null);function I(y){return y&&(g[y]||g[y.toLowerCase()])||void 0}return nd={wsIsSecure:o,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:I},nd}var Cy;function qE(){if(Cy)return Na.exports;Cy=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizePercentEncoding:n,normalizePathEncoding:o,escapePreservingEscapes:a,reescapeHostDelimiters:i,isIPv4:s,nonSimpleDomain:l}=ky(),{SCHEMES:c,getSchemeHandler:u}=NE();function h(S,E){return typeof S=="string"?S=I(S,E):typeof S=="object"&&(S=g(b(S,E),E)),S}function p(S,E,R){const x=R?Object.assign({scheme:"null"},R):{scheme:"null"},N=m(g(S,x),g(E,x),x,!0);return x.skipEscape=!0,b(N,x)}function m(S,E,R,x){const N={};return x||(S=g(b(S,R),R),E=g(b(E,R),R)),R=R||{},!R.tolerant&&E.scheme?(N.scheme=E.scheme,N.userinfo=E.userinfo,N.host=E.host,N.port=E.port,N.path=t(E.path||""),N.query=E.query):(E.userinfo!==void 0||E.host!==void 0||E.port!==void 0?(N.userinfo=E.userinfo,N.host=E.host,N.port=E.port,N.path=t(E.path||""),N.query=E.query):(E.path?(E.path[0]==="/"?N.path=t(E.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?N.path="/"+E.path:S.path?N.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+E.path:N.path=E.path,N.path=t(N.path)),N.query=E.query):(N.path=S.path,E.query!==void 0?N.query=E.query:N.query=S.query),N.userinfo=S.userinfo,N.host=S.host,N.port=S.port),N.scheme=S.scheme),N.fragment=E.fragment,N}function f(S,E,R){const x=_(S,R),N=_(E,R);return x!==void 0&&N!==void 0&&x.toLowerCase()===N.toLowerCase()}function b(S,E){const R={host:S.host,scheme:S.scheme,userinfo:S.userinfo,port:S.port,path:S.path,query:S.query,nid:S.nid,nss:S.nss,uuid:S.uuid,fragment:S.fragment,reference:S.reference,resourceName:S.resourceName,secure:S.secure,error:""},x=Object.assign({},E),N=[],U=u(x.scheme||R.scheme);U&&U.serialize&&U.serialize(R,x),R.path!==void 0&&(x.skipEscape?R.path=n(R.path):(R.path=a(R.path),R.scheme!==void 0&&(R.path=R.path.split("%3A").join(":")))),x.reference!=="suffix"&&R.scheme&&N.push(R.scheme,":");const z=r(R);if(z!==void 0&&(x.reference!=="suffix"&&N.push("//"),N.push(z),R.path&&R.path[0]!=="/"&&N.push("/")),R.path!==void 0){let ee=R.path;!x.absolutePath&&(!U||!U.absolutePath)&&(ee=t(ee)),z===void 0&&ee[0]==="/"&&ee[1]==="/"&&(ee="/%2F"+ee.slice(2)),N.push(ee)}return R.query!==void 0&&N.push("?",R.query),R.fragment!==void 0&&N.push("#",R.fragment),N.join("")}const w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function C(S,E){if(E[2]!==void 0&&S.path&&S.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof S.port=="number"&&(S.port<0||S.port>65535))return"URI port is malformed."}function v(S,E){const R=Object.assign({},E),x={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let N=!1,U=!1;R.reference==="suffix"&&(R.scheme?S=R.scheme+":"+S:S="//"+S);const z=S.match(w);if(z){x.scheme=z[1],x.userinfo=z[3],x.host=z[4],x.port=parseInt(z[5],10),x.path=z[6]||"",x.query=z[7],x.fragment=z[8],isNaN(x.port)&&(x.port=z[5]);const ee=C(x,z);if(ee!==void 0&&(x.error=x.error||ee,N=!0),x.host)if(s(x.host)===!1){const re=e(x.host);x.host=re.host.toLowerCase(),U=re.isIPV6}else U=!0;x.scheme===void 0&&x.userinfo===void 0&&x.host===void 0&&x.port===void 0&&x.query===void 0&&!x.path?x.reference="same-document":x.scheme===void 0?x.reference="relative":x.fragment===void 0?x.reference="absolute":x.reference="uri",R.reference&&R.reference!=="suffix"&&R.reference!==x.reference&&(x.error=x.error||"URI is not a "+R.reference+" reference.");const Q=u(R.scheme||x.scheme);if(!R.unicodeSupport&&(!Q||!Q.unicodeSupport)&&x.host&&(R.domainHost||Q&&Q.domainHost)&&U===!1&&l(x.host))try{x.host=new URL("http://"+x.host).hostname}catch(se){x.error=x.error||"Host's domain name can not be converted to ASCII: "+se}if((!Q||Q&&!Q.skipNormalize)&&(S.indexOf("%")!==-1&&(x.scheme!==void 0&&(x.scheme=unescape(x.scheme)),x.host!==void 0&&(x.host=i(unescape(x.host),U))),x.path&&(x.path=o(x.path)),x.fragment))try{x.fragment=encodeURI(decodeURIComponent(x.fragment))}catch{x.error=x.error||"URI malformed"}Q&&Q.parse&&Q.parse(x,R)}else x.error=x.error||"URI can not be parsed.";return{parsed:x,malformedAuthorityOrPort:N}}function g(S,E){return v(S,E).parsed}function I(S,E){return y(S,E).normalized}function y(S,E){const{parsed:R,malformedAuthorityOrPort:x}=v(S,E);return{normalized:x?S:b(R,E),malformedAuthorityOrPort:x}}function _(S,E){if(typeof S=="string"){const{normalized:R,malformedAuthorityOrPort:x}=y(S,E);return x?void 0:R}if(typeof S=="object")return b(S,E)}const k={SCHEMES:c,normalize:h,resolve:p,resolveComponent:m,equal:f,serialize:b,parse:g};return Na.exports=k,Na.exports.default=k,Na.exports.fastUri=k,Na.exports}var Sy;function LE(){if(Sy)return fi;Sy=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=qE();return e.code='require("ajv/dist/runtime/uri").default',fi.default=e,fi}var Iy;function jE(){return Iy||(Iy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=ui();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Oe();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=ed(),o=hi(),a=ay(),i=td(),s=Oe(),l=ci(),c=li(),u=Fe(),h=AE,p=LE(),m=(H,D)=>new RegExp(H,D);m.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],b=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},C={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function g(H){var D,B,F,$,O,j,G,Y,W,V,A,Z,J,te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr;const rr=H.strict,Lr=(D=H.code)===null||D===void 0?void 0:D.optimize,pr=Lr===!0||Lr===void 0?1:Lr||0,P=(F=(B=H.code)===null||B===void 0?void 0:B.regExp)!==null&&F!==void 0?F:m,X=($=H.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(j=(O=H.strictSchema)!==null&&O!==void 0?O:rr)!==null&&j!==void 0?j:!0,strictNumbers:(Y=(G=H.strictNumbers)!==null&&G!==void 0?G:rr)!==null&&Y!==void 0?Y:!0,strictTypes:(V=(W=H.strictTypes)!==null&&W!==void 0?W:rr)!==null&&V!==void 0?V:"log",strictTuples:(Z=(A=H.strictTuples)!==null&&A!==void 0?A:rr)!==null&&Z!==void 0?Z:"log",strictRequired:(te=(J=H.strictRequired)!==null&&J!==void 0?J:rr)!==null&&te!==void 0?te:!1,code:H.code?{...H.code,optimize:pr,regExp:P}:{optimize:pr,regExp:P},loopRequired:(de=H.loopRequired)!==null&&de!==void 0?de:v,loopEnum:(fe=H.loopEnum)!==null&&fe!==void 0?fe:v,meta:(Ye=H.meta)!==null&&Ye!==void 0?Ye:!0,messages:(wt=H.messages)!==null&&wt!==void 0?wt:!0,inlineRefs:(st=H.inlineRefs)!==null&&st!==void 0?st:!0,schemaId:(et=H.schemaId)!==null&&et!==void 0?et:"$id",addUsedSchema:(Be=H.addUsedSchema)!==null&&Be!==void 0?Be:!0,validateSchema:(tr=H.validateSchema)!==null&&tr!==void 0?tr:!0,validateFormats:(it=H.validateFormats)!==null&&it!==void 0?it:!0,unicodeRegExp:(qr=H.unicodeRegExp)!==null&&qr!==void 0?qr:!0,int32range:(dr=H.int32range)!==null&&dr!==void 0?dr:!0,uriResolver:X}}class I{constructor(D={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,D=this.opts={...D,...g(D)};const{es5:B,lines:F}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:b,es5:B,lines:F}),this.logger=N(D.logger);const $=D.validateFormats;D.validateFormats=!1,this.RULES=(0,a.getRules)(),y.call(this,w,D,"NOT SUPPORTED"),y.call(this,C,D,"DEPRECATED","warn"),this._metaOpts=R.call(this),D.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),D.keywords&&E.call(this,D.keywords),typeof D.meta=="object"&&this.addMetaSchema(D.meta),k.call(this),D.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:D,meta:B,schemaId:F}=this.opts;let $=h;F==="id"&&($={...h},$.id=$.$id,delete $.$id),B&&D&&this.addMetaSchema($,$[F],!1)}defaultMeta(){const{meta:D,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof D=="object"?D[B]||D:void 0}validate(D,B){let F;if(typeof D=="string"){if(F=this.getSchema(D),!F)throw new Error(`no schema with key or ref "${D}"`)}else F=this.compile(D);const $=F(B);return"$async"in F||(this.errors=F.errors),$}compile(D,B){const F=this._addSchema(D,B);return F.validate||this._compileSchemaEnv(F)}compileAsync(D,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return $.call(this,D,B);async function $(V,A){await O.call(this,V.$schema);const Z=this._addSchema(V,A);return Z.validate||j.call(this,Z)}async function O(V){V&&!this.getSchema(V)&&await $.call(this,{$ref:V},!0)}async function j(V){try{return this._compileSchemaEnv(V)}catch(A){if(!(A instanceof o.default))throw A;return G.call(this,A),await Y.call(this,A.missingSchema),j.call(this,V)}}function G({missingSchema:V,missingRef:A}){if(this.refs[V])throw new Error(`AnySchema ${V} is loaded but ${A} cannot be resolved`)}async function Y(V){const A=await W.call(this,V);this.refs[V]||await O.call(this,A.$schema),this.refs[V]||this.addSchema(A,V,B)}async function W(V){const A=this._loading[V];if(A)return A;try{return await(this._loading[V]=F(V))}finally{delete this._loading[V]}}}addSchema(D,B,F,$=this.opts.validateSchema){if(Array.isArray(D)){for(const j of D)this.addSchema(j,void 0,F,$);return this}let O;if(typeof D=="object"){const{schemaId:j}=this.opts;if(O=D[j],O!==void 0&&typeof O!="string")throw new Error(`schema ${j} must be string`)}return B=(0,l.normalizeId)(B||O),this._checkUnique(B),this.schemas[B]=this._addSchema(D,F,B,$,!0),this}addMetaSchema(D,B,F=this.opts.validateSchema){return this.addSchema(D,B,!0,F),this}validateSchema(D,B){if(typeof D=="boolean")return!0;let F;if(F=D.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const $=this.validate(F,D);if(!$&&B){const O="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(O);else throw new Error(O)}return $}getSchema(D){let B;for(;typeof(B=_.call(this,D))=="string";)D=B;if(B===void 0){const{schemaId:F}=this.opts,$=new i.SchemaEnv({schema:{},schemaId:F});if(B=i.resolveSchema.call(this,$,D),!B)return;this.refs[D]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema(D){if(D instanceof RegExp)return this._removeAllSchemas(this.schemas,D),this._removeAllSchemas(this.refs,D),this;switch(typeof D){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const B=_.call(this,D);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[D],delete this.refs[D],this}case"object":{const B=D;this._cache.delete(B);let F=D[this.opts.schemaId];return F&&(F=(0,l.normalizeId)(F),delete this.schemas[F],delete this.refs[F]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(D){for(const B of D)this.addKeyword(B);return this}addKeyword(D,B){let F;if(typeof D=="string")F=D,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=F);else if(typeof D=="object"&&B===void 0){if(B=D,F=B.keyword,Array.isArray(F)&&!F.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(z.call(this,F,B),!B)return(0,u.eachItem)(F,O=>ee.call(this,O)),this;se.call(this,B);const $={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(F,$.type.length===0?O=>ee.call(this,O,$):O=>$.type.forEach(j=>ee.call(this,O,$,j))),this}getKeyword(D){const B=this.RULES.all[D];return typeof B=="object"?B.definition:!!B}removeKeyword(D){const{RULES:B}=this;delete B.keywords[D],delete B.all[D];for(const F of B.rules){const $=F.rules.findIndex(O=>O.keyword===D);$>=0&&F.rules.splice($,1)}return this}addFormat(D,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[D]=B,this}errorsText(D=this.errors,{separator:B=", ",dataVar:F="data"}={}){return!D||D.length===0?"No errors":D.map($=>`${F}${$.instancePath} ${$.message}`).reduce(($,O)=>$+B+O)}$dataMetaSchema(D,B){const F=this.RULES.all;D=JSON.parse(JSON.stringify(D));for(const $ of B){const O=$.split("/").slice(1);let j=D;for(const G of O)j=j[G];for(const G in F){const Y=F[G];if(typeof Y!="object")continue;const{$data:W}=Y.definition,V=j[G];W&&V&&(j[G]=Se(V))}}return D}_removeAllSchemas(D,B){for(const F in D){const $=D[F];(!B||B.test(F))&&(typeof $=="string"?delete D[F]:$&&!$.meta&&(this._cache.delete($.schema),delete D[F]))}}_addSchema(D,B,F,$=this.opts.validateSchema,O=this.opts.addUsedSchema){let j;const{schemaId:G}=this.opts;if(typeof D=="object")j=D[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof D!="boolean")throw new Error("schema must be object or boolean")}let Y=this._cache.get(D);if(Y!==void 0)return Y;F=(0,l.normalizeId)(j||F);const W=l.getSchemaRefs.call(this,D,F);return Y=new i.SchemaEnv({schema:D,schemaId:G,meta:B,baseId:F,localRefs:W}),this._cache.set(Y.schema,Y),O&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=Y),$&&this.validateSchema(D,!0),Y}_checkUnique(D){if(this.schemas[D]||this.refs[D])throw new Error(`schema with key or id "${D}" already exists`)}_compileSchemaEnv(D){if(D.meta?this._compileMetaSchema(D):i.compileSchema.call(this,D),!D.validate)throw new Error("ajv implementation error");return D.validate}_compileMetaSchema(D){const B=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,D)}finally{this.opts=B}}}I.ValidationError=n.default,I.MissingRefError=o.default,e.default=I;function y(H,D,B,F="error"){for(const $ in H){const O=$;O in D&&this.logger[F](`${B}: option ${$}. ${H[O]}`)}}function _(H){return H=(0,l.normalizeId)(H),this.schemas[H]||this.refs[H]}function k(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const D in H)this.addSchema(H[D],D)}function S(){for(const H in this.opts.formats){const D=this.opts.formats[H];D&&this.addFormat(H,D)}}function E(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const D in H){const B=H[D];B.keyword||(B.keyword=D),this.addKeyword(B)}}function R(){const H={...this.opts};for(const D of f)delete H[D];return H}const x={log(){},warn(){},error(){}};function N(H){if(H===!1)return x;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function z(H,D){const{RULES:B}=this;if((0,u.eachItem)(H,F=>{if(B.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!U.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!D&&D.$data&&!("code"in D||"validate"in D))throw new Error('$data keyword must have "code" or "validate" function')}function ee(H,D,B){var F;const $=D?.post;if(B&&$)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:O}=this;let j=$?O.post:O.rules.find(({type:Y})=>Y===B);if(j||(j={type:B,rules:[]},O.rules.push(j)),O.keywords[H]=!0,!D)return;const G={keyword:H,definition:{...D,type:(0,c.getJSONTypes)(D.type),schemaType:(0,c.getJSONTypes)(D.schemaType)}};D.before?Q.call(this,j,G,D.before):j.rules.push(G),O.all[H]=G,(F=D.implements)===null||F===void 0||F.forEach(Y=>this.addKeyword(Y))}function Q(H,D,B){const F=H.rules.findIndex($=>$.keyword===B);F>=0?H.rules.splice(F,0,D):(H.rules.push(D),this.logger.warn(`rule ${B} is not defined`))}function se(H){let{metaSchema:D}=H;D!==void 0&&(H.$data&&this.opts.$data&&(D=Se(D)),H.validateSchema=this.compile(D,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Se(H){return{anyOf:[H,re]}}})(Ju)),Ju}var mi={},gi={},_i={},xy;function DE(){if(xy)return _i;xy=1,Object.defineProperty(_i,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return _i.default=e,_i}var Tn={},Ey;function UE(){if(Ey)return Tn;Ey=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.callRef=Tn.getValidate=void 0;const e=hi(),t=Mr(),r=Oe(),n=kn(),o=td(),a=Fe(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:h,it:p}=c,{baseId:m,schemaEnv:f,validateName:b,opts:w,self:C}=p,{root:v}=f;if((h==="#"||h==="#/")&&m===v.baseId)return I();const g=o.resolveRef.call(C,v,m,h);if(g===void 0)throw new e.default(p.opts.uriResolver,m,h);if(g instanceof o.SchemaEnv)return y(g);return _(g);function I(){if(f===v)return l(c,b,f,f.$async);const k=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${k}.validate`,v,v.$async)}function y(k){const S=s(c,k);l(c,S,k,k.$async)}function _(k){const S=u.scopeValue("schema",w.code.source===!0?{ref:k,code:(0,r.stringify)(k)}:{ref:k}),E=u.name("valid"),R=c.subschema({schema:k,dataTypes:[],schemaPath:r.nil,topSchemaRef:S,errSchemaPath:h},E);c.mergeEvaluated(R),c.ok(E)}}};function s(c,u){const{gen:h}=c;return u.validate?h.scopeValue("validate",{ref:u.validate}):(0,r._)`${h.scopeValue("wrapper",{ref:u})}.validate`}Tn.getValidate=s;function l(c,u,h,p){const{gen:m,it:f}=c,{allErrors:b,schemaEnv:w,opts:C}=f,v=C.passContext?n.default.this:r.nil;p?g():I();function g(){if(!w.$async)throw new Error("async schema referenced by sync schema");const k=m.let("valid");m.try(()=>{m.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),_(u),b||m.assign(k,!0)},S=>{m.if((0,r._)`!(${S} instanceof ${f.ValidationError})`,()=>m.throw(S)),y(S),b||m.assign(k,!1)}),c.ok(k)}function I(){c.result((0,t.callValidateCode)(c,u,v),()=>_(u),()=>y(u))}function y(k){const S=(0,r._)`${k}.errors`;m.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${S} : ${n.default.vErrors}.concat(${S})`),m.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function _(k){var S;if(!f.opts.unevaluated)return;const E=(S=h?.validate)===null||S===void 0?void 0:S.evaluated;if(f.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(f.props=a.mergeEvaluated.props(m,E.props,f.props));else{const R=m.var("props",(0,r._)`${k}.evaluated.props`);f.props=a.mergeEvaluated.props(m,R,f.props,r.Name)}if(f.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(f.items=a.mergeEvaluated.items(m,E.items,f.items));else{const R=m.var("items",(0,r._)`${k}.evaluated.items`);f.items=a.mergeEvaluated.items(m,R,f.items,r.Name)}}}return Tn.callRef=l,Tn.default=i,Tn}var $y;function zE(){if($y)return gi;$y=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=DE(),t=UE(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return gi.default=r,gi}var yi={},vi={},Ry;function FE(){if(Ry)return vi;Ry=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Oe(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:a,schemaCode:i})=>(0,e.str)`must be ${r[a].okStr} ${i}`,params:({keyword:a,schemaCode:i})=>(0,e._)`{comparison: ${r[a].okStr}, limit: ${i}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(a){const{keyword:i,data:s,schemaCode:l}=a;a.fail$data((0,e._)`${s} ${r[i].fail} ${l} || isNaN(${s})`)}};return vi.default=o,vi}var wi={},Py;function VE(){if(Py)return wi;Py=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=Oe(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:a,schemaCode:i,it:s}=n,l=s.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${i} === 0 || (${c} = ${a}/${i}, ${u}))`)}};return wi.default=r,wi}var bi={},ki={},My;function ZE(){if(My)return ki;My=1,Object.defineProperty(ki,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,a;for(;o<r;)n++,a=t.charCodeAt(o++),a>=55296&&a<=56319&&o<r&&(a=t.charCodeAt(o),(a&64512)===56320&&o++);return n}return ki.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ki}var Oy;function HE(){if(Oy)return bi;Oy=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=ZE(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:a,schemaCode:i}){const s=a==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${i} characters`},params:({schemaCode:a})=>(0,e._)`{limit: ${a}}`},code(a){const{keyword:i,data:s,schemaCode:l,it:c}=a,u=i==="maxLength"?e.operators.GT:e.operators.LT,h=c.opts.unicode===!1?(0,e._)`${s}.length`:(0,e._)`${(0,t.useFunc)(a.gen,r.default)}(${s})`;a.fail$data((0,e._)`${h} ${u} ${l}`)}};return bi.default=o,bi}var Ti={},Ay;function BE(){if(Ay)return Ti;Ay=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Mr(),t=Fe(),r=Oe(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},code(a){const{gen:i,data:s,$data:l,schema:c,schemaCode:u,it:h}=a,p=h.opts.unicodeRegExp?"u":"";if(l){const{regExp:m}=h.opts.code,f=m.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(i,m),b=i.let("valid");i.try(()=>i.assign(b,(0,r._)`${f}(${u}, ${p}).test(${s})`),()=>i.assign(b,!1)),a.fail$data((0,r._)`!${b}`)}else{const m=(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${m}.test(${s})`)}}};return Ti.default=o,Ti}var Ci={},Ny;function JE(){if(Ny)return Ci;Ny=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e=Oe(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const a=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:a,schemaCode:i}=n,s=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${a}).length ${s} ${i}`)}};return Ci.default=r,Ci}var Si={},qy;function GE(){if(qy)return Si;qy=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=Fe(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:a}})=>(0,t.str)`must have required property '${a}'`,params:({params:{missingProperty:a}})=>(0,t._)`{missingProperty: ${a}}`},code(a){const{gen:i,schema:s,schemaCode:l,data:c,$data:u,it:h}=a,{opts:p}=h;if(!u&&s.length===0)return;const m=s.length>=p.loopRequired;if(h.allErrors?f():b(),p.strictRequired){const v=a.parentSchema.properties,{definedProperties:g}=a.it;for(const I of s)if(v?.[I]===void 0&&!g.has(I)){const y=h.schemaEnv.baseId+h.errSchemaPath,_=`required property "${I}" is not defined at "${y}" (strictRequired)`;(0,r.checkStrictMode)(h,_,h.opts.strictRequired)}}function f(){if(m||u)a.block$data(t.nil,w);else for(const v of s)(0,e.checkReportMissingProp)(a,v)}function b(){const v=i.let("missing");if(m||u){const g=i.let("valid",!0);a.block$data(g,()=>C(v,g)),a.ok(g)}else i.if((0,e.checkMissingProp)(a,s,v)),(0,e.reportMissingProp)(a,v),i.else()}function w(){i.forOf("prop",l,v=>{a.setParams({missingProperty:v}),i.if((0,e.noPropertyInData)(i,c,v,p.ownProperties),()=>a.error())})}function C(v,g){a.setParams({missingProperty:v}),i.forOf(v,l,()=>{i.assign(g,(0,e.propertyInData)(i,c,v,p.ownProperties)),i.if((0,t.not)(g),()=>{a.error(),i.break()})},t.nil)}}};return Si.default=o,Si}var Ii={},Ly;function WE(){if(Ly)return Ii;Ly=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Oe(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const a=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:a,schemaCode:i}=n,s=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${a}.length ${s} ${i}`)}};return Ii.default=r,Ii}var xi={},Ei={},jy;function od(){if(jy)return Ei;jy=1,Object.defineProperty(Ei,"__esModule",{value:!0});const e=fy();return e.code='require("ajv/dist/runtime/equal").default',Ei.default=e,Ei}var Dy;function KE(){if(Dy)return xi;Dy=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=li(),t=Oe(),r=Fe(),n=od(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:s}})=>(0,t.str)`must NOT have duplicate items (items ## ${s} and ${i} are identical)`,params:({params:{i,j:s}})=>(0,t._)`{i: ${i}, j: ${s}}`},code(i){const{gen:s,data:l,$data:c,schema:u,parentSchema:h,schemaCode:p,it:m}=i;if(!c&&!u)return;const f=s.let("valid"),b=h.items?(0,e.getSchemaTypes)(h.items):[];i.block$data(f,w,(0,t._)`${p} === false`),i.ok(f);function w(){const I=s.let("i",(0,t._)`${l}.length`),y=s.let("j");i.setParams({i:I,j:y}),s.assign(f,!0),s.if((0,t._)`${I} > 1`,()=>(C()?v:g)(I,y))}function C(){return b.length>0&&!b.some(I=>I==="object"||I==="array")}function v(I,y){const _=s.name("item"),k=(0,e.checkDataTypes)(b,_,m.opts.strictNumbers,e.DataType.Wrong),S=s.const("indices",(0,t._)`{}`);s.for((0,t._)`;${I}--;`,()=>{s.let(_,(0,t._)`${l}[${I}]`),s.if(k,(0,t._)`continue`),b.length>1&&s.if((0,t._)`typeof ${_} == "string"`,(0,t._)`${_} += "_"`),s.if((0,t._)`typeof ${S}[${_}] == "number"`,()=>{s.assign(y,(0,t._)`${S}[${_}]`),i.error(),s.assign(f,!1).break()}).code((0,t._)`${S}[${_}] = ${I}`)})}function g(I,y){const _=(0,r.useFunc)(s,n.default),k=s.name("outer");s.label(k).for((0,t._)`;${I}--;`,()=>s.for((0,t._)`${y} = ${I}; ${y}--;`,()=>s.if((0,t._)`${_}(${l}[${I}], ${l}[${y}])`,()=>{i.error(),s.assign(f,!1).break(k)})))}}};return xi.default=a,xi}var $i={},Uy;function YE(){if(Uy)return $i;Uy=1,Object.defineProperty($i,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=od(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:a})=>(0,e._)`{allowedValue: ${a}}`},code(a){const{gen:i,data:s,$data:l,schemaCode:c,schema:u}=a;l||u&&typeof u=="object"?a.fail$data((0,e._)`!${(0,t.useFunc)(i,r.default)}(${s}, ${c})`):a.fail((0,e._)`${u} !== ${s}`)}};return $i.default=o,$i}var Ri={},zy;function QE(){if(zy)return Ri;zy=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=od(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:a})=>(0,e._)`{allowedValues: ${a}}`},code(a){const{gen:i,data:s,$data:l,schema:c,schemaCode:u,it:h}=a;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=h.opts.loopEnum;let m;const f=()=>m??(m=(0,t.useFunc)(i,r.default));let b;if(p||l)b=i.let("valid"),a.block$data(b,w);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=i.const("vSchema",u);b=(0,e.or)(...c.map((g,I)=>C(v,I)))}a.pass(b);function w(){i.assign(b,!1),i.forOf("v",u,v=>i.if((0,e._)`${f()}(${s}, ${v})`,()=>i.assign(b,!0).break()))}function C(v,g){const I=c[g];return typeof I=="object"&&I!==null?(0,e._)`${f()}(${s}, ${v}[${g}])`:(0,e._)`${s} === ${I}`}}};return Ri.default=o,Ri}var Fy;function XE(){if(Fy)return yi;Fy=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=FE(),t=VE(),r=HE(),n=BE(),o=JE(),a=GE(),i=WE(),s=KE(),l=YE(),c=QE(),u=[e.default,t.default,r.default,n.default,o.default,a.default,i.default,s.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return yi.default=u,yi}var Pi={},qo={},Vy;function Zy(){if(Vy)return qo;Vy=1,Object.defineProperty(qo,"__esModule",{value:!0}),qo.validateAdditionalItems=void 0;const e=Oe(),t=Fe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{parentSchema:i,it:s}=a,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(a,l)}};function o(a,i){const{gen:s,schema:l,data:c,keyword:u,it:h}=a;h.items=!0;const p=s.const("len",(0,e._)`${c}.length`);if(l===!1)a.setParams({len:i.length}),a.pass((0,e._)`${p} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(h,l)){const f=s.var("valid",(0,e._)`${p} <= ${i.length}`);s.if((0,e.not)(f),()=>m(f)),a.ok(f)}function m(f){s.forRange("i",i.length,p,b=>{a.subschema({keyword:u,dataProp:b,dataPropType:t.Type.Num},f),h.allErrors||s.if((0,e.not)(f),()=>s.break())})}}return qo.validateAdditionalItems=o,qo.default=n,qo}var Mi={},Lo={},Hy;function By(){if(Hy)return Lo;Hy=1,Object.defineProperty(Lo,"__esModule",{value:!0}),Lo.validateTuple=void 0;const e=Oe(),t=Fe(),r=Mr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){const{schema:i,it:s}=a;if(Array.isArray(i))return o(a,"additionalItems",i);s.items=!0,!(0,t.alwaysValidSchema)(s,i)&&a.ok((0,r.validateArray)(a))}};function o(a,i,s=a.schema){const{gen:l,parentSchema:c,data:u,keyword:h,it:p}=a;b(c),p.opts.unevaluated&&s.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,s.length,p.items));const m=l.name("valid"),f=l.const("len",(0,e._)`${u}.length`);s.forEach((w,C)=>{(0,t.alwaysValidSchema)(p,w)||(l.if((0,e._)`${f} > ${C}`,()=>a.subschema({keyword:h,schemaProp:C,dataProp:C},m)),a.ok(m))});function b(w){const{opts:C,errSchemaPath:v}=p,g=s.length,I=g===w.minItems&&(g===w.maxItems||w[i]===!1);if(C.strictTuples&&!I){const y=`"${h}" is ${g}-tuple, but minItems or maxItems/${i} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,y,C.strictTuples)}}}return Lo.validateTuple=o,Lo.default=n,Lo}var Jy;function e$(){if(Jy)return Mi;Jy=1,Object.defineProperty(Mi,"__esModule",{value:!0});const e=By(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Mi.default=t,Mi}var Oi={},Gy;function t$(){if(Gy)return Oi;Gy=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=Mr(),n=Zy(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,e.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,e._)`{limit: ${i}}`},code(i){const{schema:s,parentSchema:l,it:c}=i,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,s)&&(u?(0,n.validateAdditionalItems)(i,u):i.ok((0,r.validateArray)(i)))}};return Oi.default=a,Oi}var Ai={},Wy;function r$(){if(Wy)return Ai;Wy=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:a}})=>a===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${a} valid item(s)`,params:({params:{min:o,max:a}})=>a===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${a}}`},code(o){const{gen:a,schema:i,parentSchema:s,data:l,it:c}=o;let u,h;const{minContains:p,maxContains:m}=s;c.opts.next?(u=p===void 0?1:p,h=m):u=1;const f=a.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:h}),h===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(h!==void 0&&u>h){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,i)){let g=(0,e._)`${f} >= ${u}`;h!==void 0&&(g=(0,e._)`${g} && ${f} <= ${h}`),o.pass(g);return}c.items=!0;const b=a.name("valid");h===void 0&&u===1?C(b,()=>a.if(b,()=>a.break())):u===0?(a.let(b,!0),h!==void 0&&a.if((0,e._)`${l}.length > 0`,w)):(a.let(b,!1),w()),o.result(b,()=>o.reset());function w(){const g=a.name("_valid"),I=a.let("count",0);C(g,()=>a.if(g,()=>v(I)))}function C(g,I){a.forRange("i",0,f,y=>{o.subschema({keyword:"contains",dataProp:y,dataPropType:t.Type.Num,compositeRule:!0},g),I()})}function v(g){a.code((0,e._)`${g}++`),h===void 0?a.if((0,e._)`${g} >= ${u}`,()=>a.assign(b,!0).break()):(a.if((0,e._)`${g} > ${h}`,()=>a.assign(b,!1).break()),u===1?a.assign(b,!0):a.if((0,e._)`${g} >= ${u}`,()=>a.assign(b,!0)))}}};return Ai.default=n,Ai}var ad={},Ky;function n$(){return Ky||(Ky=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Oe(),r=Fe(),n=Mr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,t.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,t._)`{property: ${l},
|
|
93
|
-
missingProperty: ${h},
|
|
94
|
-
depsCount: ${c},
|
|
95
|
-
deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=a(l);i(l,c),s(l,u)}};function a({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const p=Array.isArray(l[h])?c:u;p[h]=l[h]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:h,it:p}=l;if(Object.keys(c).length===0)return;const m=u.let("missing");for(const f in c){const b=c[f];if(b.length===0)continue;const w=(0,n.propertyInData)(u,h,f,p.opts.ownProperties);l.setParams({property:f,depsCount:b.length,deps:b.join(", ")}),p.allErrors?u.if(w,()=>{for(const C of b)(0,n.checkReportMissingProp)(l,C)}):(u.if((0,t._)`${w} && (${(0,n.checkMissingProp)(l,b,m)})`),(0,n.reportMissingProp)(l,m),u.else())}}e.validatePropertyDeps=i;function s(l,c=l.schema){const{gen:u,data:h,keyword:p,it:m}=l,f=u.name("valid");for(const b in c)(0,r.alwaysValidSchema)(m,c[b])||(u.if((0,n.propertyInData)(u,h,b,m.opts.ownProperties),()=>{const w=l.subschema({keyword:p,schemaProp:b},f);l.mergeValidEvaluated(w,f)},()=>u.var(f,!0)),l.ok(f))}e.validateSchemaDeps=s,e.default=o})(ad)),ad}var Ni={},Yy;function o$(){if(Yy)return Ni;Yy=1,Object.defineProperty(Ni,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:a,schema:i,data:s,it:l}=o;if((0,t.alwaysValidSchema)(l,i))return;const c=a.name("valid");a.forIn("key",s,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),a.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||a.break()})}),o.ok(c)}};return Ni.default=n,Ni}var qi={},Qy;function Xy(){if(Qy)return qi;Qy=1,Object.defineProperty(qi,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=kn(),n=Fe(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,t._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:s,schema:l,parentSchema:c,data:u,errsCount:h,it:p}=i;if(!h)throw new Error("ajv implementation error");const{allErrors:m,opts:f}=p;if(p.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const b=(0,e.allSchemaProperties)(c.properties),w=(0,e.allSchemaProperties)(c.patternProperties);C(),i.ok((0,t._)`${h} === ${r.default.errors}`);function C(){s.forIn("key",u,_=>{!b.length&&!w.length?I(_):s.if(v(_),()=>I(_))})}function v(_){let k;if(b.length>8){const S=(0,n.schemaRefOrVal)(p,c.properties,"properties");k=(0,e.isOwnProperty)(s,S,_)}else b.length?k=(0,t.or)(...b.map(S=>(0,t._)`${_} === ${S}`)):k=t.nil;return w.length&&(k=(0,t.or)(k,...w.map(S=>(0,t._)`${(0,e.usePattern)(i,S)}.test(${_})`))),(0,t.not)(k)}function g(_){s.code((0,t._)`delete ${u}[${_}]`)}function I(_){if(f.removeAdditional==="all"||f.removeAdditional&&l===!1){g(_);return}if(l===!1){i.setParams({additionalProperty:_}),i.error(),m||s.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const k=s.name("valid");f.removeAdditional==="failing"?(y(_,k,!1),s.if((0,t.not)(k),()=>{i.reset(),g(_)})):(y(_,k),m||s.if((0,t.not)(k),()=>s.break()))}}function y(_,k,S){const E={keyword:"additionalProperties",dataProp:_,dataPropType:n.Type.Str};S===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(E,k)}}};return qi.default=a,qi}var Li={},ev;function a$(){if(ev)return Li;ev=1,Object.defineProperty(Li,"__esModule",{value:!0});const e=ui(),t=Mr(),r=Fe(),n=Xy(),o={keyword:"properties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,parentSchema:l,data:c,it:u}=a;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const h=(0,t.allSchemaProperties)(s);for(const w of h)u.definedProperties.add(w);u.opts.unevaluated&&h.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(h),u.props));const p=h.filter(w=>!(0,r.alwaysValidSchema)(u,s[w]));if(p.length===0)return;const m=i.name("valid");for(const w of p)f(w)?b(w):(i.if((0,t.propertyInData)(i,c,w,u.opts.ownProperties)),b(w),u.allErrors||i.else().var(m,!0),i.endIf()),a.it.definedProperties.add(w),a.ok(m);function f(w){return u.opts.useDefaults&&!u.compositeRule&&s[w].default!==void 0}function b(w){a.subschema({keyword:"properties",schemaProp:w,dataProp:w},m)}}};return Li.default=o,Li}var ji={},tv;function s$(){if(tv)return ji;tv=1,Object.defineProperty(ji,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=Fe(),n=Fe(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,data:l,parentSchema:c,it:u}=a,{opts:h}=u,p=(0,e.allSchemaProperties)(s),m=p.filter(I=>(0,r.alwaysValidSchema)(u,s[I]));if(p.length===0||m.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const f=h.strictSchema&&!h.allowMatchingProperties&&c.properties,b=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:w}=u;C();function C(){for(const I of p)f&&v(I),u.allErrors?g(I):(i.var(b,!0),g(I),i.if(b))}function v(I){for(const y in f)new RegExp(I).test(y)&&(0,r.checkStrictMode)(u,`property ${y} matches pattern ${I} (use allowMatchingProperties)`)}function g(I){i.forIn("key",l,y=>{i.if((0,t._)`${(0,e.usePattern)(a,I)}.test(${y})`,()=>{const _=m.includes(I);_||a.subschema({keyword:"patternProperties",schemaProp:I,dataProp:y,dataPropType:n.Type.Str},b),u.opts.unevaluated&&w!==!0?i.assign((0,t._)`${w}[${y}]`,!0):!_&&!u.allErrors&&i.if((0,t.not)(b),()=>i.break())})})}}};return ji.default=o,ji}var Di={},rv;function i$(){if(rv)return Di;rv=1,Object.defineProperty(Di,"__esModule",{value:!0});const e=Fe(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:a}=r;if((0,e.alwaysValidSchema)(a,o)){r.fail();return}const i=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return Di.default=t,Di}var Ui={},nv;function l$(){if(nv)return Ui;nv=1,Object.defineProperty(Ui,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Mr().validateUnion,error:{message:"must match a schema in anyOf"}};return Ui.default=t,Ui}var zi={},ov;function c$(){if(ov)return zi;ov=1,Object.defineProperty(zi,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:a,schema:i,parentSchema:s,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&s.discriminator)return;const c=i,u=a.let("valid",!1),h=a.let("passing",null),p=a.name("_valid");o.setParams({passing:h}),a.block(m),o.result(u,()=>o.reset(),()=>o.error(!0));function m(){c.forEach((f,b)=>{let w;(0,t.alwaysValidSchema)(l,f)?a.var(p,!0):w=o.subschema({keyword:"oneOf",schemaProp:b,compositeRule:!0},p),b>0&&a.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(h,(0,e._)`[${h}, ${b}]`).else(),a.if(p,()=>{a.assign(u,!0),a.assign(h,b),w&&o.mergeEvaluated(w,e.Name)})})}}};return zi.default=n,zi}var Fi={},av;function u$(){if(av)return Fi;av=1,Object.defineProperty(Fi,"__esModule",{value:!0});const e=Fe(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:a}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const i=n.name("valid");o.forEach((s,l)=>{if((0,e.alwaysValidSchema)(a,s))return;const c=r.subschema({keyword:"allOf",schemaProp:l},i);r.ok(i),r.mergeEvaluated(c)})}};return Fi.default=t,Fi}var Vi={},sv;function d$(){if(sv)return Vi;sv=1,Object.defineProperty(Vi,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:a})=>(0,e.str)`must match "${a.ifClause}" schema`,params:({params:a})=>(0,e._)`{failingKeyword: ${a.ifClause}}`},code(a){const{gen:i,parentSchema:s,it:l}=a;s.then===void 0&&s.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const h=i.let("valid",!0),p=i.name("_valid");if(m(),a.reset(),c&&u){const b=i.let("ifClause");a.setParams({ifClause:b}),i.if(p,f("then",b),f("else",b))}else c?i.if(p,f("then")):i.if((0,e.not)(p),f("else"));a.pass(h,()=>a.error(!0));function m(){const b=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);a.mergeEvaluated(b)}function f(b,w){return()=>{const C=a.subschema({keyword:b},p);i.assign(h,p),a.mergeValidEvaluated(C,h),w?i.assign(w,(0,e._)`${b}`):a.setParams({ifClause:b})}}}};function o(a,i){const s=a.schema[i];return s!==void 0&&!(0,t.alwaysValidSchema)(a,s)}return Vi.default=n,Vi}var Zi={},iv;function p$(){if(iv)return Zi;iv=1,Object.defineProperty(Zi,"__esModule",{value:!0});const e=Fe(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Zi.default=t,Zi}var lv;function h$(){if(lv)return Pi;lv=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Zy(),t=e$(),r=By(),n=t$(),o=r$(),a=n$(),i=o$(),s=Xy(),l=a$(),c=s$(),u=i$(),h=l$(),p=c$(),m=u$(),f=d$(),b=p$();function w(C=!1){const v=[u.default,h.default,p.default,m.default,f.default,b.default,i.default,s.default,a.default,l.default,c.default];return C?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return Pi.default=w,Pi}var Hi={},Bi={},cv;function f$(){if(cv)return Bi;cv=1,Object.defineProperty(Bi,"__esModule",{value:!0});const e=Oe(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:a,data:i,$data:s,schema:l,schemaCode:c,it:u}=n,{opts:h,errSchemaPath:p,schemaEnv:m,self:f}=u;if(!h.validateFormats)return;s?b():w();function b(){const C=a.scopeValue("formats",{ref:f.formats,code:h.code.formats}),v=a.const("fDef",(0,e._)`${C}[${c}]`),g=a.let("fType"),I=a.let("format");a.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>a.assign(g,(0,e._)`${v}.type || "string"`).assign(I,(0,e._)`${v}.validate`),()=>a.assign(g,(0,e._)`"string"`).assign(I,v)),n.fail$data((0,e.or)(y(),_()));function y(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${I}`}function _(){const k=m.$async?(0,e._)`(${v}.async ? await ${I}(${i}) : ${I}(${i}))`:(0,e._)`${I}(${i})`,S=(0,e._)`(typeof ${I} == "function" ? ${k} : ${I}.test(${i}))`;return(0,e._)`${I} && ${I} !== true && ${g} === ${o} && !${S}`}}function w(){const C=f.formats[l];if(!C){y();return}if(C===!0)return;const[v,g,I]=_(C);v===o&&n.pass(k());function y(){if(h.strictSchema===!1){f.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function _(S){const E=S instanceof RegExp?(0,e.regexpCode)(S):h.code.formats?(0,e._)`${h.code.formats}${(0,e.getProperty)(l)}`:void 0,R=a.scopeValue("formats",{key:l,ref:S,code:E});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,e._)`${R}.validate`]:["string",S,R]}function k(){if(typeof C=="object"&&!(C instanceof RegExp)&&C.async){if(!m.$async)throw new Error("async format in sync schema");return(0,e._)`await ${I}(${i})`}return typeof g=="function"?(0,e._)`${I}(${i})`:(0,e._)`${I}.test(${i})`}}}};return Bi.default=r,Bi}var uv;function m$(){if(uv)return Hi;uv=1,Object.defineProperty(Hi,"__esModule",{value:!0});const t=[f$().default];return Hi.default=t,Hi}var no={},dv;function g$(){return dv||(dv=1,Object.defineProperty(no,"__esModule",{value:!0}),no.contentVocabulary=no.metadataVocabulary=void 0,no.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],no.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),no}var pv;function _$(){if(pv)return mi;pv=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=zE(),t=XE(),r=h$(),n=m$(),o=g$(),a=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return mi.default=a,mi}var Ji={},qa={},hv;function y$(){if(hv)return qa;hv=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(qa.DiscrError=e={})),qa}var fv;function v$(){if(fv)return Ji;fv=1,Object.defineProperty(Ji,"__esModule",{value:!0});const e=Oe(),t=y$(),r=td(),n=hi(),o=Fe(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:s,tagName:l}})=>s===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:s,tag:l,tagName:c}})=>(0,e._)`{error: ${s}, tag: ${c}, tagValue: ${l}}`},code(s){const{gen:l,data:c,schema:u,parentSchema:h,it:p}=s,{oneOf:m}=h;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!m)throw new Error("discriminator: requires oneOf keyword");const b=l.let("valid",!1),w=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(f)}`);l.if((0,e._)`typeof ${w} == "string"`,()=>C(),()=>s.error(!1,{discrError:t.DiscrError.Tag,tag:w,tagName:f})),s.ok(b);function C(){const I=g();l.if(!1);for(const y in I)l.elseIf((0,e._)`${w} === ${y}`),l.assign(b,v(I[y]));l.else(),s.error(!1,{discrError:t.DiscrError.Mapping,tag:w,tagName:f}),l.endIf()}function v(I){const y=l.name("valid"),_=s.subschema({keyword:"oneOf",schemaProp:I},y);return s.mergeEvaluated(_,e.Name),y}function g(){var I;const y={},_=S(h);let k=!0;for(let x=0;x<m.length;x++){let N=m[x];if(N?.$ref&&!(0,o.schemaHasRulesButRef)(N,p.self.RULES)){const z=N.$ref;if(N=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,z),N instanceof r.SchemaEnv&&(N=N.schema),N===void 0)throw new n.default(p.opts.uriResolver,p.baseId,z)}const U=(I=N?.properties)===null||I===void 0?void 0:I[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);k=k&&(_||S(N)),E(U,x)}if(!k)throw new Error(`discriminator: "${f}" must be required`);return y;function S({required:x}){return Array.isArray(x)&&x.includes(f)}function E(x,N){if(x.const)R(x.const,N);else if(x.enum)for(const U of x.enum)R(U,N);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function R(x,N){if(typeof x!="string"||x in y)throw new Error(`discriminator: "${f}" values must be unique strings`);y[x]=N}}}};return Ji.default=i,Ji}const w$={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var mv;function gv(){return mv||(mv=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=jE(),n=_$(),o=v$(),a=w$,i=["/properties"],s="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(a,i):a;this.addMetaSchema(f,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=ui();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Oe();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=ed();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=hi();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(oi,oi.exports)),oi.exports}var b$=gv();const k$=Hl(b$);var Gi={exports:{}},sd={},_v;function T$(){return _v||(_v=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(x,N){return{validate:x,compare:N}}e.fullFormats={date:t(a,i),time:t(l(!0),c),"date-time":t(p(!0),m),"iso-time":t(l(),u),"iso-date-time":t(p(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:C,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:R,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:g,int32:{type:"number",validate:_},int64:{type:"number",validate:k},float:{type:"number",validate:S},double:{type:"number",validate:S},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,m),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(x){return x%4===0&&(x%100!==0||x%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(x){const N=n.exec(x);if(!N)return!1;const U=+N[1],z=+N[2],ee=+N[3];return z>=1&&z<=12&&ee>=1&&ee<=(z===2&&r(U)?29:o[z])}function i(x,N){if(x&&N)return x>N?1:x<N?-1:0}const s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(x){return function(U){const z=s.exec(U);if(!z)return!1;const ee=+z[1],Q=+z[2],se=+z[3],re=z[4],Se=z[5]==="-"?-1:1,H=+(z[6]||0),D=+(z[7]||0);if(H>23||D>59||x&&!re)return!1;if(ee<=23&&Q<=59&&se<60)return!0;const B=Q-D*Se,F=ee-H*Se-(B<0?1:0);return(F===23||F===-1)&&(B===59||B===-1)&&se<61}}function c(x,N){if(!(x&&N))return;const U=new Date("2020-01-01T"+x).valueOf(),z=new Date("2020-01-01T"+N).valueOf();if(U&&z)return U-z}function u(x,N){if(!(x&&N))return;const U=s.exec(x),z=s.exec(N);if(U&&z)return x=U[1]+U[2]+U[3],N=z[1]+z[2]+z[3],x>N?1:x<N?-1:0}const h=/t|\s/i;function p(x){const N=l(x);return function(z){const ee=z.split(h);return ee.length===2&&a(ee[0])&&N(ee[1])}}function m(x,N){if(!(x&&N))return;const U=new Date(x).valueOf(),z=new Date(N).valueOf();if(U&&z)return U-z}function f(x,N){if(!(x&&N))return;const[U,z]=x.split(h),[ee,Q]=N.split(h),se=i(U,ee);if(se!==void 0)return se||c(z,Q)}const b=/\/|:/,w=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function C(x){return b.test(x)&&w.test(x)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(x){return v.lastIndex=0,v.test(x)}const I=-2147483648,y=2**31-1;function _(x){return Number.isInteger(x)&&x<=y&&x>=I}function k(x){return Number.isInteger(x)}function S(){return!0}const E=/[^\\]\\Z/;function R(x){if(E.test(x))return!1;try{return new RegExp(x),!0}catch{return!1}}})(sd)),sd}var id={},yv;function C$(){return yv||(yv=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=gv(),r=Oe(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},a={message:({keyword:s,schemaCode:l})=>(0,r.str)`should be ${o[s].okStr} ${l}`,params:({keyword:s,schemaCode:l})=>(0,r._)`{comparison: ${o[s].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:a,code(s){const{gen:l,data:c,schemaCode:u,keyword:h,it:p}=s,{opts:m,self:f}=p;if(!m.validateFormats)return;const b=new t.KeywordCxt(p,f.RULES.all.format.definition,"format");b.$data?w():C();function w(){const g=l.scopeValue("formats",{ref:f.formats,code:m.code.formats}),I=l.const("fmt",(0,r._)`${g}[${b.schemaCode}]`);s.fail$data((0,r.or)((0,r._)`typeof ${I} != "object"`,(0,r._)`${I} instanceof RegExp`,(0,r._)`typeof ${I}.compare != "function"`,v(I)))}function C(){const g=b.schema,I=f.formats[g];if(!I||I===!0)return;if(typeof I!="object"||I instanceof RegExp||typeof I.compare!="function")throw new Error(`"${h}": format "${g}" does not define "compare" function`);const y=l.scopeValue("formats",{key:g,ref:I,code:m.code.formats?(0,r._)`${m.code.formats}${(0,r.getProperty)(g)}`:void 0});s.fail$data(v(y))}function v(g){return(0,r._)`${g}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const i=s=>(s.addKeyword(e.formatLimitDefinition),s);e.default=i})(id)),id}var vv;function S$(){return vv||(vv=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=T$(),n=C$(),o=Oe(),a=new o.Name("fullFormats"),i=new o.Name("fastFormats"),s=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,a),c;const[h,p]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,a],m=u.formats||r.formatNames;return l(c,m,h,p),u.keywords&&(0,n.default)(c),c};s.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,h,p){var m,f;(m=(f=c.opts.code).formats)!==null&&m!==void 0||(f.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const b of u)c.addFormat(b,h[b])}e.exports=t=s,Object.defineProperty(t,"__esModule",{value:!0}),t.default=s})(Gi,Gi.exports)),Gi.exports}var I$=S$();const x$=Hl(I$);function E$(){const e=new k$({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return x$(e),e}class $${constructor(t){this._ajv=t??E$()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class R${constructor(t){this._client=t}async*callToolStream(t,r=Sa,n){const o=this._client,a={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,a),s=o.getToolOutputValidator(t.name);for await(const l of i){if(l.type==="result"&&s){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Ce($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=s(c.structuredContent);if(!u.valid){yield{type:"error",error:new Ce($e.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof Ce){yield{type:"error",error:u};return}yield{type:"error",error:new Ce($e.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function P$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function M$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function Wi(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const a=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[o]=a.default),r[o]!==void 0&&Wi(a,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Wi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Wi(r,t)}}function O$(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Ki extends xE{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new $$,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",au,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ou,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Xc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new R$(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=EE(this._capabilities,t)}setRequestHandler(t,r){const o=B_(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let a;if(ni(o)){const s=o;a=s._zod?.def?.value??s.value}else{const s=o;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");const i=a;if(i==="elicitation/create"){const s=async(l,c)=>{const u=bn(lu,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new Ce($e.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:m}=O$(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new Ce($e.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!m)throw new Ce($e.InvalidParams,"Client does not support URL-mode elicitation requests");const f=await Promise.resolve(r(l,c));if(h.task){const v=bn(Ta,f);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new Ce($e.InvalidParams,`Invalid task creation result: ${g}`)}return v.data}const b=bn(cu,f);if(!b.success){const v=b.error instanceof Error?b.error.message:String(b.error);throw new Ce($e.InvalidParams,`Invalid elicitation result: ${v}`)}const w=b.data,C=h.mode==="form"?h.requestedSchema:void 0;if(h.mode==="form"&&w.action==="accept"&&w.content&&C&&this._capabilities.elicitation?.form?.applyDefaults)try{Wi(C,w.content)}catch{}return w};return super.setRequestHandler(t,s)}if(i==="sampling/createMessage"){const s=async(l,c)=>{const u=bn(su,l);if(!u.success){const w=u.error instanceof Error?u.error.message:String(u.error);throw new Ce($e.InvalidParams,`Invalid sampling request: ${w}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const w=bn(Ta,p);if(!w.success){const C=w.error instanceof Error?w.error.message:String(w.error);throw new Ce($e.InvalidParams,`Invalid task creation result: ${C}`)}return w.data}const f=h.tools||h.toolChoice?fg:iu,b=bn(f,p);if(!b.success){const w=b.error instanceof Error?b.error.message:String(b.error);throw new Ce($e.InvalidParams,`Invalid sampling result: ${w}`)}return b.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Ls,capabilities:this._capabilities,clientInfo:this._clientInfo}},Q2,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!RS.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){P$(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&M$(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Kn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},mg,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Kn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},cg,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},lg,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},og,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ag,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},sg,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Kn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Kn,r)}async callTool(t,r=Sa,n){if(this.isToolTaskRequired(t.name))throw new Ce($e.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),a=this.getToolOutputValidator(t.name);if(a){if(!o.structuredContent&&!o.isError)throw new Ce($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=a(o.structuredContent);if(!i.valid)throw new Ce($e.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Ce?i:new Ce($e.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},dg,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const a=TI.safeParse(n);if(!a.success)throw new Error(`Invalid ${t} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=a.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const h=await o();l(null,h)}catch(h){const p=h instanceof Error?h:new Error(String(h));l(p,null)}},u=()=>{if(s){const h=this._listChangedDebounceTimers.get(t);h&&clearTimeout(h);const p=setTimeout(c,s);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const A$="mcp";class wv{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,A$),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=Wn.parse(JSON.parse(n.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const jo=Or;(function(e,t){const r=Or,n=Or,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Yi,-118057+3521*-35+-2099*-233);const N$=()=>{const e=Or,t=Or,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(i,s){return i!==s},r[t(394)]=t(414),r.ktWqD=function(i,s){return i!==s},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let a=859*2+-3*-1039+-4835*1;for(;;){switch(o[a++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},q$=(e,t,r)=>{const n=Or,o=Or,a={};a.eOzBp=function(s,l){return s!==l},a.ooaJk="undefined",a[n(402)]=function(s,l){return s===l},a[n(421)]="function";const i=a;i[o(389)](typeof window,i.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&i.pTvSc(typeof e[o(423)],i[n(421)])&&e.postMessage(t,r)};class bv{constructor(t){this._port=t}async[jo(401)](){const t=jo,r=jo;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,a;const i=t;try{const s=Wn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,s,n[i(412)][i(428)])}catch(s){const l=new Error("MessageChannel failed to parse message: "+s);(a=this[i(383)])==null||a.call(this,l)}},this._port.onmessageerror=n=>{var o;const a=r,i=new Error("MessageChannel transport error: "+JSON[a(415)](n));(o=this.onerror)==null||o.call(this,i)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,a){return o instanceof a},cDUwk:function(o,a){return o(a)}};return new Promise((o,a)=>{var i;const s=Or,l=Or;try{const c={};c[s(404)]=r?.[s(404)];const u={};u[s(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[s(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(i=this.onerror)==null||i.call(this,u),a(u)}})}async close(){var t,r;const n=jo,o=jo;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class L$ extends bv{constructor(t,r=N$()){const n=jo,o={lSpBh:function(i,s,l,c){return i(s,l,c)}};super(),this._endpoint=t,this._globalObject=r;const a=new MessageChannel;this._port=a[n(410)],o[n(418)](q$,this._globalObject,{endpoint:this[n(397)]},[a[n(429)]])}}function Yi(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return Yi=function(){return e},Yi()}function Or(e,t){const r=Yi();return Or=function(n,o){return n=n-(17227+1*-16844),r[n]},Or(e,t)}(function(e,t){const r=Ke,n=Ke,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Qi,-411935*1+228107+208149*2);const j$=async(e,t,r)=>{var n;const o=Ke,a=Ke,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[a(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=a(477),i[a(436)]=a(478),i[a(442)]=o(437),i.dEmVs=o(465);const s=i,{id:l,method:c,params:u}=r;let h={};switch(c){case s.VRyiJ:h=await t.listTools(u);break;case s.VkPYu:h=await t.callTool(u);break;case s.fgMSD:h=await t.listResources(u);break;case s[a(466)]:h=await t.listResourceTemplates(u);break;case s.sthgI:h=await t[o(455)](u);break;case a(486):h=await t.subscribeResource(u);break;case o(410):h=await t.unsubscribeResource(u);break;case s[a(461)]:h=await t[a(414)](u);break;case s[o(412)]:h=await t[o(491)](u);break;case s[o(436)]:h=await t[o(478)]();break;case s.kkNqg:h=await t.complete(u);break;case o(464):h=await t.setLoggingLevel(u?.[a(443)]);break}const p={};p.result=h,p.jsonrpc=s[a(472)],p.id=l,await((n=e?.[a(488)])==null?void 0:n[o(460)](p))},D$=async(e,t,r)=>{var n;const o=Ke,a=Ke,i={};i[o(487)]=a(462),i.ypHTC="ping",i.fPExS=o(465);const s=i,{id:l,method:c,params:u}=r;let h={};switch(c){case"roots/list":const m={};m.method=c,m[a(446)]=u,h=await t[o(469)](m,_g);break;case"sampling/createMessage":const f={};f[o(481)]=c,f[o(446)]=u,h=await t.request(f,iu);break;case s[o(487)]:const b={};b.method=c,b[a(446)]=u,h=await t.request(b,cu);break;case s.ypHTC:const w={};w.method=c,h=await t.request(w,Kn);break}const p={};return p.result=h,p.jsonrpc=s.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),h};function Ke(e,t){const r=Qi();return Ke=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ke(e,t)}const U$=(e,t)=>{const r=Ke,n=Ke,o={vYlhn:function(i,s){return i===s},DhPFX:r(470),NYVNC:function(i,s,l,c){return i(s,l,c)},yfZbw:"2.0"},a=e._onrequest;e[n(463)]=async(i,s)=>{var l,c,u,h,p;const m=n,f=r,{id:b,method:w}=i;try{o[m(451)](w,o.DhPFX)?await a.call(e,i,s):await o[f(474)](j$,e,t,i)}catch(C){const{code:v,message:g,data:I}=C;try{if(v){const y={};y[f(485)]=v,y[m(422)]=g,y.data=I;const _={};_[f(448)]=y,_.jsonrpc=o[m(417)],_.id=b,await((l=e?.transport)==null?void 0:l[f(460)](_))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,C)}catch(y){(p=(h=e?.transport)==null?void 0:h.onerror)==null||p.call(h,y)}}}},z$=(e,t)=>{const r=Ke,n=Ke,o={};o[r(476)]=r(439),o[r(431)]=function(i,s){return i!==s},o.UPdQt="notifications/cancelled";const a=o;e[r(421)]=async i=>{var s,l;const c=r,u=n,{method:h,params:p}=i;if(h!==a[c(476)]&&(a.QWYMz(h,a.UPdQt)||p?.[u(490)]))try{await t[c(445)](i)}catch(m){(l=(s=e?.[c(488)])==null?void 0:s[c(480)])==null||l.call(s,m)}}},F$=(e,t)=>async r=>{var n,o,a,i,s;const l=Ke,c=Ke,u={TJhyV:function(h,p,m,f){return h(p,m,f)},MMNTY:l(465)};try{return await u.TJhyV(D$,e,t,r)}catch(h){const{code:p,message:m,data:f}=h;try{if(p){const b={};b.code=p,b[l(422)]=m,b[c(419)]=f;const w={};w[l(448)]=b,w[l(424)]=u.MMNTY,w.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](w))}else(a=(o=e?.transport)==null?void 0:o[l(480)])==null||a.call(o,h)}catch(b){(s=(i=e?.[l(488)])==null?void 0:i.onerror)==null||s.call(i,b)}}},V$=(e,t)=>async r=>{var n,o,a;const i=Ke,s=Ke,l={};l.xmcLM=function(p,m){return p!==m},l.xSWLt="notifications/initialized",l[i(420)]=s(453);const c=l,{method:u,params:h}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[s(420)])||h?.[s(490)]))try{const p={...r};p.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(p))}catch(p){(a=(o=e?.transport)==null?void 0:o.onerror)==null||a.call(o,p)}};function Qi(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return Qi=function(){return e},Qi()}const Z$=(e,t)=>async r=>{var n,o,a,i,s,l;const c=Ke,u=Ke,h={};h.kSvAZ=c(465);const p=h;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(m){const{code:f,message:b,data:w}=m;try{if(f){const C={};C.code=f,C.message=b,C.data=w;const v={};v.error=C,v[u(424)]=p.kSvAZ,v.id=r.id,await((o=e?.transport)==null?void 0:o.send(v))}else(i=(a=e?.transport)==null?void 0:a[c(480)])==null||i.call(a,m)}catch(C){(l=(s=e?.[c(488)])==null?void 0:s[u(480)])==null||l.call(s,C)}}},ld=()=>{const e=Ke,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ke;if(c){const h=[];for(const p of r)try{h.push(p(l,c))}catch{}for(const p of h)if(t.rgPZO(p,null))return p}else for(const h of r)try{t[u(427)](h,l)}catch{}},o=l=>{const c=Ke,u=Ke;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},a=l=>{const c=Ke,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Ke;r[l(430)]=-505*7+1322+2213},s={};return s.handleListener=n,s[e(447)]=o,s.removeListener=a,s.clearListener=i,s},H$=e=>{const t=Ke,r=Ke,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n[t(423)](ld);e._onresponse=o,e[r(438)]=a,e.removeResponseListener=i,e.clearResponseListener=s}{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n[t(489)](ld);e[t(432)]=o,e[r(473)]=a,e.removeRequestListener=i,e.clearRequestListener=s}{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n.jsmFN(ld);e.fallbackNotificationHandler=o,e[t(444)]=a,e.removeNotificationListener=i,e[r(426)]=s}},B$=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ke,o=Ke,a={HucXo:function(s,l){return s===l},HicFO:n(468),JMaxV:function(s){return s()},DclXr:function(s,l){return s(l)},UynHf:function(s,l){return s===l},yCyFn:function(s){return s()}},i=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),a.HucXo(typeof t,a.HicFO)&&a[n(435)](t),a[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),a.DclXr(H$,e),e[o(438)](s=>{const l=n;e.originalOnResponse[l(440)](e,s)}),a[n(429)](typeof r,a.HicFO)&&a[o(425)](r),e[o(444)](s=>{const l=o,{method:c}=s,u=i[l(483)](c);a[l(467)](typeof u,"function")&&u(s)})},J$=an;(function(e,t){const r=an,n=an,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Xi,995159+-6*-266138+-1619768);const G$=()=>{const e=an,t=an,r={};r.svuxn=function(o,a){return o&a},r.ZUPdr=function(o,a){return o===a},r[e(227)]=function(o,a){return o===a},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const a=e,i=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[a(225)](o,"x")?i:n[a(209)](i,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},W$=e=>{const t=an,r=an,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},Cn={};Cn[J$(211)]=G$,Cn.randomBytes=W$;function an(e,t){const r=Xi();return an=function(n,o){return n=n-(-7373+7187*1+395),r[n]},an(e,t)}function Xi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Xi=function(){return e},Xi()}function sn(e,t){const r=el();return sn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},sn(e,t)}const Ar=sn,La=sn;(function(e,t){const r=sn,n=sn,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(el,-4*308317+753182*2+658196);const K$=(e,t)=>{const r=sn,n=sn,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](U$,e,t),z$(e,t);const a=o[n(283)](F$,t,e),i=o[n(294)](Z$,t,e),s=o[r(277)](V$,t,e);t.addRequestListener(a),t.addResponseListener(i),t[n(287)](s),e.onclose=()=>{const l=r,c=n;t[l(247)](a),t.removeResponseListener(i),t[c(252)](s)}},cd=(e,t,r)=>{const n={QhPqi:function(i,s){return i instanceof s},AIICR:"close",Qalmc:function(i,s,l){return i(s,l)}},o=()=>{var i;n.QhPqi(r,Ys)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var s;(s=r[sn(295)])==null||s.close()})),n.Qalmc(K$,e,t)},a={};a.afterInit=o,n.Qalmc(B$,t,a)},kv=(e,t=Cn[Ar(299)]())=>{const r=Ar,n=Ar,o={RVabx:function(u,h,p){return u(h,p)},crCTs:"include"},a={};a["sse-session-id"]=t;const i=a,s={};s["sse-session-id"]=t;const l={};l.headers=s,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,h){const p=r,m=r,f=new Headers(h?.[p(268)]||{});Object.entries(i).forEach(([w,C])=>{f.set(w,C)});const b={...h};return b.headers=f,o[m(279)](fetch,u,b)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,i.Authorization=n(256)+e),c},Tv=(e,t=Cn[Ar(299)]())=>{const r=La,n=Ar,o={};o[r(271)]="include";const a=o,i={};i["stream-session-id"]=t;const s={};s[n(268)]=i,s.credentials=a[r(271)];const l={};l.requestInit=s;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},ud=async(e,t,r)=>{const n=Ar,o=Ar,a={rRtFD:function(s){return s()},ToRAF:function(s,l){return s instanceof l}},i=a[n(276)](r);try{return await e[o(260)](i),i}catch(s){if(a[n(275)](s,kr)){const l=await t();return await i[n(257)](l),await ud(e,t,r)}else throw s}},Cv=(e,t)=>{const r=La,n=La,o={};o[r(267)]=function(i,s){return i in s},o.timcZ="waitForOAuthCode",o[r(253)]=function(i,s){return i===s},o.ufiEQ=r(285),o[n(250)]=r(293);const a=o;if(a.oGmBG(a[r(258)],e))return e[n(278)];if(a[n(253)](typeof t,a.ufiEQ))return t;throw new Error(a.daYBw)};function el(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return el=function(){return e},el()}const Y$=async e=>{const t=La,r=Ar,n={GKDjq:function(E,R,x){return E(R,x)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(E){return E()},kdowC:function(E,R,x,N){return E(R,x,N)},KkViY:"sessionId"},{client:o,url:a,token:i,sessionId:s,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const m=p,f=s||Cn[r(299)](),b=n[t(289)](kv,i,f);if(c){const E={...b.requestInit,...c};E[r(268)]={...b[r(280)][t(268)],...c.headers},m.requestInit=E}else m.requestInit=b[t(280)];if(u){const E={...b[t(270)],...u};m.eventSourceInit=E}else m.eventSourceInit=b[t(270)];const w={};w[t(254)]=!0;const C={};C.roots=w,C[t(298)]={},C[r(303)]={};const v=C,g={};g.name=n[r(261)],g[t(288)]=n.mcbiU;const I={};I[t(251)]=v;const y=new Ki(g,I),_=()=>new Ys(new URL(a),m);let k=n[t(282)](_);if(l){const E=Cv(l,h);k=await n[t(263)](ud,y,E,_)}else await y.connect(k);cd(y,o,k),k.sessionId=k[r(274)].searchParams[t(297)](n.KkViY);const S={};return S.transport=k,S.sessionId=k[r(286)],S},Q$=async e=>{const t=La,r=Ar,n={wfHUn:function(E,R,x){return E(R,x)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(E){return E()},PdsSn:function(E,R,x,N){return E(R,x,N)}},{client:o,url:a,token:i,sessionId:s,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const m=p,f=s||Cn.randomUUID(),b=n[r(272)](Tv,i,f);if(c){const E={...b[t(280)],...c};E.headers={...b.requestInit[t(268)],...c.headers},m.requestInit=E}else m[r(280)]=b[r(280)];const w={};w[r(254)]=!0;const C={};C.roots=w,C[t(298)]={},C[t(303)]={};const v=C,g={};g.name=n[t(262)],g.version=n.omKPe;const I={};I.capabilities=v;const y=new Ki(g,I),_=()=>new Js(new URL(a),m);let k=n.rSiEq(_);if(l){const E=n[t(272)](Cv,l,h);k=await n[t(296)](ud,y,E,_)}else await y[t(260)](k);n.PdsSn(cd,y,o,k);const S={};return S.transport=k,S[r(286)]=k[r(286)],S},X$=async e=>{const t=Ar,r=Ar,n={eZwNI:function(C,v,g,I){return C(v,g,I)}},{client:o,url:a,token:i,sessionId:s}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,h={};h.name="mcp-socket-proxy-client",h.version=r(248);const p={};p[r(251)]=u;const m=new Ki(h,p),f=s||Cn[r(299)](),b=new wv(new URL(a+"?sessionId="+f+r(265)+i));await m.connect(b),n[t(259)](cd,m,o,b);const w={};return w.transport=b,w[r(286)]=f,w},Sn=Nr,ja=Nr;(function(e,t){const r=Nr,n=Nr,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(tl,1297719+-42747*-22+-1289197);function Nr(e,t){const r=tl();return Nr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Nr(e,t)}const eR=()=>Cn.randomBytes(-8746+-382*-23);class rP{constructor(t){const r=Nr,n=Nr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:a,state:i,redirectCallback:s,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=a,this[r(206)]=a.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=i||o.HbwOh(eR),this._redirectCallback=s||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,a,i,s;const l=Nr,c=Nr,u={};u[l(198)]="GET";const h=await fetch(t,u);!h.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+h[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(a=(o=this[l(207)]).reject)==null||a.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const m=await p.json();(s=(i=this._callBackPromise).resolve)==null||s.call(i,m.code)}async[Sn(191)](t,r){const n=Sn,o={};o.xAOmI="POST";const a=o,i={};i["Content-Type"]=n(217);const s={};return s.state=r,fetch(t,{method:a.xAOmI,headers:i,body:new URLSearchParams(s)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Nr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Sn(206)]}get[ja(190)](){return this._clientMetadata}[Sn(213)](){return this[Sn(197)]}[ja(218)](){return this[ja(200)]}[Sn(194)](t){this._clientInformation=t}tokens(){return this[ja(210)]}saveTokens(t){const r=ja;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Sn(212)](){const t=Sn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function tl(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return tl=function(){return e},tl()}(function(e,t){for(var r=nl,n=nl,o=e();;)try{var a=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(a===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(rl,262*-2438+1346066*-1+2*1373311);function rl(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return rl=function(){return e},rl()}function nl(e,t){var r=rl();return nl=function(n,o){n=n-287;var a=r[n];return a},nl(e,t)}const tR=e=>{const t=()=>typeof navigator>"u"?null:navigator.modelContextTesting||null;e.onmessage=async r=>{if(!r||typeof r!="object")return;const n=r.id,o=r.method;try{if(o==="initialize")await e.send({jsonrpc:"2.0",id:n,result:{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!0},logging:{}},serverInfo:{name:"browser-builtin-webmcp-proxy",version:"1.0.0"}}});else if(o!=="notifications/initialized")if(o==="ping"||o==="custom_ping")await e.send({jsonrpc:"2.0",id:n,result:{}});else if(o==="tools/list"){const a=t();if(a&&a.listTools){const s=(await a.listTools()).map(l=>{let c={};if(typeof l.inputSchema=="string")try{c=JSON.parse(l.inputSchema)}catch(u){console.error("Failed to parse inputSchema:",u)}else typeof l.inputSchema=="object"&&l.inputSchema!==null&&(c=l.inputSchema);return{name:l.name,description:l.description||"",inputSchema:{type:"object",properties:c.properties||{},required:c.required||[]}}});await e.send({jsonrpc:"2.0",id:n,result:{tools:s}})}else await e.send({jsonrpc:"2.0",id:n,result:{tools:[]}})}else if(o==="tools/call"){const a=t();if(a&&a.executeTool){if(!r.params||typeof r.params!="object"||!r.params.name){const u=new Error('Invalid params: "name" is required and params must be an object');throw u.code=-32602,u}const{name:i,arguments:s}=r.params,l=await a.executeTool(i,JSON.stringify(s||{})),c=l&&typeof l=="object"&&"content"in l?l:{content:[{type:"text",text:typeof l=="string"?l:JSON.stringify(l)}]};await e.send({jsonrpc:"2.0",id:n,result:c})}else{const i=new Error("executeTool not implemented in Browser built-in WebMCP");throw i.code=-32601,i}}else o==="logging/setLevel"?await e.send({jsonrpc:"2.0",id:n,result:{}}):o==="prompts/list"?await e.send({jsonrpc:"2.0",id:n,result:{prompts:[]}}):o==="resources/list"?await e.send({jsonrpc:"2.0",id:n,result:{resources:[]}}):n!==void 0&&await e.send({jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${o}`}})}catch(a){n!==void 0&&await e.send({jsonrpc:"2.0",id:n,error:{code:a.code||-32e3,message:a.message||String(a)}})}}};class rR{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ki(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=a=>{this.onerror?.(a)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:a,agent:i,builtin:s,onError:l}=t;if(i){const h={client:this.client,url:r,token:n,sessionId:o},p=a==="sse"?await Y$(h):a==="socket"?await X$(h):await Q$(h);return p.transport.onerror=async m=>{l?.(m)},s&&tR(p.transport),p}const c=new URL(r);let u;if(a==="channel"&&(u=new L$(r),await this.client.connect(u)),a==="sse"){const h=kv(n,o);u=new Ys(c,h),await this.client.connect(u)}if(a==="socket"&&(u=new wv(new URL(`${r}?sessionId=${o}&token=${n}`)),u.sessionId=o,await this.client.connect(u)),a==="stream"||typeof u>"u"){const h=Tv(n,o);u=new Js(c,h),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,Sa,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(lu,t)}onCreateMessage(t){this.client.setRequestHandler(su,t)}onListRoots(t){this.client.setRequestHandler(gg,t)}onToolListChanged(t){this.client.setNotificationHandler(au,t)}onPromptListChanged(t){this.client.setNotificationHandler(ou,t)}onResourceListChanged(t){this.client.setNotificationHandler(Xc,t)}onResourceUpdated(t){this.client.setNotificationHandler(ig,t)}onLoggingMessage(t){this.client.setNotificationHandler(hg,t)}async onPagehide(t){t.persisted||(nR(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const nR=e=>e instanceof Js,Sv=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:a}of r.tools){const i=async(s,l)=>e.callTool({name:n,arguments:s},{signal:l?.abortSignal});t[n]=Zl({description:o,inputSchema:Vn({...a,properties:a.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}},oR=async e=>{const t={};if(!e)return t;const r=e,n=r.listTools??r.getTools;if(!n)return t;const o=await n.call(r),a=Array.isArray(o)?o:[];for(const i of a){const{name:s,description:l}=i,c=i.inputSchema;let u={};if(typeof c=="string")try{u=JSON.parse(c)}catch(p){console.error("Failed to parse inputSchema in getBuiltinMcpTools:",p)}else typeof c=="object"&&c!==null&&(u=c);const h={type:"object",properties:u.properties??{},...u.required?{required:u.required}:{},additionalProperties:!1,...u};t[s]=Zl({description:l??"",inputSchema:Vn(h),async execute(p){if(!r.executeTool)throw new Error("navigator.modelContextTesting.executeTool is not available");return r.executeTool(s,JSON.stringify(p??{}))}})}return t};function aR(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
96
|
-
# 工具调用
|
|
97
|
-
|
|
98
|
-
你可以根据需要调用以下工具:
|
|
99
|
-
|
|
100
|
-
<tools>
|
|
101
|
-
`;return t.forEach(([n,o])=>{const a=o,i=a.description||"无描述",s=a.parameters||a.inputSchema||{};r+=`${JSON.stringify({name:n,description:i,parameters:s},null,2)}
|
|
102
|
-
`}),r+=`
|
|
103
|
-
</tools>
|
|
104
|
-
|
|
105
|
-
## 工具调用格式
|
|
106
|
-
|
|
107
|
-
要调用工具,请使用以下 XML 格式:
|
|
108
|
-
Thought: [你的思考过程]
|
|
109
|
-
<tool_call>
|
|
110
|
-
{"name": "toolName", "arguments": {"arg1": "value1"}}
|
|
111
|
-
</tool_call>
|
|
112
|
-
|
|
113
|
-
工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
|
|
114
|
-
|
|
115
|
-
## 使用示例
|
|
116
|
-
|
|
117
|
-
如果用户要求"获取今天的日期",你可以这样调用工具:
|
|
118
|
-
Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
|
|
119
|
-
<tool_call>{"name": "get-today", "arguments": {}}</tool_call>
|
|
120
|
-
|
|
121
|
-
然后等待工具返回结果(Observation),再根据结果给出最终答案。
|
|
122
|
-
|
|
123
|
-
## 任务完成
|
|
124
|
-
|
|
125
|
-
当任务完成或无法继续时,直接给出最终答案即可。
|
|
126
|
-
|
|
127
|
-
**重要提示**:
|
|
128
|
-
- 必须严格按照 XML 格式调用工具
|
|
129
|
-
- arguments 必须是有效的 JSON 格式
|
|
130
|
-
- 如果不需要调用工具,直接给出最终答案即可
|
|
131
|
-
`,r}function Iv(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),a=o.name||o.action||o.tool,i=o.arguments||o.args||o.input||{};if(a&&t[a])return{toolName:a,arguments:i}}catch{}return null}const sR={openai:Qg,deepseek:H_};class iR{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=sR[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type==="builtin"){const o=t.client;return{tools:()=>oR(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,a=o.headers?{headers:o.headers}:void 0;r=new Js(new URL(o.url),{requestInit:a})}else if("type"in t&&t.type==="sse"){const o=t,a=o.headers?{headers:o.headers}:void 0;r=new Ys(new URL(o.url),{requestInit:a})}else"type"in t&&t.type==="extension"?r=new CE(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await ES({transport:r});return o.__transport__=r,o}else{const o=new rR({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof Qs||r&&r instanceof bv)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const a=await this._createOneClient(o);return{serverName:n,client:a}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Sv(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const a=await this._getClientTools(o,n);return{serverName:n,tools:a}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const a=o&&typeof o=="object"?o:{};this.mcpTools[n]=a})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,a)=>({...o,...a}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=aR(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
132
|
-
${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const a=o,i=a.execute||a.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(r,{})}}catch(a){return{success:!1,error:a?.message||String(a)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const a=this._tempMergeTools(o.tools);if(Object.keys(a).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let s=[];o.message&&!o.messages?s.push({role:"user",content:o.message}):o.messages?s=[...o.messages]:s=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(a,l,o.system)},h=s[0]?.role==="system"?s:[u,...s];return t===Ec?this._chatReActStream(h,a,l,n,o):this._chatReActNonStream(h,a,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let a=0;const i=[];for(let s=r.length-1;s>=0;s--){const l=r[s];if(this._messageHasImage(l.content))if(a<n)i.unshift(l),a++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,a){let i=[...t];const s=t[0]?.role==="system"?t[0]:null,l=s?t.slice(1):t;let c=0;const u=a.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(s,l,u),{tools:m,...f}=a,w=(await s2({model:this.llm(n),messages:p,...f})).text,C={role:"assistant",content:w};l.push(C),i.push(C);const v=Iv(w,r);if(!v)return this.responseMessages=i,{text:w,response:{messages:i}};const g=await this._executeReActToolCall(v.toolName,v.arguments,r),_={role:"user",content:`<tool_response>
|
|
133
|
-
${g.success?JSON.stringify(g.result):`工具执行失败 - ${g.error}`}
|
|
134
|
-
</tool_response>`};l.push(_),i.push(_)}return this.responseMessages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,a){const i=this,s=this.llm(n);let l,c;const u=new Promise((p,m)=>{l=p,c=m});return{fullStream:new ReadableStream({async start(p){let m=[...t];const f=t[0]?.role==="system"?t[0]:null,b=f?t.slice(1):[...t];let w=0,C="";const v=a.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;w<o;){w++;const g=i._buildMessagesForModel(f,b,v),{tools:I,...y}=a;delete y.system,delete y.onFinish;const _=await Ec({...y,model:s,messages:g});let k="";for await(const Q of _.fullStream)Q.type==="text-delta"?(k+=Q.text||"",p.enqueue({type:"text-delta",text:Q.text})):Q.type==="text-start"?p.enqueue({type:"text-start"}):Q.type==="text-end"||Q.type==="finish-step"||Q.type==="finish"||Q.type==="start"||Q.type==="start-step"||p.enqueue(Q);C+=k;const S={role:"assistant",content:C};b.push(S),m.push(S);const E=Iv(C,r);if(!E){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m});return}if(E.toolName==="computer"&&E.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m});return}const R=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:R,toolName:E.toolName});const x=JSON.stringify(E.arguments,null,2);p.enqueue({type:"tool-input-delta",id:R,delta:x}),p.enqueue({type:"tool-input-end",id:R}),p.enqueue({type:"tool-call",toolCallId:R,toolName:E.toolName,input:E.arguments});const N=await i._executeReActToolCall(E.toolName,E.arguments,r);let U,z=N.result;if(N.success&&N.result&&typeof N.result=="object"&&N.result.screenshot){U=N.result.screenshot;const{screenshot:Q,...se}=N.result;z=se}let ee="";if(N.success){z&&Array.isArray(z.content)&&z.content.length>0&&z.content[0].text?ee=z.content[0].text:ee=JSON.stringify(z);let Q=`<tool_response>
|
|
135
|
-
${ee}
|
|
136
|
-
</tool_response>`;U&&(Q+=`
|
|
137
|
-
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:R,result:Q});const se=U?{role:"user",content:[{type:"text",text:Q},{type:"image",image:U}]}:{role:"user",content:Q};b.push(se),m.push(se),C=""}else ee=`工具执行失败 - ${N.error}`,p.enqueue({type:"tool-error",toolCallId:R,input:E.arguments,error:{message:ee}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m})}catch(g){p.error(g),c(g)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const a=o.tools||{},i=this._tempMergeTools(a,!1),s=()=>{const m=this._tempMergeTools(a,!1);Object.entries(m).forEach(([f,b])=>{i[f]=b}),Object.keys(i).forEach(f=>{f in m||delete i[f]})},l=o.prepareStep,c=async m=>{s();const f=this._getActiveToolNames(i),b=typeof l=="function"?await l(m):void 0,w=b&&typeof b=="object"?b:{};return{...w,activeTools:Array.isArray(w.activeTools)?w.activeTools.filter(C=>f.includes(C)):f}},u={model:this.llm(r),stopWhen:Sc(n),...o,tools:i,prepareStep:c,activeTools:this._getActiveToolNames(i)};let h=null;if(o.message&&!o.messages)h={role:"user",content:o.message},this.responseMessages.push(h),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const m=o.messages[o.messages.length-1];m.role==="user"&&(h=m)}const p=t(u);return p?.response?.then(m=>{const f=m.messages?.[0];h&&f?.role!=="user"&&this.responseMessages.push(h),this.responseMessages.push(...m.messages)}),p}async chat(t){return this._chat(s2,t)}async chatStream(t){return this._chat(Ec,t)}}var Do={},dd,xv;function lR(){return xv||(xv=1,dd=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),dd}var pd={},In={},Ev;function oo(){if(Ev)return In;Ev=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return In.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},In.getSymbolTotalCodewords=function(n){return t[n]},In.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},In.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},In.isKanjiModeEnabled=function(){return typeof e<"u"},In.toSJIS=function(n){return e(n)},In}var hd={},$v;function fd(){return $v||($v=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(hd)),hd}var md,Rv;function cR(){if(Rv)return md;Rv=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},md=e,md}var gd,Pv;function uR(){if(Pv)return gd;Pv=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const a=t*this.size+r;this.data[a]=n,o&&(this.reservedBit[a]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},gd=e,gd}var _d={},Mv;function dR(){return Mv||(Mv=1,(function(e){const t=oo().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,a=t(n),i=a===145?26:Math.ceil((a-13)/(2*o-2))*2,s=[a-7];for(let l=1;l<o-1;l++)s[l]=s[l-1]-i;return s.push(6),s.reverse()},e.getPositions=function(n){const o=[],a=e.getRowColCoords(n),i=a.length;for(let s=0;s<i;s++)for(let l=0;l<i;l++)s===0&&l===0||s===0&&l===i-1||s===i-1&&l===0||o.push([a[s],a[l]]);return o}})(_d)),_d}var yd={},Ov;function pR(){if(Ov)return yd;Ov=1;const e=oo().getSymbolSize,t=7;return yd.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},yd}var vd={},Av;function hR(){return Av||(Av=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const a=o.size;let i=0,s=0,l=0,c=null,u=null;for(let h=0;h<a;h++){s=l=0,c=u=null;for(let p=0;p<a;p++){let m=o.get(h,p);m===c?s++:(s>=5&&(i+=t.N1+(s-5)),c=m,s=1),m=o.get(p,h),m===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=m,l=1)}s>=5&&(i+=t.N1+(s-5)),l>=5&&(i+=t.N1+(l-5))}return i},e.getPenaltyN2=function(o){const a=o.size;let i=0;for(let s=0;s<a-1;s++)for(let l=0;l<a-1;l++){const c=o.get(s,l)+o.get(s,l+1)+o.get(s+1,l)+o.get(s+1,l+1);(c===4||c===0)&&i++}return i*t.N2},e.getPenaltyN3=function(o){const a=o.size;let i=0,s=0,l=0;for(let c=0;c<a;c++){s=l=0;for(let u=0;u<a;u++)s=s<<1&2047|o.get(c,u),u>=10&&(s===1488||s===93)&&i++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&i++}return i*t.N3},e.getPenaltyN4=function(o){let a=0;const i=o.data.length;for(let l=0;l<i;l++)a+=o.data[l];return Math.abs(Math.ceil(a*100/i/5)-10)*t.N4};function r(n,o,a){switch(n){case e.Patterns.PATTERN000:return(o+a)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return a%3===0;case e.Patterns.PATTERN011:return(o+a)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(a/3))%2===0;case e.Patterns.PATTERN101:return o*a%2+o*a%3===0;case e.Patterns.PATTERN110:return(o*a%2+o*a%3)%2===0;case e.Patterns.PATTERN111:return(o*a%3+(o+a)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,a){const i=a.size;for(let s=0;s<i;s++)for(let l=0;l<i;l++)a.isReserved(l,s)||a.xor(l,s,r(o,l,s))},e.getBestMask=function(o,a){const i=Object.keys(e.Patterns).length;let s=0,l=1/0;for(let c=0;c<i;c++){a(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,s=c)}return s}})(vd)),vd}var ol={},Nv;function qv(){if(Nv)return ol;Nv=1;const e=fd(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return ol.getBlocksCount=function(o,a){switch(a){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},ol.getTotalCodewordsCount=function(o,a){switch(a){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},ol}var wd={},Da={},Lv;function fR(){if(Lv)return Da;Lv=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),Da.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Da.exp=function(n){return e[n]},Da.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Da}var jv;function mR(){return jv||(jv=1,(function(e){const t=fR();e.mul=function(n,o){const a=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let s=0;s<o.length;s++)a[i+s]^=t.mul(n[i],o[s]);return a},e.mod=function(n,o){let a=new Uint8Array(n);for(;a.length-o.length>=0;){const i=a[0];for(let l=0;l<o.length;l++)a[l]^=t.mul(o[l],i);let s=0;for(;s<a.length&&a[s]===0;)s++;a=a.slice(s)}return a},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let a=0;a<n;a++)o=e.mul(o,new Uint8Array([1,t.exp(a)]));return o}})(wd)),wd}var bd,Dv;function gR(){if(Dv)return bd;Dv=1;const e=mR();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const a=e.mod(o,this.genPoly),i=this.degree-a.length;if(i>0){const s=new Uint8Array(this.degree);return s.set(a,i),s}return a},bd=t,bd}var kd={},Td={},Cd={},Uv;function zv(){return Uv||(Uv=1,Cd.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Cd}var Jr={},Fv;function Vv(){if(Fv)return Jr;Fv=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
138
|
-
]))+`;Jr.KANJI=new RegExp(r,"g"),Jr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Jr.BYTE=new RegExp(n,"g"),Jr.NUMERIC=new RegExp(e,"g"),Jr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),a=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Jr.testKanji=function(l){return o.test(l)},Jr.testNumeric=function(l){return a.test(l)},Jr.testAlphanumeric=function(l){return i.test(l)},Jr}var Zv;function ao(){return Zv||(Zv=1,(function(e){const t=zv(),r=Vv();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(a,i){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?a.ccBits[0]:i<27?a.ccBits[1]:a.ccBits[2]},e.getBestModeForData=function(a){return r.testNumeric(a)?e.NUMERIC:r.testAlphanumeric(a)?e.ALPHANUMERIC:r.testKanji(a)?e.KANJI:e.BYTE},e.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},e.isValid=function(a){return a&&a.bit&&a.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(a,i){if(e.isValid(a))return a;try{return n(a)}catch{return i}}})(Td)),Td}var Hv;function _R(){return Hv||(Hv=1,(function(e){const t=oo(),r=qv(),n=fd(),o=ao(),a=zv(),i=7973,s=t.getBCHDigit(i);function l(p,m,f){for(let b=1;b<=40;b++)if(m<=e.getCapacity(b,f,p))return b}function c(p,m){return o.getCharCountIndicator(p,m)+4}function u(p,m){let f=0;return p.forEach(function(b){const w=c(b.mode,m);f+=w+b.getBitsLength()}),f}function h(p,m){for(let f=1;f<=40;f++)if(u(p,f)<=e.getCapacity(f,m,o.MIXED))return f}e.from=function(m,f){return a.isValid(m)?parseInt(m,10):f},e.getCapacity=function(m,f,b){if(!a.isValid(m))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=o.BYTE);const w=t.getSymbolTotalCodewords(m),C=r.getTotalCodewordsCount(m,f),v=(w-C)*8;if(b===o.MIXED)return v;const g=v-c(b,m);switch(b){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(m,f){let b;const w=n.from(f,n.M);if(Array.isArray(m)){if(m.length>1)return h(m,w);if(m.length===0)return 1;b=m[0]}else b=m;return l(b.mode,b.getLength(),w)},e.getEncodedBits=function(m){if(!a.isValid(m)||m<7)throw new Error("Invalid QR Code version");let f=m<<12;for(;t.getBCHDigit(f)-s>=0;)f^=i<<t.getBCHDigit(f)-s;return m<<12|f}})(kd)),kd}var Sd={},Bv;function yR(){if(Bv)return Sd;Bv=1;const e=oo(),t=1335,r=21522,n=e.getBCHDigit(t);return Sd.getEncodedBits=function(a,i){const s=a.bit<<3|i;let l=s<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(s<<10|l)^r},Sd}var Id={},xd,Jv;function vR(){if(Jv)return xd;Jv=1;const e=ao();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,a,i;for(o=0;o+3<=this.data.length;o+=3)a=this.data.substr(o,3),i=parseInt(a,10),n.put(i,10);const s=this.data.length-o;s>0&&(a=this.data.substr(o),i=parseInt(a,10),n.put(i,s*3+1))},xd=t,xd}var Ed,Gv;function wR(){if(Gv)return Ed;Gv=1;const e=ao(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let a;for(a=0;a+2<=this.data.length;a+=2){let i=t.indexOf(this.data[a])*45;i+=t.indexOf(this.data[a+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[a]),6)},Ed=r,Ed}var $d,Wv;function bR(){if(Wv)return $d;Wv=1;const e=ao();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},$d=t,$d}var Rd,Kv;function kR(){if(Kv)return Rd;Kv=1;const e=ao(),t=oo();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let a=t.toSJIS(this.data[o]);if(a>=33088&&a<=40956)a-=33088;else if(a>=57408&&a<=60351)a-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
|
|
139
|
-
Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),n.put(a,13)}},Rd=r,Rd}var Pd={exports:{}},Yv;function TR(){return Yv||(Yv=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var a={},i={};i[n]=0;var s=t.PriorityQueue.make();s.push(n,0);for(var l,c,u,h,p,m,f,b,w;!s.empty();){l=s.pop(),c=l.value,h=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(m=p[u],f=h+m,b=i[u],w=typeof i[u]>"u",(w||b>f)&&(i[u]=f,s.push(u,f),a[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var C=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(C)}return a},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],a=n;a;)o.push(a),r[a],a=r[a];return o.reverse(),o},find_path:function(r,n,o){var a=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(a,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},a;r=r||{};for(a in n)n.hasOwnProperty(a)&&(o[a]=n[a]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Pd)),Pd.exports}var Qv;function CR(){return Qv||(Qv=1,(function(e){const t=ao(),r=vR(),n=wR(),o=bR(),a=kR(),i=Vv(),s=oo(),l=TR();function c(C){return unescape(encodeURIComponent(C)).length}function u(C,v,g){const I=[];let y;for(;(y=C.exec(g))!==null;)I.push({data:y[0],index:y.index,mode:v,length:y[0].length});return I}function h(C){const v=u(i.NUMERIC,t.NUMERIC,C),g=u(i.ALPHANUMERIC,t.ALPHANUMERIC,C);let I,y;return s.isKanjiModeEnabled()?(I=u(i.BYTE,t.BYTE,C),y=u(i.KANJI,t.KANJI,C)):(I=u(i.BYTE_KANJI,t.BYTE,C),y=[]),v.concat(g,I,y).sort(function(k,S){return k.index-S.index}).map(function(k){return{data:k.data,mode:k.mode,length:k.length}})}function p(C,v){switch(v){case t.NUMERIC:return r.getBitsLength(C);case t.ALPHANUMERIC:return n.getBitsLength(C);case t.KANJI:return a.getBitsLength(C);case t.BYTE:return o.getBitsLength(C)}}function m(C){return C.reduce(function(v,g){const I=v.length-1>=0?v[v.length-1]:null;return I&&I.mode===g.mode?(v[v.length-1].data+=g.data,v):(v.push(g),v)},[])}function f(C){const v=[];for(let g=0;g<C.length;g++){const I=C[g];switch(I.mode){case t.NUMERIC:v.push([I,{data:I.data,mode:t.ALPHANUMERIC,length:I.length},{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.ALPHANUMERIC:v.push([I,{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.KANJI:v.push([I,{data:I.data,mode:t.BYTE,length:c(I.data)}]);break;case t.BYTE:v.push([{data:I.data,mode:t.BYTE,length:c(I.data)}])}}return v}function b(C,v){const g={},I={start:{}};let y=["start"];for(let _=0;_<C.length;_++){const k=C[_],S=[];for(let E=0;E<k.length;E++){const R=k[E],x=""+_+E;S.push(x),g[x]={node:R,lastCount:0},I[x]={};for(let N=0;N<y.length;N++){const U=y[N];g[U]&&g[U].node.mode===R.mode?(I[U][x]=p(g[U].lastCount+R.length,R.mode)-p(g[U].lastCount,R.mode),g[U].lastCount+=R.length):(g[U]&&(g[U].lastCount=R.length),I[U][x]=p(R.length,R.mode)+4+t.getCharCountIndicator(R.mode,v))}}y=S}for(let _=0;_<y.length;_++)I[y[_]].end=0;return{map:I,table:g}}function w(C,v){let g;const I=t.getBestModeForData(C);if(g=t.from(v,I),g!==t.BYTE&&g.bit<I.bit)throw new Error('"'+C+'" cannot be encoded with mode '+t.toString(g)+`.
|
|
140
|
-
Suggested mode is: `+t.toString(I));switch(g===t.KANJI&&!s.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new r(C);case t.ALPHANUMERIC:return new n(C);case t.KANJI:return new a(C);case t.BYTE:return new o(C)}}e.fromArray=function(v){return v.reduce(function(g,I){return typeof I=="string"?g.push(w(I,null)):I.data&&g.push(w(I.data,I.mode)),g},[])},e.fromString=function(v,g){const I=h(v,s.isKanjiModeEnabled()),y=f(I),_=b(y,g),k=l.find_path(_.map,"start","end"),S=[];for(let E=1;E<k.length-1;E++)S.push(_.table[k[E]].node);return e.fromArray(m(S))},e.rawSplit=function(v){return e.fromArray(h(v,s.isKanjiModeEnabled()))}})(Id)),Id}var Xv;function SR(){if(Xv)return pd;Xv=1;const e=oo(),t=fd(),r=cR(),n=uR(),o=dR(),a=pR(),i=hR(),s=qv(),l=gR(),c=_R(),u=yR(),h=ao(),p=CR();function m(_,k){const S=_.size,E=a.getPositions(k);for(let R=0;R<E.length;R++){const x=E[R][0],N=E[R][1];for(let U=-1;U<=7;U++)if(!(x+U<=-1||S<=x+U))for(let z=-1;z<=7;z++)N+z<=-1||S<=N+z||(U>=0&&U<=6&&(z===0||z===6)||z>=0&&z<=6&&(U===0||U===6)||U>=2&&U<=4&&z>=2&&z<=4?_.set(x+U,N+z,!0,!0):_.set(x+U,N+z,!1,!0))}}function f(_){const k=_.size;for(let S=8;S<k-8;S++){const E=S%2===0;_.set(S,6,E,!0),_.set(6,S,E,!0)}}function b(_,k){const S=o.getPositions(k);for(let E=0;E<S.length;E++){const R=S[E][0],x=S[E][1];for(let N=-2;N<=2;N++)for(let U=-2;U<=2;U++)N===-2||N===2||U===-2||U===2||N===0&&U===0?_.set(R+N,x+U,!0,!0):_.set(R+N,x+U,!1,!0)}}function w(_,k){const S=_.size,E=c.getEncodedBits(k);let R,x,N;for(let U=0;U<18;U++)R=Math.floor(U/3),x=U%3+S-8-3,N=(E>>U&1)===1,_.set(R,x,N,!0),_.set(x,R,N,!0)}function C(_,k,S){const E=_.size,R=u.getEncodedBits(k,S);let x,N;for(x=0;x<15;x++)N=(R>>x&1)===1,x<6?_.set(x,8,N,!0):x<8?_.set(x+1,8,N,!0):_.set(E-15+x,8,N,!0),x<8?_.set(8,E-x-1,N,!0):x<9?_.set(8,15-x-1+1,N,!0):_.set(8,15-x-1,N,!0);_.set(E-8,8,1,!0)}function v(_,k){const S=_.size;let E=-1,R=S-1,x=7,N=0;for(let U=S-1;U>0;U-=2)for(U===6&&U--;;){for(let z=0;z<2;z++)if(!_.isReserved(R,U-z)){let ee=!1;N<k.length&&(ee=(k[N]>>>x&1)===1),_.set(R,U-z,ee),x--,x===-1&&(N++,x=7)}if(R+=E,R<0||S<=R){R-=E,E=-E;break}}}function g(_,k,S){const E=new r;S.forEach(function(z){E.put(z.mode.bit,4),E.put(z.getLength(),h.getCharCountIndicator(z.mode,_)),z.write(E)});const R=e.getSymbolTotalCodewords(_),x=s.getTotalCodewordsCount(_,k),N=(R-x)*8;for(E.getLengthInBits()+4<=N&&E.put(0,4);E.getLengthInBits()%8!==0;)E.putBit(0);const U=(N-E.getLengthInBits())/8;for(let z=0;z<U;z++)E.put(z%2?17:236,8);return I(E,_,k)}function I(_,k,S){const E=e.getSymbolTotalCodewords(k),R=s.getTotalCodewordsCount(k,S),x=E-R,N=s.getBlocksCount(k,S),U=E%N,z=N-U,ee=Math.floor(E/N),Q=Math.floor(x/N),se=Q+1,re=ee-Q,Se=new l(re);let H=0;const D=new Array(N),B=new Array(N);let F=0;const $=new Uint8Array(_.buffer);for(let W=0;W<N;W++){const V=W<z?Q:se;D[W]=$.slice(H,H+V),B[W]=Se.encode(D[W]),H+=V,F=Math.max(F,V)}const O=new Uint8Array(E);let j=0,G,Y;for(G=0;G<F;G++)for(Y=0;Y<N;Y++)G<D[Y].length&&(O[j++]=D[Y][G]);for(G=0;G<re;G++)for(Y=0;Y<N;Y++)O[j++]=B[Y][G];return O}function y(_,k,S,E){let R;if(Array.isArray(_))R=p.fromArray(_);else if(typeof _=="string"){let ee=k;if(!ee){const Q=p.rawSplit(_);ee=c.getBestVersionForData(Q,S)}R=p.fromString(_,ee||40)}else throw new Error("Invalid data");const x=c.getBestVersionForData(R,S);if(!x)throw new Error("The amount of data is too big to be stored in a QR Code");if(!k)k=x;else if(k<x)throw new Error(`
|
|
141
|
-
The chosen QR Code version cannot contain this amount of data.
|
|
142
|
-
Minimum version required to store current data is: `+x+`.
|
|
143
|
-
`);const N=g(k,S,R),U=e.getSymbolSize(k),z=new n(U);return m(z,k),f(z),b(z,k),C(z,S,0),k>=7&&w(z,k),v(z,N),isNaN(E)&&(E=i.getBestMask(z,C.bind(null,z,S))),i.applyMask(E,z),C(z,S,E),{modules:z,version:k,errorCorrectionLevel:S,maskPattern:E,segments:R}}return pd.create=function(k,S){if(typeof k>"u"||k==="")throw new Error("No input text");let E=t.M,R,x;return typeof S<"u"&&(E=t.from(S.errorCorrectionLevel,t.M),R=c.from(S.version),x=i.from(S.maskPattern),S.toSJISFunc&&e.setToSJISFunction(S.toSJISFunc)),y(k,R,E,x)},pd}var Md={},Od={},e1;function t1(){return e1||(e1=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(a){return[a,a]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,a=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:a,scale:a?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const a=e.getScale(n,o);return Math.floor((n+o.margin*2)*a)},e.qrToImageData=function(n,o,a){const i=o.modules.size,s=o.modules.data,l=e.getScale(i,a),c=Math.floor((i+a.margin*2)*l),u=a.margin*l,h=[a.color.light,a.color.dark];for(let p=0;p<c;p++)for(let m=0;m<c;m++){let f=(p*c+m)*4,b=a.color.light;if(p>=u&&m>=u&&p<c-u&&m<c-u){const w=Math.floor((p-u)/l),C=Math.floor((m-u)/l);b=h[s[w*i+C]?1:0]}n[f++]=b.r,n[f++]=b.g,n[f++]=b.b,n[f]=b.a}}})(Od)),Od}var r1;function IR(){return r1||(r1=1,(function(e){const t=t1();function r(o,a,i){o.clearRect(0,0,a.width,a.height),a.style||(a.style={}),a.height=i,a.width=i,a.style.height=i+"px",a.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(a,i,s){let l=s,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(a.modules.size,l),h=c.getContext("2d"),p=h.createImageData(u,u);return t.qrToImageData(p.data,a,l),r(h,c,u),h.putImageData(p,0,0),c},e.renderToDataURL=function(a,i,s){let l=s;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(a,i,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}})(Md)),Md}var Ad={},n1;function xR(){if(n1)return Ad;n1=1;const e=t1();function t(o,a){const i=o.a/255,s=a+'="'+o.hex+'"';return i<1?s+" "+a+'-opacity="'+i.toFixed(2).slice(1)+'"':s}function r(o,a,i){let s=o+a;return typeof i<"u"&&(s+=" "+i),s}function n(o,a,i){let s="",l=0,c=!1,u=0;for(let h=0;h<o.length;h++){const p=Math.floor(h%a),m=Math.floor(h/a);!p&&!c&&(c=!0),o[h]?(u++,h>0&&p>0&&o[h-1]||(s+=c?r("M",p+i,.5+m+i):r("m",l,0),l=0,c=!1),p+1<a&&o[h+1]||(s+=r("h",u),u=0)):l++}return s}return Ad.render=function(a,i,s){const l=e.getOptions(i),c=a.modules.size,u=a.modules.data,h=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",m="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',f='viewBox="0 0 '+h+" "+h+'"',w='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+f+' shape-rendering="crispEdges">'+p+m+`</svg>
|
|
144
|
-
`;return typeof s=="function"&&s(null,w),w},Ad}var o1;function ER(){if(o1)return Do;o1=1;const e=lR(),t=SR(),r=IR(),n=xR();function o(a,i,s,l,c){const u=[].slice.call(arguments,1),h=u.length,p=typeof u[h-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(c=s,s=i,i=l=void 0):h===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=s,s=i,i=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(s=i,i=l=void 0):h===2&&!i.getContext&&(l=s,s=i,i=void 0),new Promise(function(m,f){try{const b=t.create(s,l);m(a(b,i,l))}catch(b){f(b)}})}try{const m=t.create(s,l);c(null,a(m,i,l))}catch(m){c(m)}}return Do.create=t.create,Do.toCanvas=o.bind(null,r.render),Do.toDataURL=o.bind(null,r.renderToDataURL),Do.toString=o.bind(null,function(a,i,s){return n.render(a,s)}),Do}var $R=ER();const a1=Hl($R);class s1{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:a="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=a}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return a1.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return a1.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const RR={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class PR{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...RR,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
|
|
145
|
-
<div class="${this.opts.className}__arrow"></div>
|
|
146
|
-
<div class="${this.opts.className}__inner">${t}</div>
|
|
147
|
-
`}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,a=window.pageXOffset||document.documentElement.scrollLeft,i=6,[s,l="center"]=t.split("-");let c=0,u=0;return s==="top"?c=r.top+o-n.height-i:s==="bottom"?c=r.bottom+o+i:s==="left"?u=r.left+a-n.width-i:s==="right"&&(u=r.right+a+i),(s==="top"||s==="bottom")&&(l==="start"?u=r.left+a:l==="end"?u=r.right+a-n.width:u=(r.left+r.right)/2+a-n.width/2),(s==="left"||s==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,a=window.innerHeight,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.height<=a-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const i1="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(i1))return;const e=document.createElement("style");e.id=i1,e.textContent=`
|
|
148
|
-
.tiny-remoter-native-tooltip {
|
|
149
|
-
position: absolute;
|
|
150
|
-
z-index: 9999;
|
|
151
|
-
max-width: 200px;
|
|
152
|
-
padding: 6px 10px;
|
|
153
|
-
font-size: 12px;
|
|
154
|
-
line-height: 1.4;
|
|
155
|
-
color: #fff;
|
|
156
|
-
background: #191919;
|
|
157
|
-
border-radius: 4px;
|
|
158
|
-
pointer-events: none;
|
|
159
|
-
box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
|
|
160
|
-
}
|
|
161
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
162
|
-
position: absolute;
|
|
163
|
-
width: 0; height: 0;
|
|
164
|
-
border: 6px solid transparent;
|
|
165
|
-
}
|
|
166
|
-
.tiny-remoter-native-tooltip--top
|
|
167
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
168
|
-
bottom: -12px;
|
|
169
|
-
left: 50%; transform:
|
|
170
|
-
translateX(-50%);
|
|
171
|
-
border-top-color: rgba(0,0,0,.75);
|
|
172
|
-
}
|
|
173
|
-
.tiny-remoter-native-tooltip--bottom
|
|
174
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
175
|
-
top: -12px;
|
|
176
|
-
left: 50%; transform:
|
|
177
|
-
translateX(-50%);
|
|
178
|
-
border-bottom-color: rgba(0,0,0,.75);
|
|
179
|
-
}
|
|
180
|
-
.tiny-remoter-native-tooltip--left
|
|
181
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
182
|
-
right: -12px;
|
|
183
|
-
top: 50%;
|
|
184
|
-
transform: translateY(-50%);
|
|
185
|
-
border-left-color: rgba(0,0,0,.75);
|
|
186
|
-
}
|
|
187
|
-
.tiny-remoter-native-tooltip--right
|
|
188
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
189
|
-
left: -12px;
|
|
190
|
-
top: 50%;
|
|
191
|
-
transform: translateY(-50%);
|
|
192
|
-
border-right-color: rgba(0,0,0,.75);
|
|
193
|
-
}
|
|
194
|
-
`,document.head.appendChild(e)})();const l1="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",c1="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",u1="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",d1="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",MR="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",OR="data:image/svg+xml,%3csvg%20width='100.000000'%20height='100.000000'%20viewBox='0%200%20100%20100'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cdesc%3e%20Created%20with%20Pixso.%20%3c/desc%3e%3cdefs%3e%3cradialGradient%20gradientTransform='translate(67.5526%2065.1155)%20rotate(51.0683)%20scale(22.991%2020.6919)'%20cx='0.000000'%20cy='0.000000'%20r='1.000000'%20id='paint_radial_9_3036_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235ADDF8'/%3e%3cstop%20stop-color='%23AEBFFF'/%3e%3cstop%20offset='0.329153'%20stop-color='%231476FF'/%3e%3cstop%20offset='0.667785'%20stop-color='%23655AF8'/%3e%3cstop%20offset='0.868255'%20stop-color='%23948CFF'/%3e%3cstop%20offset='1.000000'%20stop-color='%23D25AF8'/%3e%3cstop%20offset='1.000000'%20stop-color='%235A8BF8'/%3e%3c/radialGradient%3e%3clinearGradient%20x1='69.000122'%20y1='85.000198'%20x2='69.500107'%20y2='70.500183'%20id='paint_linear_9_3039_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%23000000'%20stop-opacity='0.000000'/%3e%3cstop%20offset='1.000000'%20stop-color='%23000000'/%3e%3c/linearGradient%3e%3cradialGradient%20gradientTransform='translate(26.9999%2024.7118)%20rotate(38.3655)%20scale(77.7996%20109.496)'%20cx='0.000000'%20cy='0.000000'%20r='1.000000'%20id='paint_radial_9_3040_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235ADDF8'/%3e%3cstop%20stop-color='%23AEBFFF'/%3e%3cstop%20offset='0.329153'%20stop-color='%231476FF'/%3e%3cstop%20offset='0.667785'%20stop-color='%23655AF8'/%3e%3cstop%20offset='0.868255'%20stop-color='%23948CFF'/%3e%3cstop%20offset='1.000000'%20stop-color='%23D25AF8'/%3e%3cstop%20offset='1.000000'%20stop-color='%235A8BF8'/%3e%3c/radialGradient%3e%3c/defs%3e%3crect%20id='NEXT-LOGO-无背景渐变-左'%20width='100.000000'%20height='99.999939'%20fill='%23FFFFFF'%20fill-opacity='0'/%3e%3cmask%20id='mask9_3032'%20mask-type='alpha'%20maskUnits='userSpaceOnUse'%20x='0.000000'%20y='0.000061'%20width='99.999939'%20height='99.999939'%3e%3crect%20id='画板%201773'%20y='0.000061'%20width='99.999962'%20height='99.999947'%20fill='%23000000'%20fill-opacity='1.000000'/%3e%3c/mask%3e%3cg%20mask='url(%23mask9_3032)'%3e%3cpath%20id='矢量%201'%20d='M64.07%2081.01L64%2063L82%2063.07L67.51%2082.23C66.39%2083.71%2064.07%2082.9%2064.07%2081.01Z'%20fill='url(%23paint_radial_9_3036_0)'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3cg%20opacity='0.100000'%20style='mix-blend-mode:normal'%3e%3cpath%20id='矢量%201'%20d='M64.07%2081.01L64%2063L82%2063.07L67.51%2082.23C66.39%2083.71%2064.07%2082.9%2064.07%2081.01Z'%20fill='url(%23paint_linear_9_3039_0)'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3c/g%3e%3crect%20id='矩形%205'%20x='12.000000'%20y='19.000153'%20rx='26.999992'%20width='75.999977'%20height='53.999985'%20fill='url(%23paint_radial_9_3040_0)'%20fill-opacity='1.000000'/%3e%3crect%20id='矩形%205'%20x='12.500000'%20y='19.500153'%20rx='26.499992'%20width='74.999977'%20height='52.999985'%20fill='%23000000'%20fill-opacity='0'/%3e%3crect%20id='矩形%205'%20x='12.500000'%20y='19.500153'%20rx='26.499992'%20width='74.999977'%20height='52.999985'%20stroke='%23000000'%20stroke-opacity='0'%20stroke-width='1.000000'/%3e%3cpath%20id='path'%20d='M54.61%2059.06C55.78%2060.05%2057.1%2060.66%2058.57%2060.89C60.05%2061.12%2061.43%2061.04%2062.72%2060.65C64%2060.26%2065.96%2058.58%2065.96%2058.58C65.96%2058.58%2070.98%2054.73%2070.98%2045.61C70.98%2036.5%2066.5%2032.5%2066.5%2032.5C66.5%2032.5%2065.28%2031.31%2063.5%2031C61.71%2030.68%2060.57%2030.98%2059.34%2031.33C49.11%2034.23%2037.62%2034.33%2027.42%2031.33C26.19%2030.98%2025.09%2030.93%2024.11%2031.17C23.13%2031.42%2022.29%2031.89%2021.58%2032.59C18.35%2035.81%2017.12%2041.06%2017%2045.61C16.87%2050.09%2018.03%2055.24%2021.06%2058.54C21.96%2059.52%2023.02%2060.22%2024.22%2060.63C25.41%2061.04%2026.68%2061.12%2028.01%2060.89C29.34%2060.66%2030.52%2060.05%2031.54%2059.06C31.98%2058.62%2032.61%2058.07%2033.43%2057.4C34.24%2056.73%2035.16%2056.08%2036.21%2055.44C37.25%2054.8%2038.38%2054.25%2039.61%2053.8C40.84%2053.35%2042.09%2053.13%2043.38%2053.13C44.64%2053.13%2045.84%2053.36%2047%2053.83C48.15%2054.29%2049.21%2054.84%2050.18%2055.48C51.14%2056.12%2052%2056.78%2052.74%2057.45C53.49%2058.11%2054.11%2058.65%2054.61%2059.06Z'%20fill='%23FFFFFF'%20fill-opacity='1.000000'%20fill-rule='nonzero'/%3e%3crect%20id='矩形%20840'%20x='58.016602'%20y='38.000046'%20rx='2.000000'%20width='3.999999'%20height='11.999996'%20transform='rotate(1.39597%2058.016602%2038.000046)'%20fill='%231476FF'%20fill-opacity='1.000000'/%3e%3cpath%20id='合并'%20d='M28.97%2038C28.17%2037.97%2027.38%2038.42%2027.01%2039.19L23.2%2047.11C22.71%2048.13%2023.15%2049.34%2024.18%2049.81C25.22%2050.28%2026.45%2049.83%2026.94%2048.8L28.97%2044.59L30.99%2048.81C31.48%2049.83%2032.72%2050.28%2033.75%2049.81C34.79%2049.34%2035.23%2048.13%2034.74%2047.11L30.93%2039.19C30.56%2038.42%2029.78%2037.98%2028.97%2038Z'%20fill='%231476FF'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3c/g%3e%3c/svg%3e",AR="https://chat.opentiny.design",NR="https://ai.opentiny.design/next-remoter",qR=OR,LR=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:d1},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:l1},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:u1},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:c1}]};class jR{constructor(t){this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new PR(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||NR,remoteUrl:t.remoteUrl||AR,logoUrl:t.logoUrl||qR},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){const r={"qr-code":d1,"ai-chat":l1,"remote-url":u1,"remote-control":c1};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?LR(this.options):[]}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
|
|
195
|
-
<div class="tiny-remoter-floating-block__icon">
|
|
196
|
-
<img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
|
|
197
|
-
</div>
|
|
198
|
-
`,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(r=>r.show!==!1).map(r=>`
|
|
199
|
-
<div class="tiny-remoter-dropdown-item" data-action="${r.action}">
|
|
200
|
-
<div id="tiny-remoter-icon-item-${r.action}" class="tiny-remoter-dropdown-item__icon">
|
|
201
|
-
</div>
|
|
202
|
-
<div class="tiny-remoter-dropdown-item__content">
|
|
203
|
-
<div title="${r.tip}">${r.text}</div>
|
|
204
|
-
<div class="tiny-remoter-dropdown-item__desc-wrapper">
|
|
205
|
-
<div class="tiny-remoter-dropdown-item__desc ${r.active?"tiny-remoter-dropdown-item__desc--active":""} ${r.know?"tiny-remoter-dropdown-item__desc--know":""}">${r.desc??""}</div>
|
|
206
|
-
<div>
|
|
207
|
-
${r.showCopyIcon?`
|
|
208
|
-
<div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
|
|
209
|
-
<img src="${MR}"/>
|
|
210
|
-
</div>
|
|
211
|
-
`:""}
|
|
212
|
-
</div>
|
|
213
|
-
</div>
|
|
214
|
-
</div>
|
|
215
|
-
</div>
|
|
216
|
-
`).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const i=n.dataset.action;i&&this.handleAction(i);return}const a=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;a&&this.handleAction(a)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(a=>a.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new s1((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
|
|
217
|
-
<div style="text-align: center; padding: 32px;">
|
|
218
|
-
<!-- 二维码容器 - 添加渐变背景和阴影效果 -->
|
|
219
|
-
<div style="
|
|
220
|
-
width: 240px;
|
|
221
|
-
height: 240px;
|
|
222
|
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
|
223
|
-
margin: 0 auto 24px;
|
|
224
|
-
display: flex;
|
|
225
|
-
align-items: center;
|
|
226
|
-
justify-content: center;
|
|
227
|
-
border-radius: 20px;
|
|
228
|
-
box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
|
|
229
|
-
position: relative;
|
|
230
|
-
overflow: hidden;
|
|
231
|
-
">
|
|
232
|
-
<!-- 装饰性背景元素 -->
|
|
233
|
-
<div style="
|
|
234
|
-
position: absolute;
|
|
235
|
-
top: -50%;
|
|
236
|
-
left: -50%;
|
|
237
|
-
width: 200%;
|
|
238
|
-
height: 200%;
|
|
239
|
-
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
|
|
240
|
-
animation: rotate 20s linear infinite;
|
|
241
|
-
"></div>
|
|
242
|
-
|
|
243
|
-
<!-- 二维码图片容器 -->
|
|
244
|
-
<div style="
|
|
245
|
-
width: 200px;
|
|
246
|
-
height: 200px;
|
|
247
|
-
background: white;
|
|
248
|
-
border-radius: 16px;
|
|
249
|
-
padding: 16px;
|
|
250
|
-
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
|
|
251
|
-
position: relative;
|
|
252
|
-
z-index: 1;
|
|
253
|
-
">
|
|
254
|
-
<img src="${r}" alt="二维码" style="
|
|
255
|
-
width: 100%;
|
|
256
|
-
height: 100%;
|
|
257
|
-
object-fit: contain;
|
|
258
|
-
border-radius: 8px;
|
|
259
|
-
">
|
|
260
|
-
</div>
|
|
261
|
-
</div>
|
|
262
|
-
|
|
263
|
-
<!-- 标题文字 -->
|
|
264
|
-
<h3 style="
|
|
265
|
-
color: #333;
|
|
266
|
-
margin: 0 0 12px 0;
|
|
267
|
-
font-size: 20px;
|
|
268
|
-
font-weight: 600;
|
|
269
|
-
letter-spacing: 0.5px;
|
|
270
|
-
">扫描二维码</h3>
|
|
271
|
-
|
|
272
|
-
<!-- 描述文字 -->
|
|
273
|
-
<p style="
|
|
274
|
-
color: #666;
|
|
275
|
-
margin: 0 auto;
|
|
276
|
-
margin-bottom: 20px;
|
|
277
|
-
font-size: 14px;
|
|
278
|
-
line-height: 1.6;
|
|
279
|
-
max-width: 280px;
|
|
280
|
-
">请使用手机微信或者浏览器扫描二维码跳转到智能遥控器</p>
|
|
281
|
-
|
|
282
|
-
<!-- 提示图标和文字 -->
|
|
283
|
-
<div style="
|
|
284
|
-
display: flex;
|
|
285
|
-
align-items: center;
|
|
286
|
-
justify-content: center;
|
|
287
|
-
gap: 8px;
|
|
288
|
-
color: #999;
|
|
289
|
-
font-size: 12px;
|
|
290
|
-
">
|
|
291
|
-
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="opacity: 0.7;">
|
|
292
|
-
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/>
|
|
293
|
-
</svg>
|
|
294
|
-
<span>支持微信、浏览器等多种方式</span>
|
|
295
|
-
</div>
|
|
296
|
-
</div>
|
|
297
|
-
`);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(t,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
|
|
298
|
-
<div class="tiny-remoter-modal-overlay"></div>
|
|
299
|
-
<div class="tiny-remoter-modal-content">
|
|
300
|
-
<div class="tiny-remoter-modal-header">
|
|
301
|
-
<h3>${t}</h3>
|
|
302
|
-
<button class="tiny-remoter-modal-close">×</button>
|
|
303
|
-
</div>
|
|
304
|
-
<div class="tiny-remoter-modal-body">
|
|
305
|
-
${r}
|
|
306
|
-
</div>
|
|
307
|
-
</div>
|
|
308
|
-
`;const o=n.querySelector(".tiny-remoter-modal-close"),a=n.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(n)),a.addEventListener("click",()=>this.hideModal(n)),n}showModal(t){document.body.appendChild(t),setTimeout(()=>t.classList.add("show"),10)}hideModal(t){t.classList.remove("show"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},100)}addStyles(){const t=document.createElement("style");t.textContent=`
|
|
309
|
-
/* 浮动块样式 */
|
|
310
|
-
.tiny-remoter-floating-block {
|
|
311
|
-
position: fixed;
|
|
312
|
-
bottom: 30px;
|
|
313
|
-
right: 30px;
|
|
314
|
-
width: 60px;
|
|
315
|
-
height: 60px;
|
|
316
|
-
cursor: pointer;
|
|
317
|
-
display: flex;
|
|
318
|
-
align-items: center;
|
|
319
|
-
justify-content: center;
|
|
320
|
-
color: white;
|
|
321
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
322
|
-
z-index: 99;
|
|
323
|
-
overflow: hidden;
|
|
324
|
-
border-radius: 50%;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
.tiny-remoter-floating-block__icon {
|
|
328
|
-
transform: scale(0.8);
|
|
329
|
-
transition: transform 0.3s ease;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
.tiny-remoter-floating-block__icon:hover {
|
|
333
|
-
transform: scale(1.1);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
.tiny-remoter-floating-block.expanded .tiny-remoter-floating-block__icon {
|
|
337
|
-
transform: scale(1.1);
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/* 下拉菜单样式 */
|
|
341
|
-
.tiny-remoter-floating-dropdown {
|
|
342
|
-
position: fixed;
|
|
343
|
-
bottom: 100px;
|
|
344
|
-
right: 30px;
|
|
345
|
-
background: white;
|
|
346
|
-
border-radius: 18px;
|
|
347
|
-
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
|
|
348
|
-
padding: 24px 24px 0px 24px;
|
|
349
|
-
opacity: 0;
|
|
350
|
-
visibility: hidden;
|
|
351
|
-
transform: translateY(20px) scale(0.95);
|
|
352
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
353
|
-
z-index: 999;
|
|
354
|
-
min-width: 200px;
|
|
355
|
-
width: 223px;
|
|
356
|
-
height: auto;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
.tiny-remoter-floating-dropdown.show {
|
|
360
|
-
opacity: 1;
|
|
361
|
-
visibility: visible;
|
|
362
|
-
transform: translateY(0) scale(1);
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
.tiny-remoter-dropdown-item {
|
|
366
|
-
display: flex;
|
|
367
|
-
align-items: center;
|
|
368
|
-
border-radius: 12px;
|
|
369
|
-
cursor: pointer;
|
|
370
|
-
transition: all 0.2s ease;
|
|
371
|
-
color: #333;
|
|
372
|
-
margin-bottom: 24px;
|
|
373
|
-
height: 40px;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
.tiny-remoter-dropdown-item:last-child {
|
|
377
|
-
margin-bottom: 32px;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
.tiny-remoter-dropdown-item > span {
|
|
381
|
-
flex: 1;
|
|
382
|
-
overflow: hidden;
|
|
383
|
-
max-width: 120px;
|
|
384
|
-
text-overflow: ellipsis;
|
|
385
|
-
white-space: nowrap;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
.tiny-remoter-dropdown-item__icon {
|
|
389
|
-
display: flex;
|
|
390
|
-
align-items: center;
|
|
391
|
-
justify-content: center;
|
|
392
|
-
width: 40px;
|
|
393
|
-
height: 40px;
|
|
394
|
-
background: #f8f9fa;
|
|
395
|
-
border-radius: 8px;
|
|
396
|
-
color: #667eea;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
.tiny-remoter-dropdown-item__content {
|
|
400
|
-
flex: 1;
|
|
401
|
-
display: flex;
|
|
402
|
-
flex-direction: column;
|
|
403
|
-
gap: 4px;
|
|
404
|
-
overflow: hidden;
|
|
405
|
-
font-size: 12px;
|
|
406
|
-
margin-left: 16px;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
.tiny-remoter-dropdown-item__desc-wrapper {
|
|
410
|
-
display: flex;
|
|
411
|
-
align-items: center;
|
|
412
|
-
gap: 4px;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
.tiny-remoter-dropdown-item__desc {
|
|
416
|
-
color: #808080;
|
|
417
|
-
overflow: hidden;
|
|
418
|
-
white-space: nowrap;
|
|
419
|
-
text-overflow: ellipsis;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
.tiny-remoter-dropdown-item__desc--active {
|
|
423
|
-
color: #1476ff;
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
.tiny-remoter-dropdown-item__desc--know {
|
|
427
|
-
color: #191919;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/* 复制图标样式 */
|
|
431
|
-
.tiny-remoter-copy-icon {
|
|
432
|
-
display: flex;
|
|
433
|
-
align-items: center;
|
|
434
|
-
justify-content: center;
|
|
435
|
-
width: 24px;
|
|
436
|
-
height: 24px;
|
|
437
|
-
background: #f0f0f0;
|
|
438
|
-
border-radius: 6px;
|
|
439
|
-
color: #666;
|
|
440
|
-
cursor: pointer;
|
|
441
|
-
transition: all 0.2s ease;
|
|
442
|
-
opacity: 0.7;
|
|
443
|
-
margin-left: auto;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
.tiny-remoter-copy-icon:hover {
|
|
447
|
-
background: #e0e0e0;
|
|
448
|
-
color: #333;
|
|
449
|
-
opacity: 1;
|
|
450
|
-
transform: scale(1.1);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
.tiny-remoter-copy-icon:active {
|
|
454
|
-
transform: scale(0.95);
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
/* 弹窗样式 */
|
|
458
|
-
.tiny-remoter-floating-modal {
|
|
459
|
-
position: fixed;
|
|
460
|
-
top: 0;
|
|
461
|
-
left: 0;
|
|
462
|
-
width: 100%;
|
|
463
|
-
height: 100%;
|
|
464
|
-
z-index: 2000;
|
|
465
|
-
display: flex;
|
|
466
|
-
align-items: center;
|
|
467
|
-
justify-content: center;
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
.tiny-remoter-modal-overlay {
|
|
471
|
-
position: absolute;
|
|
472
|
-
top: 0;
|
|
473
|
-
left: 0;
|
|
474
|
-
width: 100%;
|
|
475
|
-
height: 100%;
|
|
476
|
-
background: rgba(0, 0, 0, 0.5);
|
|
477
|
-
backdrop-filter: blur(4px);
|
|
478
|
-
opacity: 0;
|
|
479
|
-
transition: opacity 0.3s ease;
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
.tiny-remoter-modal-content {
|
|
483
|
-
background: white;
|
|
484
|
-
border-radius: 16px;
|
|
485
|
-
box-shadow: 0 25px 80px rgba(0, 0, 0, 0.2);
|
|
486
|
-
max-width: 500px;
|
|
487
|
-
width: 90%;
|
|
488
|
-
max-height: 80vh;
|
|
489
|
-
overflow: hidden;
|
|
490
|
-
transform: scale(0.9) translateY(20px);
|
|
491
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
.tiny-remoter-floating-modal.show .tiny-remoter-modal-overlay {
|
|
495
|
-
opacity: 1;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
.tiny-remoter-floating-modal.show .tiny-remoter-modal-content {
|
|
499
|
-
transform: scale(1) translateY(0);
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
.tiny-remoter-modal-header {
|
|
503
|
-
display: flex;
|
|
504
|
-
align-items: center;
|
|
505
|
-
justify-content: space-between;
|
|
506
|
-
padding: 20px 24px;
|
|
507
|
-
border-bottom: 1px solid #f0f0f0;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
.tiny-remoter-modal-header h3 {
|
|
511
|
-
margin: 0;
|
|
512
|
-
font-size: 18px;
|
|
513
|
-
font-weight: 600;
|
|
514
|
-
color: #333;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
.tiny-remoter-modal-close {
|
|
518
|
-
background: none;
|
|
519
|
-
border: none;
|
|
520
|
-
font-size: 24px;
|
|
521
|
-
cursor: pointer;
|
|
522
|
-
color: #999;
|
|
523
|
-
padding: 0;
|
|
524
|
-
width: 32px;
|
|
525
|
-
height: 32px;
|
|
526
|
-
border-radius: 50%;
|
|
527
|
-
display: flex;
|
|
528
|
-
align-items: center;
|
|
529
|
-
justify-content: center;
|
|
530
|
-
transition: all 0.2s ease;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
.tiny-remoter-modal-close:hover {
|
|
534
|
-
background: #f5f5f5;
|
|
535
|
-
color: #666;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
.tiny-remoter-modal-body {
|
|
539
|
-
padding: 24px;
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
/* 二维码弹窗动画 */
|
|
543
|
-
@keyframes rotate {
|
|
544
|
-
from {
|
|
545
|
-
transform: rotate(0deg);
|
|
546
|
-
}
|
|
547
|
-
to {
|
|
548
|
-
transform: rotate(360deg);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/* 响应式设计 */
|
|
553
|
-
@media (max-width: 768px) {
|
|
554
|
-
.tiny-remoter-floating-block {
|
|
555
|
-
bottom: 20px;
|
|
556
|
-
right: 20px;
|
|
557
|
-
width: 56px;
|
|
558
|
-
height: 56px;
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
.tiny-remoter-floating-dropdown {
|
|
562
|
-
bottom: 90px;
|
|
563
|
-
right: 20px;
|
|
564
|
-
min-width: 180px;
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
.tiny-remoter-modal-content {
|
|
568
|
-
width: 95%;
|
|
569
|
-
margin: 20px;
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
/* 复制反馈提示样式 */
|
|
574
|
-
.tiny-remoter-copy-feedback {
|
|
575
|
-
position: fixed;
|
|
576
|
-
top: 50%;
|
|
577
|
-
left: 50%;
|
|
578
|
-
transform: translate(-50%, -50%);
|
|
579
|
-
background: rgba(0, 0, 0, 0.8);
|
|
580
|
-
color: white;
|
|
581
|
-
padding: 12px 24px;
|
|
582
|
-
border-radius: 8px;
|
|
583
|
-
font-size: 14px;
|
|
584
|
-
font-weight: 500;
|
|
585
|
-
z-index: 10000;
|
|
586
|
-
opacity: 0;
|
|
587
|
-
visibility: hidden;
|
|
588
|
-
transition: all 0.3s ease;
|
|
589
|
-
backdrop-filter: blur(4px);
|
|
590
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
.tiny-remoter-copy-feedback.show {
|
|
594
|
-
opacity: 1;
|
|
595
|
-
visibility: visible;
|
|
596
|
-
transform: translate(-50%, -50%) scale(1);
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
.tiny-remoter-copy-feedback.success {
|
|
600
|
-
background: rgba(34, 197, 94, 0.9);
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
.tiny-remoter-copy-feedback.error {
|
|
604
|
-
background: rgba(239, 68, 68, 0.9);
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
/* 深色主题支持 */
|
|
608
|
-
@media (prefers-color-scheme: dark) {
|
|
609
|
-
.tiny-remoter-floating-dropdown {
|
|
610
|
-
background: #1a1a1a;
|
|
611
|
-
color: white;
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
.tiny-remoter-dropdown-item {
|
|
615
|
-
color: white;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
.tiny-remoter-copy-icon {
|
|
620
|
-
background: #2a2a2a;
|
|
621
|
-
color: #ccc;
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
.tiny-remoter-copy-icon:hover {
|
|
625
|
-
background: #3a3a3a;
|
|
626
|
-
color: white;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
.tiny-remoter-modal-content {
|
|
630
|
-
background: #1a1a1a;
|
|
631
|
-
color: white;
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
.tiny-remoter-modal-header {
|
|
635
|
-
border-bottom-color: #333;
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
.tiny-remoter-modal-header h3 {
|
|
639
|
-
color: white;
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
`,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const DR=(e={})=>new jR(e);Kr.AgentModelProvider=iR,Kr.QrCode=s1,Kr.createRemoter=DR,Kr.getAISDKTools=Sv,Object.defineProperty(Kr,Symbol.toStringTag,{value:"Module"})}));
|