@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/index.umd.js
DELETED
|
@@ -1,1248 +0,0 @@
|
|
|
1
|
-
(function(e,t){typeof exports=="object"&&typeof module<"u"?t(exports):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebMCP={}))})(this,(function(exports){"use strict";function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ajv={exports:{}},core$1={},validate$1={},boolSchema={},errors={},codegen={},code$1={},hasRequiredCode$1;function requireCode$1(){return hasRequiredCode$1||(hasRequiredCode$1=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(g){if(super(),!e.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((m,S)=>`${m}${S}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((m,S)=>(S instanceof r&&(m[S.str]=(m[S.str]||0)+1),m),{})}}e._Code=n,e.nil=new n("");function o(w,...g){const m=[w[0]];let S=0;for(;S<g.length;)i(m,g[S]),m.push(w[++S]);return new n(m)}e._=o;const a=new n("+");function s(w,...g){const m=[f(w[0])];let S=0;for(;S<g.length;)m.push(a),i(m,g[S]),m.push(a,f(w[++S]));return l(m),new n(m)}e.str=s;function i(w,g){g instanceof n?w.push(...g._items):g instanceof r?w.push(g):w.push(d(g))}e.addCodeArg=i;function l(w){let g=1;for(;g<w.length-1;){if(w[g]===a){const m=c(w[g-1],w[g+1]);if(m!==void 0){w.splice(g-1,3,m);continue}w[g++]="+"}g++}}function c(w,g){if(g==='""')return w;if(w==='""')return g;if(typeof w=="string")return g instanceof r||w[w.length-1]!=='"'?void 0:typeof g!="string"?`${w.slice(0,-1)}${g}"`:g[0]==='"'?w.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(w instanceof r))return`"${w}${g.slice(1)}`}function u(w,g){return g.emptyStr()?w:w.emptyStr()?g:s`${w}${g}`}e.strConcat=u;function d(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:f(Array.isArray(w)?w.join(","):w)}function p(w){return new n(f(w))}e.stringify=p;function f(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=h;function b(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=b;function y(w){return new n(w.toString())}e.regexpCode=y})(code$1)),code$1}var scope={},hasRequiredScope;function requireScope(){return hasRequiredScope||(hasRequiredScope=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=requireCode$1();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,d;if(!((d=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||d===void 0)&&d.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:d}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${d}]`}}e.ValueScopeName=a;const s=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?s:t.nil}}get(){return this._scope}name(c){return new a(c,this._newName(c))}value(c,u){var d;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:f}=p,h=(d=u.key)!==null&&d!==void 0?d:u.ref;let b=this._values[f];if(b){const g=b.get(h);if(g)return g}else b=this._values[f]=new Map;b.set(h,p);const y=this._scope[f]||(this._scope[f]=[]),w=y.length;return y[w]=u.ref,p.setValue(u,{property:f,itemIndex:w}),p}getValue(c,u){const d=this._values[c];if(d)return d.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${c}${d.scopePath}`})}scopeCode(c=this._values,u,d){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,d)}_reduceValues(c,u,d={},p){let f=t.nil;for(const h in c){const b=c[h];if(!b)continue;const y=d[h]=d[h]||new Map;b.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let g=u(w);if(g){const m=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${m} ${w} = ${g};${this.opts._n}`}else if(g=p?.(w))f=(0,t._)`${f}${g}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(scope)),scope}var hasRequiredCodegen;function requireCodegen(){return hasRequiredCodegen||(hasRequiredCodegen=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=requireCode$1(),r=requireScope();var n=requireCode$1();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=requireScope();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(I,k){return this}}class s extends a{constructor(I,k,O){super(),this.varKind=I,this.name=k,this.rhs=O}render({es5:I,_n:k}){const O=I?r.varKinds.var:this.varKind,q=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${q};`+k}optimizeNames(I,k){if(I[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,I,k)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends a{constructor(I,k,O){super(),this.lhs=I,this.rhs=k,this.sideEffects=O}render({_n:I}){return`${this.lhs} = ${this.rhs};`+I}optimizeNames(I,k){if(!(this.lhs instanceof t.Name&&!I[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,I,k),this}get names(){const I=this.lhs instanceof t.Name?{}:{...this.lhs.names};return D(I,this.rhs)}}class l extends i{constructor(I,k,O,q){super(I,O,q),this.op=k}render({_n:I}){return`${this.lhs} ${this.op}= ${this.rhs};`+I}}class c extends a{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`${this.label}:`+I}}class u extends a{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`break${this.label?` ${this.label}`:""};`+I}}class d extends a{constructor(I){super(),this.error=I}render({_n:I}){return`throw ${this.error};`+I}get names(){return this.error.names}}class p extends a{constructor(I){super(),this.code=I}render({_n:I}){return`${this.code};`+I}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(I,k){return this.code=U(this.code,I,k),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends a{constructor(I=[]){super(),this.nodes=I}render(I){return this.nodes.reduce((k,O)=>k+O.render(I),"")}optimizeNodes(){const{nodes:I}=this;let k=I.length;for(;k--;){const O=I[k].optimizeNodes();Array.isArray(O)?I.splice(k,1,...O):O?I[k]=O:I.splice(k,1)}return I.length>0?this:void 0}optimizeNames(I,k){const{nodes:O}=this;let q=O.length;for(;q--;){const B=O[q];B.optimizeNames(I,k)||(K(I,B.names),O.splice(q,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((I,k)=>A(I,k.names),{})}}class h extends f{render(I){return"{"+I._n+super.render(I)+"}"+I._n}}class b extends f{}class y extends h{}y.kind="else";class w extends h{constructor(I,k){super(k),this.condition=I}render(I){let k=`if(${this.condition})`+super.render(I);return this.else&&(k+="else "+this.else.render(I)),k}optimizeNodes(){super.optimizeNodes();const I=this.condition;if(I===!0)return this.nodes;let k=this.else;if(k){const O=k.optimizeNodes();k=this.else=Array.isArray(O)?new y(O):O}if(k)return I===!1?k instanceof w?k:k.nodes:this.nodes.length?this:new w(G(I),k instanceof w?[k]:k.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,k){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(I,k),!!(super.optimizeNames(I,k)||this.else))return this.condition=U(this.condition,I,k),this}get names(){const I=super.names;return D(I,this.condition),this.else&&A(I,this.else.names),I}}w.kind="if";class g extends h{}g.kind="for";class m extends g{constructor(I){super(),this.iteration=I}render(I){return`for(${this.iteration})`+super.render(I)}optimizeNames(I,k){if(super.optimizeNames(I,k))return this.iteration=U(this.iteration,I,k),this}get names(){return A(super.names,this.iteration.names)}}class S extends g{constructor(I,k,O,q){super(),this.varKind=I,this.name=k,this.from=O,this.to=q}render(I){const k=I.es5?r.varKinds.var:this.varKind,{name:O,from:q,to:B}=this;return`for(${k} ${O}=${q}; ${O}<${B}; ${O}++)`+super.render(I)}get names(){const I=D(super.names,this.from);return D(I,this.to)}}class v extends g{constructor(I,k,O,q){super(),this.loop=I,this.varKind=k,this.name=O,this.iterable=q}render(I){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(I)}optimizeNames(I,k){if(super.optimizeNames(I,k))return this.iterable=U(this.iterable,I,k),this}get names(){return A(super.names,this.iterable.names)}}class _ extends h{constructor(I,k,O){super(),this.name=I,this.args=k,this.async=O}render(I){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(I)}}_.kind="func";class $ extends f{render(I){return"return "+super.render(I)}}$.kind="return";class T extends h{render(I){let k="try"+super.render(I);return this.catch&&(k+=this.catch.render(I)),this.finally&&(k+=this.finally.render(I)),k}optimizeNodes(){var I,k;return super.optimizeNodes(),(I=this.catch)===null||I===void 0||I.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames(I,k){var O,q;return super.optimizeNames(I,k),(O=this.catch)===null||O===void 0||O.optimizeNames(I,k),(q=this.finally)===null||q===void 0||q.optimizeNames(I,k),this}get names(){const I=super.names;return this.catch&&A(I,this.catch.names),this.finally&&A(I,this.finally.names),I}}class R extends h{constructor(I){super(),this.error=I}render(I){return`catch(${this.error})`+super.render(I)}}R.kind="catch";class x extends h{render(I){return"finally"+super.render(I)}}x.kind="finally";class E{constructor(I,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?`
|
|
2
|
-
`:""},this._extScope=I,this._scope=new r.Scope({parent:I}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name(I){return this._scope.name(I)}scopeName(I){return this._extScope.name(I)}scopeValue(I,k){const O=this._extScope.value(I,k);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(I,k){return this._extScope.getValue(I,k)}scopeRefs(I){return this._extScope.scopeRefs(I,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(I,k,O,q){const B=this._scope.toName(k);return O!==void 0&&q&&(this._constants[B.str]=O),this._leafNode(new s(I,B,O)),B}const(I,k,O){return this._def(r.varKinds.const,I,k,O)}let(I,k,O){return this._def(r.varKinds.let,I,k,O)}var(I,k,O){return this._def(r.varKinds.var,I,k,O)}assign(I,k,O){return this._leafNode(new i(I,k,O))}add(I,k){return this._leafNode(new l(I,e.operators.ADD,k))}code(I){return typeof I=="function"?I():I!==t.nil&&this._leafNode(new p(I)),this}object(...I){const k=["{"];for(const[O,q]of I)k.length>1&&k.push(","),k.push(O),(O!==q||this.opts.es5)&&(k.push(":"),(0,t.addCodeArg)(k,q));return k.push("}"),new t._Code(k)}if(I,k,O){if(this._blockNode(new w(I)),k&&O)this.code(k).else().code(O).endIf();else if(k)this.code(k).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(I){return this._elseNode(new w(I))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(I,k){return this._blockNode(I),k&&this.code(k).endFor(),this}for(I,k){return this._for(new m(I),k)}forRange(I,k,O,q,B=this.opts.es5?r.varKinds.var:r.varKinds.let){const F=this._scope.toName(I);return this._for(new S(B,F,k,O),()=>q(F))}forOf(I,k,O,q=r.varKinds.const){const B=this._scope.toName(I);if(this.opts.es5){const F=k instanceof t.Name?k:this.var("_arr",k);return this.forRange("_i",0,(0,t._)`${F}.length`,j=>{this.var(B,(0,t._)`${F}[${j}]`),O(B)})}return this._for(new v("of",q,B,k),()=>O(B))}forIn(I,k,O,q=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(I,(0,t._)`Object.keys(${k})`,O);const B=this._scope.toName(I);return this._for(new v("in",q,B,k),()=>O(B))}endFor(){return this._endBlockNode(g)}label(I){return this._leafNode(new c(I))}break(I){return this._leafNode(new u(I))}return(I){const k=new $;if(this._blockNode(k),this.code(I),k.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(I,k,O){if(!k&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const q=new T;if(this._blockNode(q),this.code(I),k){const B=this.name("e");this._currNode=q.catch=new R(B),k(B)}return O&&(this._currNode=q.finally=new x,this.code(O)),this._endBlockNode(R,x)}throw(I){return this._leafNode(new d(I))}block(I,k){return this._blockStarts.push(this._nodes.length),I&&this.code(I).endBlock(k),this}endBlock(I){const k=this._blockStarts.pop();if(k===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-k;if(O<0||I!==void 0&&O!==I)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${I} expected`);return this._nodes.length=k,this}func(I,k=t.nil,O,q){return this._blockNode(new _(I,k,O)),q&&this.code(q).endFunc(),this}endFunc(){return this._endBlockNode(_)}optimize(I=1){for(;I-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(I){return this._currNode.nodes.push(I),this}_blockNode(I){this._currNode.nodes.push(I),this._nodes.push(I)}_endBlockNode(I,k){const O=this._currNode;if(O instanceof I||k&&O instanceof k)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${k?`${I.kind}/${k.kind}`:I.kind}"`)}_elseNode(I){const k=this._currNode;if(!(k instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=k.else=I,this}get _root(){return this._nodes[0]}get _currNode(){const I=this._nodes;return I[I.length-1]}set _currNode(I){const k=this._nodes;k[k.length-1]=I}}e.CodeGen=E;function A(L,I){for(const k in I)L[k]=(L[k]||0)+(I[k]||0);return L}function D(L,I){return I instanceof t._CodeOrName?A(L,I.names):L}function U(L,I,k){if(L instanceof t.Name)return O(L);if(!q(L))return L;return new t._Code(L._items.reduce((B,F)=>(F instanceof t.Name&&(F=O(F)),F instanceof t._Code?B.push(...F._items):B.push(F),B),[]));function O(B){const F=k[B.str];return F===void 0||I[B.str]!==1?B:(delete I[B.str],F)}function q(B){return B instanceof t._Code&&B._items.some(F=>F instanceof t.Name&&I[F.str]===1&&k[F.str]!==void 0)}}function K(L,I){for(const k in I)L[k]=(L[k]||0)-(I[k]||0)}function G(L){return typeof L=="boolean"||typeof L=="number"||L===null?!L:(0,t._)`!${N(L)}`}e.not=G;const te=C(e.operators.AND);function X(...L){return L.reduce(te)}e.and=X;const ue=C(e.operators.OR);function V(...L){return L.reduce(ue)}e.or=V;function C(L){return(I,k)=>I===t.nil?k:k===t.nil?I:(0,t._)`${N(I)} ${L} ${N(k)}`}function N(L){return L instanceof t.Name?L:(0,t._)`(${L})`}})(codegen)),codegen}var util$1={},hasRequiredUtil;function requireUtil(){if(hasRequiredUtil)return util$1;hasRequiredUtil=1,Object.defineProperty(util$1,"__esModule",{value:!0}),util$1.checkStrictMode=util$1.getErrorPath=util$1.Type=util$1.useFunc=util$1.setEvaluated=util$1.evaluatedPropsToName=util$1.mergeEvaluated=util$1.eachItem=util$1.unescapeJsonPointer=util$1.escapeJsonPointer=util$1.escapeFragment=util$1.unescapeFragment=util$1.schemaRefOrVal=util$1.schemaHasRulesButRef=util$1.schemaHasRules=util$1.checkUnknownRules=util$1.alwaysValidSchema=util$1.toHash=void 0;const e=requireCodegen(),t=requireCode$1();function r(v){const _={};for(const $ of v)_[$]=!0;return _}util$1.toHash=r;function n(v,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(o(v,_),!a(_,v.self.RULES.all))}util$1.alwaysValidSchema=n;function o(v,_=v.schema){const{opts:$,self:T}=v;if(!$.strictSchema||typeof _=="boolean")return;const R=T.RULES.keywords;for(const x in _)R[x]||S(v,`unknown keyword: "${x}"`)}util$1.checkUnknownRules=o;function a(v,_){if(typeof v=="boolean")return!v;for(const $ in v)if(_[$])return!0;return!1}util$1.schemaHasRules=a;function s(v,_){if(typeof v=="boolean")return!v;for(const $ in v)if($!=="$ref"&&_.all[$])return!0;return!1}util$1.schemaHasRulesButRef=s;function i({topSchemaRef:v,schemaPath:_},$,T,R){if(!R){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return(0,e._)`${$}`}return(0,e._)`${v}${_}${(0,e.getProperty)(T)}`}util$1.schemaRefOrVal=i;function l(v){return d(decodeURIComponent(v))}util$1.unescapeFragment=l;function c(v){return encodeURIComponent(u(v))}util$1.escapeFragment=c;function u(v){return typeof v=="number"?`${v}`:v.replace(/~/g,"~0").replace(/\//g,"~1")}util$1.escapeJsonPointer=u;function d(v){return v.replace(/~1/g,"/").replace(/~0/g,"~")}util$1.unescapeJsonPointer=d;function p(v,_){if(Array.isArray(v))for(const $ of v)_($);else _(v)}util$1.eachItem=p;function f({mergeNames:v,mergeToName:_,mergeValues:$,resultToName:T}){return(R,x,E,A)=>{const D=E===void 0?x:E instanceof e.Name?(x instanceof e.Name?v(R,x,E):_(R,x,E),E):x instanceof e.Name?(_(R,E,x),x):$(x,E);return A===e.Name&&!(D instanceof e.Name)?T(R,D):D}}util$1.mergeEvaluated={props:f({mergeNames:(v,_,$)=>v.if((0,e._)`${$} !== true && ${_} !== undefined`,()=>{v.if((0,e._)`${_} === true`,()=>v.assign($,!0),()=>v.assign($,(0,e._)`${$} || {}`).code((0,e._)`Object.assign(${$}, ${_})`))}),mergeToName:(v,_,$)=>v.if((0,e._)`${$} !== true`,()=>{_===!0?v.assign($,!0):(v.assign($,(0,e._)`${$} || {}`),b(v,$,_))}),mergeValues:(v,_)=>v===!0?!0:{...v,..._},resultToName:h}),items:f({mergeNames:(v,_,$)=>v.if((0,e._)`${$} !== true && ${_} !== undefined`,()=>v.assign($,(0,e._)`${_} === true ? true : ${$} > ${_} ? ${$} : ${_}`)),mergeToName:(v,_,$)=>v.if((0,e._)`${$} !== true`,()=>v.assign($,_===!0?!0:(0,e._)`${$} > ${_} ? ${$} : ${_}`)),mergeValues:(v,_)=>v===!0?!0:Math.max(v,_),resultToName:(v,_)=>v.var("items",_)})};function h(v,_){if(_===!0)return v.var("props",!0);const $=v.var("props",(0,e._)`{}`);return _!==void 0&&b(v,$,_),$}util$1.evaluatedPropsToName=h;function b(v,_,$){Object.keys($).forEach(T=>v.assign((0,e._)`${_}${(0,e.getProperty)(T)}`,!0))}util$1.setEvaluated=b;const y={};function w(v,_){return v.scopeValue("func",{ref:_,code:y[_.code]||(y[_.code]=new t._Code(_.code))})}util$1.useFunc=w;var g;(function(v){v[v.Num=0]="Num",v[v.Str=1]="Str"})(g||(util$1.Type=g={}));function m(v,_,$){if(v instanceof e.Name){const T=_===g.Num;return $?T?(0,e._)`"[" + ${v} + "]"`:(0,e._)`"['" + ${v} + "']"`:T?(0,e._)`"/" + ${v}`:(0,e._)`"/" + ${v}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,e.getProperty)(v).toString():"/"+u(v)}util$1.getErrorPath=m;function S(v,_,$=v.opts.strictSchema){if($){if(_=`strict mode: ${_}`,$===!0)throw new Error(_);v.self.logger.warn(_)}}return util$1.checkStrictMode=S,util$1}var names={},hasRequiredNames;function requireNames(){if(hasRequiredNames)return names;hasRequiredNames=1,Object.defineProperty(names,"__esModule",{value:!0});const e=requireCodegen(),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 names.default=t,names}var hasRequiredErrors;function requireErrors(){return hasRequiredErrors||(hasRequiredErrors=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=requireCodegen(),r=requireUtil(),n=requireNames();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,g,m){const{it:S}=y,{gen:v,compositeRule:_,allErrors:$}=S,T=d(y,w,g);m??(_||$)?l(v,T):c(S,(0,t._)`[${T}]`)}e.reportError=o;function a(y,w=e.keywordError,g){const{it:m}=y,{gen:S,compositeRule:v,allErrors:_}=m,$=d(y,w,g);l(S,$),v||_||c(m,n.default.vErrors)}e.reportExtraError=a;function s(y,w){y.assign(n.default.errors,w),y.if((0,t._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,t._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}e.resetErrorsCount=s;function i({gen:y,keyword:w,schemaValue:g,data:m,errsCount:S,it:v}){if(S===void 0)throw new Error("ajv implementation error");const _=y.name("err");y.forRange("i",S,n.default.errors,$=>{y.const(_,(0,t._)`${n.default.vErrors}[${$}]`),y.if((0,t._)`${_}.instancePath === undefined`,()=>y.assign((0,t._)`${_}.instancePath`,(0,t.strConcat)(n.default.instancePath,v.errorPath))),y.assign((0,t._)`${_}.schemaPath`,(0,t.str)`${v.errSchemaPath}/${w}`),v.opts.verbose&&(y.assign((0,t._)`${_}.schema`,g),y.assign((0,t._)`${_}.data`,m))})}e.extendErrors=i;function l(y,w){const g=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${g}]`),(0,t._)`${n.default.vErrors}.push(${g})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:g,validateName:m,schemaEnv:S}=y;S.$async?g.throw((0,t._)`new ${y.ValidationError}(${w})`):(g.assign((0,t._)`${m}.errors`,w),g.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 d(y,w,g){const{createErrors:m}=y.it;return m===!1?(0,t._)`{}`:p(y,w,g)}function p(y,w,g={}){const{gen:m,it:S}=y,v=[f(S,g),h(y,g)];return b(y,w,v),m.object(...v)}function f({errorPath:y},{instancePath:w}){const g=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,g)]}function h({keyword:y,it:{errSchemaPath:w}},{schemaPath:g,parentSchema:m}){let S=m?w:(0,t.str)`${w}/${y}`;return g&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(g,r.Type.Str)}`),[u.schemaPath,S]}function b(y,{params:w,message:g},m){const{keyword:S,data:v,schemaValue:_,it:$}=y,{opts:T,propertyName:R,topSchemaRef:x,schemaPath:E}=$;m.push([u.keyword,S],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),T.messages&&m.push([u.message,typeof g=="function"?g(y):g]),T.verbose&&m.push([u.schema,_],[u.parentSchema,(0,t._)`${x}${E}`],[n.default.data,v]),R&&m.push([u.propertyName,R])}})(errors)),errors}var hasRequiredBoolSchema;function requireBoolSchema(){if(hasRequiredBoolSchema)return boolSchema;hasRequiredBoolSchema=1,Object.defineProperty(boolSchema,"__esModule",{value:!0}),boolSchema.boolOrEmptySchema=boolSchema.topBoolOrEmptySchema=void 0;const e=requireErrors(),t=requireCodegen(),r=requireNames(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?s(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}boolSchema.topBoolOrEmptySchema=o;function a(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),s(i)):c.var(l,!0)}boolSchema.boolOrEmptySchema=a;function s(i,l){const{gen:c,data:u}=i,d={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(d,n,void 0,l)}return boolSchema}var dataType={},rules={},hasRequiredRules;function requireRules(){if(hasRequiredRules)return rules;hasRequiredRules=1,Object.defineProperty(rules,"__esModule",{value:!0}),rules.getRules=rules.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)}rules.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 rules.getRules=n,rules}var applicability={},hasRequiredApplicability;function requireApplicability(){if(hasRequiredApplicability)return applicability;hasRequiredApplicability=1,Object.defineProperty(applicability,"__esModule",{value:!0}),applicability.shouldUseRule=applicability.shouldUseGroup=applicability.schemaHasRulesForType=void 0;function e({schema:n,self:o},a){const s=o.RULES.types[a];return s&&s!==!0&&t(n,s)}applicability.schemaHasRulesForType=e;function t(n,o){return o.rules.some(a=>r(n,a))}applicability.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(s=>n[s]!==void 0))}return applicability.shouldUseRule=r,applicability}var hasRequiredDataType;function requireDataType(){if(hasRequiredDataType)return dataType;hasRequiredDataType=1,Object.defineProperty(dataType,"__esModule",{value:!0}),dataType.reportTypeError=dataType.checkDataTypes=dataType.checkDataType=dataType.coerceAndCheckDataType=dataType.getJSONTypes=dataType.getSchemaTypes=dataType.DataType=void 0;const e=requireRules(),t=requireApplicability(),r=requireErrors(),n=requireCodegen(),o=requireUtil();var a;(function(g){g[g.Correct=0]="Correct",g[g.Wrong=1]="Wrong"})(a||(dataType.DataType=a={}));function s(g){const m=i(g.type);if(m.includes("null")){if(g.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!m.length&&g.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');g.nullable===!0&&m.push("null")}return m}dataType.getSchemaTypes=s;function i(g){const m=Array.isArray(g)?g:g?[g]:[];if(m.every(e.isJSONType))return m;throw new Error("type must be JSONType or JSONType[]: "+m.join(","))}dataType.getJSONTypes=i;function l(g,m){const{gen:S,data:v,opts:_}=g,$=u(m,_.coerceTypes),T=m.length>0&&!($.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(g,m[0]));if(T){const R=h(m,v,_.strictNumbers,a.Wrong);S.if(R,()=>{$.length?d(g,m,$):y(g)})}return T}dataType.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(g,m){return m?g.filter(S=>c.has(S)||m==="array"&&S==="array"):[]}function d(g,m,S){const{gen:v,data:_,opts:$}=g,T=v.let("dataType",(0,n._)`typeof ${_}`),R=v.let("coerced",(0,n._)`undefined`);$.coerceTypes==="array"&&v.if((0,n._)`${T} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>v.assign(_,(0,n._)`${_}[0]`).assign(T,(0,n._)`typeof ${_}`).if(h(m,_,$.strictNumbers),()=>v.assign(R,_))),v.if((0,n._)`${R} !== undefined`);for(const E of S)(c.has(E)||E==="array"&&$.coerceTypes==="array")&&x(E);v.else(),y(g),v.endIf(),v.if((0,n._)`${R} !== undefined`,()=>{v.assign(_,R),p(g,R)});function x(E){switch(E){case"string":v.elseIf((0,n._)`${T} == "number" || ${T} == "boolean"`).assign(R,(0,n._)`"" + ${_}`).elseIf((0,n._)`${_} === null`).assign(R,(0,n._)`""`);return;case"number":v.elseIf((0,n._)`${T} == "boolean" || ${_} === null
|
|
3
|
-
|| (${T} == "string" && ${_} && ${_} == +${_})`).assign(R,(0,n._)`+${_}`);return;case"integer":v.elseIf((0,n._)`${T} === "boolean" || ${_} === null
|
|
4
|
-
|| (${T} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(R,(0,n._)`+${_}`);return;case"boolean":v.elseIf((0,n._)`${_} === "false" || ${_} === 0 || ${_} === null`).assign(R,!1).elseIf((0,n._)`${_} === "true" || ${_} === 1`).assign(R,!0);return;case"null":v.elseIf((0,n._)`${_} === "" || ${_} === 0 || ${_} === false`),v.assign(R,null);return;case"array":v.elseIf((0,n._)`${T} === "string" || ${T} === "number"
|
|
5
|
-
|| ${T} === "boolean" || ${_} === null`).assign(R,(0,n._)`[${_}]`)}}}function p({gen:g,parentData:m,parentDataProperty:S},v){g.if((0,n._)`${m} !== undefined`,()=>g.assign((0,n._)`${m}[${S}]`,v))}function f(g,m,S,v=a.Correct){const _=v===a.Correct?n.operators.EQ:n.operators.NEQ;let $;switch(g){case"null":return(0,n._)`${m} ${_} null`;case"array":$=(0,n._)`Array.isArray(${m})`;break;case"object":$=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":$=T((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":$=T();break;default:return(0,n._)`typeof ${m} ${_} ${g}`}return v===a.Correct?$:(0,n.not)($);function T(R=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,R,S?(0,n._)`isFinite(${m})`:n.nil)}}dataType.checkDataType=f;function h(g,m,S,v){if(g.length===1)return f(g[0],m,S,v);let _;const $=(0,o.toHash)(g);if($.array&&$.object){const T=(0,n._)`typeof ${m} != "object"`;_=$.null?T:(0,n._)`!${m} || ${T}`,delete $.null,delete $.array,delete $.object}else _=n.nil;$.number&&delete $.integer;for(const T in $)_=(0,n.and)(_,f(T,m,S,v));return _}dataType.checkDataTypes=h;const b={message:({schema:g})=>`must be ${g}`,params:({schema:g,schemaValue:m})=>typeof g=="string"?(0,n._)`{type: ${g}}`:(0,n._)`{type: ${m}}`};function y(g){const m=w(g);(0,r.reportError)(m,b)}dataType.reportTypeError=y;function w(g){const{gen:m,data:S,schema:v}=g,_=(0,o.schemaRefOrVal)(g,v,"type");return{gen:m,keyword:"type",data:S,schema:v.type,schemaCode:_,schemaValue:_,parentSchema:v,params:{},it:g}}return dataType}var defaults={},hasRequiredDefaults;function requireDefaults(){if(hasRequiredDefaults)return defaults;hasRequiredDefaults=1,Object.defineProperty(defaults,"__esModule",{value:!0}),defaults.assignDefaults=void 0;const e=requireCodegen(),t=requireUtil();function r(o,a){const{properties:s,items:i}=o.schema;if(a==="object"&&s)for(const l in s)n(o,l,s[l].default);else a==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}defaults.assignDefaults=r;function n(o,a,s){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(s===void 0)return;const d=(0,e._)`${c}${(0,e.getProperty)(a)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${d}`);return}let p=(0,e._)`${d} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${d} === null || ${d} === ""`),i.if(p,(0,e._)`${d} = ${(0,e.stringify)(s)}`)}return defaults}var keyword={},code={},hasRequiredCode;function requireCode(){if(hasRequiredCode)return code;hasRequiredCode=1,Object.defineProperty(code,"__esModule",{value:!0}),code.validateUnion=code.validateArray=code.usePattern=code.callValidateCode=code.schemaProperties=code.allSchemaProperties=code.noPropertyInData=code.propertyInData=code.isOwnProperty=code.hasPropFunc=code.reportMissingProp=code.checkMissingProp=code.checkReportMissingProp=void 0;const e=requireCodegen(),t=requireUtil(),r=requireNames(),n=requireUtil();function o(g,m){const{gen:S,data:v,it:_}=g;S.if(u(S,v,m,_.opts.ownProperties),()=>{g.setParams({missingProperty:(0,e._)`${m}`},!0),g.error()})}code.checkReportMissingProp=o;function a({gen:g,data:m,it:{opts:S}},v,_){return(0,e.or)(...v.map($=>(0,e.and)(u(g,m,$,S.ownProperties),(0,e._)`${_} = ${$}`)))}code.checkMissingProp=a;function s(g,m){g.setParams({missingProperty:m},!0),g.error()}code.reportMissingProp=s;function i(g){return g.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}code.hasPropFunc=i;function l(g,m,S){return(0,e._)`${i(g)}.call(${m}, ${S})`}code.isOwnProperty=l;function c(g,m,S,v){const _=(0,e._)`${m}${(0,e.getProperty)(S)} !== undefined`;return v?(0,e._)`${_} && ${l(g,m,S)}`:_}code.propertyInData=c;function u(g,m,S,v){const _=(0,e._)`${m}${(0,e.getProperty)(S)} === undefined`;return v?(0,e.or)(_,(0,e.not)(l(g,m,S))):_}code.noPropertyInData=u;function d(g){return g?Object.keys(g).filter(m=>m!=="__proto__"):[]}code.allSchemaProperties=d;function p(g,m){return d(m).filter(S=>!(0,t.alwaysValidSchema)(g,m[S]))}code.schemaProperties=p;function f({schemaCode:g,data:m,it:{gen:S,topSchemaRef:v,schemaPath:_,errorPath:$},it:T},R,x,E){const A=E?(0,e._)`${g}, ${m}, ${v}${_}`:m,D=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,$)],[r.default.parentData,T.parentData],[r.default.parentDataProperty,T.parentDataProperty],[r.default.rootData,r.default.rootData]];T.opts.dynamicRef&&D.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const U=(0,e._)`${A}, ${S.object(...D)}`;return x!==e.nil?(0,e._)`${R}.call(${x}, ${U})`:(0,e._)`${R}(${U})`}code.callValidateCode=f;const h=(0,e._)`new RegExp`;function b({gen:g,it:{opts:m}},S){const v=m.unicodeRegExp?"u":"",{regExp:_}=m.code,$=_(S,v);return g.scopeValue("pattern",{key:$.toString(),ref:$,code:(0,e._)`${_.code==="new RegExp"?h:(0,n.useFunc)(g,_)}(${S}, ${v})`})}code.usePattern=b;function y(g){const{gen:m,data:S,keyword:v,it:_}=g,$=m.name("valid");if(_.allErrors){const R=m.let("valid",!0);return T(()=>m.assign(R,!1)),R}return m.var($,!0),T(()=>m.break()),$;function T(R){const x=m.const("len",(0,e._)`${S}.length`);m.forRange("i",0,x,E=>{g.subschema({keyword:v,dataProp:E,dataPropType:t.Type.Num},$),m.if((0,e.not)($),R)})}}code.validateArray=y;function w(g){const{gen:m,schema:S,keyword:v,it:_}=g;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(x=>(0,t.alwaysValidSchema)(_,x))&&!_.opts.unevaluated)return;const T=m.let("valid",!1),R=m.name("_valid");m.block(()=>S.forEach((x,E)=>{const A=g.subschema({keyword:v,schemaProp:E,compositeRule:!0},R);m.assign(T,(0,e._)`${T} || ${R}`),g.mergeValidEvaluated(A,R)||m.if((0,e.not)(T))})),g.result(T,()=>g.reset(),()=>g.error(!0))}return code.validateUnion=w,code}var hasRequiredKeyword;function requireKeyword(){if(hasRequiredKeyword)return keyword;hasRequiredKeyword=1,Object.defineProperty(keyword,"__esModule",{value:!0}),keyword.validateKeywordUsage=keyword.validSchemaType=keyword.funcKeywordCode=keyword.macroKeywordCode=void 0;const e=requireCodegen(),t=requireNames(),r=requireCode(),n=requireErrors();function o(p,f){const{gen:h,keyword:b,schema:y,parentSchema:w,it:g}=p,m=f.macro.call(g.self,y,w,g),S=c(h,b,m);g.opts.validateSchema!==!1&&g.self.validateSchema(m,!0);const v=h.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${g.errSchemaPath}/${b}`,topSchemaRef:S,compositeRule:!0},v),p.pass(v,()=>p.error(!0))}keyword.macroKeywordCode=o;function a(p,f){var h;const{gen:b,keyword:y,schema:w,parentSchema:g,$data:m,it:S}=p;l(S,f);const v=!m&&f.compile?f.compile.call(S.self,w,g,S):f.validate,_=c(b,y,v),$=b.let("valid");p.block$data($,T),p.ok((h=f.valid)!==null&&h!==void 0?h:$);function T(){if(f.errors===!1)E(),f.modifying&&s(p),A(()=>p.error());else{const D=f.async?R():x();f.modifying&&s(p),A(()=>i(p,D))}}function R(){const D=b.let("ruleErrs",null);return b.try(()=>E((0,e._)`await `),U=>b.assign($,!1).if((0,e._)`${U} instanceof ${S.ValidationError}`,()=>b.assign(D,(0,e._)`${U}.errors`),()=>b.throw(U))),D}function x(){const D=(0,e._)`${_}.errors`;return b.assign(D,null),E(e.nil),D}function E(D=f.async?(0,e._)`await `:e.nil){const U=S.opts.passContext?t.default.this:t.default.self,K=!("compile"in f&&!m||f.schema===!1);b.assign($,(0,e._)`${D}${(0,r.callValidateCode)(p,_,U,K)}`,f.modifying)}function A(D){var U;b.if((0,e.not)((U=f.valid)!==null&&U!==void 0?U:$),D)}}keyword.funcKeywordCode=a;function s(p){const{gen:f,data:h,it:b}=p;f.if(b.parentData,()=>f.assign(h,(0,e._)`${b.parentData}[${b.parentDataProperty}]`))}function i(p,f){const{gen:h}=p;h.if((0,e._)`Array.isArray(${f})`,()=>{h.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${f} : ${t.default.vErrors}.concat(${f})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},f){if(f.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,f,h){if(h===void 0)throw new Error(`keyword "${f}" failed to compile`);return p.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,e.stringify)(h)})}function u(p,f,h=!1){return!f.length||f.some(b=>b==="array"?Array.isArray(p):b==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==b||h&&typeof p>"u")}keyword.validSchemaType=u;function d({schema:p,opts:f,self:h,errSchemaPath:b},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const g=y.dependencies;if(g?.some(m=>!Object.prototype.hasOwnProperty.call(p,m)))throw new Error(`parent schema must have dependencies of ${w}: ${g.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const S=`keyword "${w}" value is invalid at path "${b}": `+h.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")h.logger.error(S);else throw new Error(S)}}return keyword.validateKeywordUsage=d,keyword}var subschema={},hasRequiredSubschema;function requireSubschema(){if(hasRequiredSubschema)return subschema;hasRequiredSubschema=1,Object.defineProperty(subschema,"__esModule",{value:!0}),subschema.extendSubschemaMode=subschema.extendSubschemaData=subschema.getSubschema=void 0;const e=requireCodegen(),t=requireUtil();function r(a,{keyword:s,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:d}){if(s!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){const p=a.schema[s];return i===void 0?{schema:p,schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${s}`}:{schema:p[i],schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(i)}`,errSchemaPath:`${a.errSchemaPath}/${s}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||d===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:d,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}subschema.getSubschema=r;function n(a,s,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:d}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=s;if(i!==void 0){const{errorPath:h,dataPathArr:b,opts:y}=s,w=p.let("data",(0,e._)`${s.data}${(0,e.getProperty)(i)}`,!0);f(w),a.errorPath=(0,e.str)`${h}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,a.parentDataProperty=(0,e._)`${i}`,a.dataPathArr=[...b,a.parentDataProperty]}if(c!==void 0){const h=c instanceof e.Name?c:p.let("data",c,!0);f(h),d!==void 0&&(a.propertyName=d)}u&&(a.dataTypes=u);function f(h){a.data=h,a.dataLevel=s.dataLevel+1,a.dataTypes=[],s.definedProperties=new Set,a.parentData=s.data,a.dataNames=[...s.dataNames,h]}}subschema.extendSubschemaData=n;function o(a,{jtdDiscriminator:s,jtdMetadata:i,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=s,a.jtdMetadata=i}return subschema.extendSubschemaMode=o,subschema}var resolve$1={},fastDeepEqual,hasRequiredFastDeepEqual;function requireFastDeepEqual(){return hasRequiredFastDeepEqual||(hasRequiredFastDeepEqual=1,fastDeepEqual=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 s=a[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}),fastDeepEqual}var jsonSchemaTraverse={exports:{}},hasRequiredJsonSchemaTraverse;function requireJsonSchemaTraverse(){if(hasRequiredJsonSchemaTraverse)return jsonSchemaTraverse.exports;hasRequiredJsonSchemaTraverse=1;var e=jsonSchemaTraverse.exports=function(n,o,a){typeof o=="function"&&(a=o,o={}),a=o.cb||a;var s=typeof a=="function"?a:a.pre||function(){},i=a.post||function(){};t(o,s,i,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,s,i,l,c,u,d,p){if(s&&typeof s=="object"&&!Array.isArray(s)){o(s,i,l,c,u,d,p);for(var f in s){var h=s[f];if(Array.isArray(h)){if(f in e.arrayKeywords)for(var b=0;b<h.length;b++)t(n,o,a,h[b],i+"/"+f+"/"+b,l,i,f,s,b)}else if(f in e.propsKeywords){if(h&&typeof h=="object")for(var y in h)t(n,o,a,h[y],i+"/"+f+"/"+r(y),l,i,f,s,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,a,h,i+"/"+f,l,i,f,s)}a(s,i,l,c,u,d,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return jsonSchemaTraverse.exports}var hasRequiredResolve;function requireResolve(){if(hasRequiredResolve)return resolve$1;hasRequiredResolve=1,Object.defineProperty(resolve$1,"__esModule",{value:!0}),resolve$1.getSchemaRefs=resolve$1.resolveUrl=resolve$1.normalizeId=resolve$1._getFullPath=resolve$1.getFullPath=resolve$1.inlineRef=void 0;const e=requireUtil(),t=requireFastDeepEqual(),r=requireJsonSchemaTraverse(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(b,y=!0){return typeof b=="boolean"?!0:y===!0?!s(b):y?i(b)<=y:!1}resolve$1.inlineRef=o;const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(b){for(const y in b){if(a.has(y))return!0;const w=b[y];if(Array.isArray(w)&&w.some(s)||typeof w=="object"&&s(w))return!0}return!1}function i(b){let y=0;for(const w in b){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof b[w]=="object"&&(0,e.eachItem)(b[w],g=>y+=i(g)),y===1/0))return 1/0}return y}function l(b,y="",w){w!==!1&&(y=d(y));const g=b.parse(y);return c(b,g)}resolve$1.getFullPath=l;function c(b,y){return b.serialize(y).split("#")[0]+"#"}resolve$1._getFullPath=c;const u=/#\/?$/;function d(b){return b?b.replace(u,""):""}resolve$1.normalizeId=d;function p(b,y,w){return w=d(w),b.resolve(y,w)}resolve$1.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function h(b,y){if(typeof b=="boolean")return{};const{schemaId:w,uriResolver:g}=this.opts,m=d(b[w]||y),S={"":m},v=l(g,m,!1),_={},$=new Set;return r(b,{allKeys:!0},(x,E,A,D)=>{if(D===void 0)return;const U=v+E;let K=S[D];typeof x[w]=="string"&&(K=G.call(this,x[w])),te.call(this,x.$anchor),te.call(this,x.$dynamicAnchor),S[E]=K;function G(X){const ue=this.opts.uriResolver.resolve;if(X=d(K?ue(K,X):X),$.has(X))throw R(X);$.add(X);let V=this.refs[X];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?T(x,V.schema,X):X!==d(U)&&(X[0]==="#"?(T(x,_[X],X),_[X]=x):this.refs[X]=U),X}function te(X){if(typeof X=="string"){if(!f.test(X))throw new Error(`invalid anchor "${X}"`);G.call(this,`#${X}`)}}}),_;function T(x,E,A){if(E!==void 0&&!t(x,E))throw R(A)}function R(x){return new Error(`reference "${x}" resolves to more than one schema`)}}return resolve$1.getSchemaRefs=h,resolve$1}var hasRequiredValidate;function requireValidate(){if(hasRequiredValidate)return validate$1;hasRequiredValidate=1,Object.defineProperty(validate$1,"__esModule",{value:!0}),validate$1.getData=validate$1.KeywordCxt=validate$1.validateFunctionCode=void 0;const e=requireBoolSchema(),t=requireDataType(),r=requireApplicability(),n=requireDataType(),o=requireDefaults(),a=requireKeyword(),s=requireSubschema(),i=requireCodegen(),l=requireNames(),c=requireResolve(),u=requireUtil(),d=requireErrors();function p(M){if(v(M)&&($(M),S(M))){y(M);return}f(M,()=>(0,e.topBoolOrEmptySchema)(M))}validate$1.validateFunctionCode=p;function f({gen:M,validateName:Z,schema:H,schemaEnv:J,opts:oe},se){oe.code.es5?M.func(Z,(0,i._)`${l.default.data}, ${l.default.valCxt}`,J.$async,()=>{M.code((0,i._)`"use strict"; ${g(H,oe)}`),b(M,oe),M.code(se)}):M.func(Z,(0,i._)`${l.default.data}, ${h(oe)}`,J.$async,()=>M.code(g(H,oe)).code(se))}function h(M){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${M.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function b(M,Z){M.if(l.default.valCxt,()=>{M.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),M.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),M.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),M.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{M.var(l.default.instancePath,(0,i._)`""`),M.var(l.default.parentData,(0,i._)`undefined`),M.var(l.default.parentDataProperty,(0,i._)`undefined`),M.var(l.default.rootData,l.default.data),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(M){const{schema:Z,opts:H,gen:J}=M;f(M,()=>{H.$comment&&Z.$comment&&D(M),x(M),J.let(l.default.vErrors,null),J.let(l.default.errors,0),H.unevaluated&&w(M),T(M),U(M)})}function w(M){const{gen:Z,validateName:H}=M;M.evaluated=Z.const("evaluated",(0,i._)`${H}.evaluated`),Z.if((0,i._)`${M.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${M.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${M.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${M.evaluated}.items`,(0,i._)`undefined`))}function g(M,Z){const H=typeof M=="object"&&M[Z.schemaId];return H&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${H} */`:i.nil}function m(M,Z){if(v(M)&&($(M),S(M))){_(M,Z);return}(0,e.boolOrEmptySchema)(M,Z)}function S({schema:M,self:Z}){if(typeof M=="boolean")return!M;for(const H in M)if(Z.RULES.all[H])return!0;return!1}function v(M){return typeof M.schema!="boolean"}function _(M,Z){const{schema:H,gen:J,opts:oe}=M;oe.$comment&&H.$comment&&D(M),E(M),A(M);const se=J.const("_errs",l.default.errors);T(M,se),J.var(Z,(0,i._)`${se} === ${l.default.errors}`)}function $(M){(0,u.checkUnknownRules)(M),R(M)}function T(M,Z){if(M.opts.jtd)return G(M,[],!1,Z);const H=(0,t.getSchemaTypes)(M.schema),J=(0,t.coerceAndCheckDataType)(M,H);G(M,H,!J,Z)}function R(M){const{schema:Z,errSchemaPath:H,opts:J,self:oe}=M;Z.$ref&&J.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,oe.RULES)&&oe.logger.warn(`$ref: keywords ignored in schema at path "${H}"`)}function x(M){const{schema:Z,opts:H}=M;Z.default!==void 0&&H.useDefaults&&H.strictSchema&&(0,u.checkStrictMode)(M,"default is ignored in the schema root")}function E(M){const Z=M.schema[M.opts.schemaId];Z&&(M.baseId=(0,c.resolveUrl)(M.opts.uriResolver,M.baseId,Z))}function A(M){if(M.schema.$async&&!M.schemaEnv.$async)throw new Error("async schema in sync schema")}function D({gen:M,schemaEnv:Z,schema:H,errSchemaPath:J,opts:oe}){const se=H.$comment;if(oe.$comment===!0)M.code((0,i._)`${l.default.self}.logger.log(${se})`);else if(typeof oe.$comment=="function"){const _e=(0,i.str)`${J}/$comment`,Te=M.scopeValue("root",{ref:Z.root});M.code((0,i._)`${l.default.self}.opts.$comment(${se}, ${_e}, ${Te}.schema)`)}}function U(M){const{gen:Z,schemaEnv:H,validateName:J,ValidationError:oe,opts:se}=M;H.$async?Z.if((0,i._)`${l.default.errors} === 0`,()=>Z.return(l.default.data),()=>Z.throw((0,i._)`new ${oe}(${l.default.vErrors})`)):(Z.assign((0,i._)`${J}.errors`,l.default.vErrors),se.unevaluated&&K(M),Z.return((0,i._)`${l.default.errors} === 0`))}function K({gen:M,evaluated:Z,props:H,items:J}){H instanceof i.Name&&M.assign((0,i._)`${Z}.props`,H),J instanceof i.Name&&M.assign((0,i._)`${Z}.items`,J)}function G(M,Z,H,J){const{gen:oe,schema:se,data:_e,allErrors:Te,opts:Se,self:Q}=M,{RULES:ve}=Q;if(se.$ref&&(Se.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(se,ve))){oe.block(()=>q(M,"$ref",ve.all.$ref.definition));return}Se.jtd||X(M,Z),oe.block(()=>{for(const ne of ve.rules)de(ne);de(ve.post)});function de(ne){(0,r.shouldUseGroup)(se,ne)&&(ne.type?(oe.if((0,n.checkDataType)(ne.type,_e,Se.strictNumbers)),te(M,ne),Z.length===1&&Z[0]===ne.type&&H&&(oe.else(),(0,n.reportTypeError)(M)),oe.endIf()):te(M,ne),Te||oe.if((0,i._)`${l.default.errors} === ${J||0}`))}}function te(M,Z){const{gen:H,schema:J,opts:{useDefaults:oe}}=M;oe&&(0,o.assignDefaults)(M,Z.type),H.block(()=>{for(const se of Z.rules)(0,r.shouldUseRule)(J,se)&&q(M,se.keyword,se.definition,Z.type)})}function X(M,Z){M.schemaEnv.meta||!M.opts.strictTypes||(ue(M,Z),M.opts.allowUnionTypes||V(M,Z),C(M,M.dataTypes))}function ue(M,Z){if(Z.length){if(!M.dataTypes.length){M.dataTypes=Z;return}Z.forEach(H=>{L(M.dataTypes,H)||k(M,`type "${H}" not allowed by context "${M.dataTypes.join(",")}"`)}),I(M,Z)}}function V(M,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&k(M,"use allowUnionTypes to allow union type keyword")}function C(M,Z){const H=M.self.RULES.all;for(const J in H){const oe=H[J];if(typeof oe=="object"&&(0,r.shouldUseRule)(M.schema,oe)){const{type:se}=oe.definition;se.length&&!se.some(_e=>N(Z,_e))&&k(M,`missing type "${se.join(",")}" for keyword "${J}"`)}}}function N(M,Z){return M.includes(Z)||Z==="number"&&M.includes("integer")}function L(M,Z){return M.includes(Z)||Z==="integer"&&M.includes("number")}function I(M,Z){const H=[];for(const J of M.dataTypes)L(Z,J)?H.push(J):Z.includes("integer")&&J==="number"&&H.push("integer");M.dataTypes=H}function k(M,Z){const H=M.schemaEnv.baseId+M.errSchemaPath;Z+=` at "${H}" (strictTypes)`,(0,u.checkStrictMode)(M,Z,M.opts.strictTypes)}class O{constructor(Z,H,J){if((0,a.validateKeywordUsage)(Z,H,J),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=J,this.data=Z.data,this.schema=Z.schema[J],this.$data=H.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,J,this.$data),this.schemaType=H.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=H,this.$data)this.schemaCode=Z.gen.const("vSchema",j(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,H.schemaType,H.allowUndefined))throw new Error(`${J} value must be ${JSON.stringify(H.schemaType)}`);("code"in H?H.trackErrors:H.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",l.default.errors))}result(Z,H,J){this.failResult((0,i.not)(Z),H,J)}failResult(Z,H,J){this.gen.if(Z),J?J():this.error(),H?(this.gen.else(),H(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,H){this.failResult((0,i.not)(Z),void 0,H)}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:H}=this;this.fail((0,i._)`${H} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,H,J){if(H){this.setParams(H),this._error(Z,J),this.setParams({});return}this._error(Z,J)}_error(Z,H){(Z?d.reportExtraError:d.reportError)(this,this.def.error,H)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,H){H?Object.assign(this.params,Z):this.params=Z}block$data(Z,H,J=i.nil){this.gen.block(()=>{this.check$data(Z,J),H()})}check$data(Z=i.nil,H=i.nil){if(!this.$data)return;const{gen:J,schemaCode:oe,schemaType:se,def:_e}=this;J.if((0,i.or)((0,i._)`${oe} === undefined`,H)),Z!==i.nil&&J.assign(Z,!0),(se.length||_e.validateSchema)&&(J.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&J.assign(Z,!1)),J.else()}invalid$data(){const{gen:Z,schemaCode:H,schemaType:J,def:oe,it:se}=this;return(0,i.or)(_e(),Te());function _e(){if(J.length){if(!(H instanceof i.Name))throw new Error("ajv implementation error");const Se=Array.isArray(J)?J:[J];return(0,i._)`${(0,n.checkDataTypes)(Se,H,se.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Te(){if(oe.validateSchema){const Se=Z.scopeValue("validate$data",{ref:oe.validateSchema});return(0,i._)`!${Se}(${H})`}return i.nil}}subschema(Z,H){const J=(0,s.getSubschema)(this.it,Z);(0,s.extendSubschemaData)(J,this.it,Z),(0,s.extendSubschemaMode)(J,Z);const oe={...this.it,...J,items:void 0,props:void 0};return m(oe,H),oe}mergeEvaluated(Z,H){const{it:J,gen:oe}=this;J.opts.unevaluated&&(J.props!==!0&&Z.props!==void 0&&(J.props=u.mergeEvaluated.props(oe,Z.props,J.props,H)),J.items!==!0&&Z.items!==void 0&&(J.items=u.mergeEvaluated.items(oe,Z.items,J.items,H)))}mergeValidEvaluated(Z,H){const{it:J,gen:oe}=this;if(J.opts.unevaluated&&(J.props!==!0||J.items!==!0))return oe.if(H,()=>this.mergeEvaluated(Z,i.Name)),!0}}validate$1.KeywordCxt=O;function q(M,Z,H,J){const oe=new O(M,H,Z);"code"in H?H.code(oe,J):oe.$data&&H.validate?(0,a.funcKeywordCode)(oe,H):"macro"in H?(0,a.macroKeywordCode)(oe,H):(H.compile||H.validate)&&(0,a.funcKeywordCode)(oe,H)}const B=/^\/(?:[^~]|~0|~1)*$/,F=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function j(M,{dataLevel:Z,dataNames:H,dataPathArr:J}){let oe,se;if(M==="")return l.default.rootData;if(M[0]==="/"){if(!B.test(M))throw new Error(`Invalid JSON-pointer: ${M}`);oe=M,se=l.default.rootData}else{const Q=F.exec(M);if(!Q)throw new Error(`Invalid JSON-pointer: ${M}`);const ve=+Q[1];if(oe=Q[2],oe==="#"){if(ve>=Z)throw new Error(Se("property/index",ve));return J[Z-ve]}if(ve>Z)throw new Error(Se("data",ve));if(se=H[Z-ve],!oe)return se}let _e=se;const Te=oe.split("/");for(const Q of Te)Q&&(se=(0,i._)`${se}${(0,i.getProperty)((0,u.unescapeJsonPointer)(Q))}`,_e=(0,i._)`${_e} && ${se}`);return _e;function Se(Q,ve){return`Cannot access ${Q} ${ve} levels up, current level is ${Z}`}}return validate$1.getData=j,validate$1}var validation_error={},hasRequiredValidation_error;function requireValidation_error(){if(hasRequiredValidation_error)return validation_error;hasRequiredValidation_error=1,Object.defineProperty(validation_error,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return validation_error.default=e,validation_error}var ref_error={},hasRequiredRef_error;function requireRef_error(){if(hasRequiredRef_error)return ref_error;hasRequiredRef_error=1,Object.defineProperty(ref_error,"__esModule",{value:!0});const e=requireResolve();class t extends Error{constructor(n,o,a,s){super(s||`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 ref_error.default=t,ref_error}var compile={},hasRequiredCompile;function requireCompile(){if(hasRequiredCompile)return compile;hasRequiredCompile=1,Object.defineProperty(compile,"__esModule",{value:!0}),compile.resolveSchema=compile.getCompilingSchema=compile.resolveRef=compile.compileSchema=compile.SchemaEnv=void 0;const e=requireCodegen(),t=requireValidation_error(),r=requireNames(),n=requireResolve(),o=requireUtil(),a=requireValidate();class s{constructor(w){var g;this.refs={},this.dynamicAnchors={};let m;typeof w.schema=="object"&&(m=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(g=w.baseId)!==null&&g!==void 0?g:(0,n.normalizeId)(m?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=m?.$async,this.refs={}}}compile.SchemaEnv=s;function i(y){const w=u.call(this,y);if(w)return w;const g=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:m,lines:S}=this.opts.code,{ownProperties:v}=this.opts,_=new e.CodeGen(this.scope,{es5:m,lines:S,ownProperties:v});let $;y.$async&&($=_.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const T=_.scopeName("validate");y.validateName=T;const R={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:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:T,ValidationError:$,schema:y.schema,schemaEnv:y,rootId:g,baseId:y.baseId||g,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let x;try{this._compilations.add(y),(0,a.validateFunctionCode)(R),_.optimize(this.opts.code.optimize);const E=_.toString();x=`${_.scopeRefs(r.default.scope)}return ${E}`,this.opts.code.process&&(x=this.opts.code.process(x,y));const D=new Function(`${r.default.self}`,`${r.default.scope}`,x)(this,this.scope.get());if(this.scope.value(T,{ref:D}),D.errors=null,D.schema=y.schema,D.schemaEnv=y,y.$async&&(D.$async=!0),this.opts.code.source===!0&&(D.source={validateName:T,validateCode:E,scopeValues:_._values}),this.opts.unevaluated){const{props:U,items:K}=R;D.evaluated={props:U instanceof e.Name?void 0:U,items:K instanceof e.Name?void 0:K,dynamicProps:U instanceof e.Name,dynamicItems:K instanceof e.Name},D.source&&(D.source.evaluated=(0,e.stringify)(D.evaluated))}return y.validate=D,y}catch(E){throw delete y.validate,delete y.validateName,x&&this.logger.error("Error compiling schema, function code:",x),E}finally{this._compilations.delete(y)}}compile.compileSchema=i;function l(y,w,g){var m;g=(0,n.resolveUrl)(this.opts.uriResolver,w,g);const S=y.refs[g];if(S)return S;let v=p.call(this,y,g);if(v===void 0){const _=(m=y.localRefs)===null||m===void 0?void 0:m[g],{schemaId:$}=this.opts;_&&(v=new s({schema:_,schemaId:$,root:y,baseId:w}))}if(v!==void 0)return y.refs[g]=c.call(this,v)}compile.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:i.call(this,y)}function u(y){for(const w of this._compilations)if(d(w,y))return w}compile.getCompilingSchema=u;function d(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let g;for(;typeof(g=this.refs[w])=="string";)w=g;return g||this.schemas[w]||f.call(this,y,w)}function f(y,w){const g=this.opts.uriResolver.parse(w),m=(0,n._getFullPath)(this.opts.uriResolver,g);let S=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&m===S)return b.call(this,g,y);const v=(0,n.normalizeId)(m),_=this.refs[v]||this.schemas[v];if(typeof _=="string"){const $=f.call(this,y,_);return typeof $?.schema!="object"?void 0:b.call(this,g,$)}if(typeof _?.schema=="object"){if(_.validate||i.call(this,_),v===(0,n.normalizeId)(w)){const{schema:$}=_,{schemaId:T}=this.opts,R=$[T];return R&&(S=(0,n.resolveUrl)(this.opts.uriResolver,S,R)),new s({schema:$,schemaId:T,root:y,baseId:S})}return b.call(this,g,_)}}compile.resolveSchema=f;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(y,{baseId:w,schema:g,root:m}){var S;if(((S=y.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(const $ of y.fragment.slice(1).split("/")){if(typeof g=="boolean")return;const T=g[(0,o.unescapeFragment)($)];if(T===void 0)return;g=T;const R=typeof g=="object"&&g[this.opts.schemaId];!h.has($)&&R&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,R))}let v;if(typeof g!="boolean"&&g.$ref&&!(0,o.schemaHasRulesButRef)(g,this.RULES)){const $=(0,n.resolveUrl)(this.opts.uriResolver,w,g.$ref);v=f.call(this,m,$)}const{schemaId:_}=this.opts;if(v=v||new s({schema:g,schemaId:_,root:m,baseId:w}),v.schema!==v.root.schema)return v}return compile}const $id$1="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description="Meta-schema for $data reference (JSON AnySchema extension proposal)",type$1="object",required$2=["$data"],properties$2={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties$1=!1,require$$9={$id:$id$1,description,type:type$1,required:required$2,properties:properties$2,additionalProperties:additionalProperties$1};var uri$1={},fastUri={exports:{}},utils$2,hasRequiredUtils$2;function requireUtils$2(){if(hasRequiredUtils$2)return utils$2;hasRequiredUtils$2=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(v){let _="",$=0,T=0;for(T=0;T<v.length;T++)if($=v[T].charCodeAt(0),$!==48){if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";_+=v[T];break}for(T+=1;T<v.length;T++){if($=v[T].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";_+=v[T]}return _}const s=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function i(v){return v.length=0,!0}function l(v,_,$){if(v.length){const T=a(v);if(T!=="")_.push(T);else return $.error=!0,!1;v.length=0}return!0}function c(v){let _=0;const $={error:!1,address:"",zone:""},T=[],R=[];let x=!1,E=!1,A=l;for(let D=0;D<v.length;D++){const U=v[D];if(!(U==="["||U==="]"))if(U===":"){if(x===!0&&(E=!0),!A(R,T,$))break;if(++_>7){$.error=!0;break}D>0&&v[D-1]===":"&&(x=!0),T.push(":");continue}else if(U==="%"){if(!A(R,T,$))break;A=i}else{R.push(U);continue}}return R.length&&(A===i?$.zone=R.join(""):E?T.push(R.join("")):T.push(a(R))),$.address=T.join(""),$}function u(v){if(d(v,":")<2)return{host:v,isIPV6:!1};const _=c(v);if(_.error)return{host:v,isIPV6:!1};{let $=_.address,T=_.address;return _.zone&&($+="%"+_.zone,T+="%25"+_.zone),{host:$,isIPV6:!0,escapedHost:T}}}function d(v,_){let $=0;for(let T=0;T<v.length;T++)v[T]===_&&$++;return $}function p(v){let _=v;const $=[];let T=-1,R=0;for(;R=_.length;){if(R===1){if(_===".")break;if(_==="/"){$.push("/");break}else{$.push(_);break}}else if(R===2){if(_[0]==="."){if(_[1]===".")break;if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&(_[1]==="."||_[1]==="/")){$.push("/");break}}else if(R===3&&_==="/.."){$.length!==0&&$.pop(),$.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),$.length!==0&&$.pop();continue}}if((T=_.indexOf("/",1))===-1){$.push(_);break}else $.push(_.slice(0,T)),_=_.slice(T)}return $.join("")}const f={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},h=/[@/?#:]/g,b=/[@/?#]/g;function y(v,_){const $=_?b:h;return $.lastIndex=0,v.replace($,T=>f[T])}function w(v,_=!1){if(v.indexOf("%")===-1)return v;let $="";for(let T=0;T<v.length;T++){if(v[T]==="%"&&T+2<v.length){const R=v.slice(T+1,T+3);if(r(R)){const x=R.toUpperCase(),E=String.fromCharCode(parseInt(x,16));_&&n(E)?$+=E:$+="%"+x,T+=2;continue}}$+=v[T]}return $}function g(v){let _="";for(let $=0;$<v.length;$++){if(v[$]==="%"&&$+2<v.length){const T=v.slice($+1,$+3);if(r(T)){const R=T.toUpperCase(),x=String.fromCharCode(parseInt(R,16));x!=="."&&n(x)?_+=x:_+="%"+R,$+=2;continue}}o(v[$])?_+=v[$]:_+=escape(v[$])}return _}function m(v){let _="";for(let $=0;$<v.length;$++){if(v[$]==="%"&&$+2<v.length){const T=v.slice($+1,$+3);if(r(T)){_+="%"+T.toUpperCase(),$+=2;continue}}_+=escape(v[$])}return _}function S(v){const _=[];if(v.userinfo!==void 0&&(_.push(v.userinfo),_.push("@")),v.host!==void 0){let $=unescape(v.host);if(!t($)){const T=u($);T.isIPV6===!0?$=`[${T.escapedHost}]`:$=y($,!1)}_.push($)}return(typeof v.port=="number"||typeof v.port=="string")&&(_.push(":"),_.push(String(v.port))),_.length?_.join(""):void 0}return utils$2={nonSimpleDomain:s,recomposeAuthority:S,reescapeHostDelimiters:y,normalizePercentEncoding:w,normalizePathEncoding:g,escapePreservingEscapes:m,removeDotSegments:p,isIPv4:t,isUUID:e,normalizeIPv6:u,stringArrayToHexStripped:a},utils$2}var schemes,hasRequiredSchemes;function requireSchemes(){if(hasRequiredSchemes)return schemes;hasRequiredSchemes=1;const{isUUID:e}=requireUtils$2(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(v){return r.indexOf(v)!==-1}function o(v){return v.secure===!0?!0:v.secure===!1?!1:v.scheme?v.scheme.length===3&&(v.scheme[0]==="w"||v.scheme[0]==="W")&&(v.scheme[1]==="s"||v.scheme[1]==="S")&&(v.scheme[2]==="s"||v.scheme[2]==="S"):!1}function a(v){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v}function s(v){const _=String(v.scheme).toLowerCase()==="https";return(v.port===(_?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}function i(v){return v.secure=o(v),v.resourceName=(v.path||"/")+(v.query?"?"+v.query:""),v.path=void 0,v.query=void 0,v}function l(v){if((v.port===(o(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){const[_,$]=v.resourceName.split("?");v.path=_&&_!=="/"?_:void 0,v.query=$,v.resourceName=void 0}return v.fragment=void 0,v}function c(v,_){if(!v.path)return v.error="URN can not be parsed",v;const $=v.path.match(t);if($){const T=_.scheme||v.scheme||"urn";v.nid=$[1].toLowerCase(),v.nss=$[2];const R=`${T}:${_.nid||v.nid}`,x=S(R);v.path=void 0,x&&(v=x.parse(v,_))}else v.error=v.error||"URN can not be parsed.";return v}function u(v,_){if(v.nid===void 0)throw new Error("URN without nid cannot be serialized");const $=_.scheme||v.scheme||"urn",T=v.nid.toLowerCase(),R=`${$}:${_.nid||T}`,x=S(R);x&&(v=x.serialize(v,_));const E=v,A=v.nss;return E.path=`${T||_.nid}:${A}`,_.skipEscape=!0,E}function d(v,_){const $=v;return $.uuid=$.nss,$.nss=void 0,!_.tolerant&&(!$.uuid||!e($.uuid))&&($.error=$.error||"UUID is not valid."),$}function p(v){const _=v;return _.nss=(v.uuid||"").toLowerCase(),_}const f={scheme:"http",domainHost:!0,parse:a,serialize:s},h={scheme:"https",domainHost:f.domainHost,parse:a,serialize:s},b={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:b.domainHost,parse:b.parse,serialize:b.serialize},m={http:f,https:h,ws:b,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:d,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(m,null);function S(v){return v&&(m[v]||m[v.toLowerCase()])||void 0}return schemes={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:S},schemes}var hasRequiredFastUri;function requireFastUri(){if(hasRequiredFastUri)return fastUri.exports;hasRequiredFastUri=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizePercentEncoding:n,normalizePathEncoding:o,escapePreservingEscapes:a,reescapeHostDelimiters:s,isIPv4:i,nonSimpleDomain:l}=requireUtils$2(),{SCHEMES:c,getSchemeHandler:u}=requireSchemes();function d(T,R){return typeof T=="string"?T=S(T,R):typeof T=="object"&&(T=m(b(T,R),R)),T}function p(T,R,x){const E=x?Object.assign({scheme:"null"},x):{scheme:"null"},A=f(m(T,E),m(R,E),E,!0);return E.skipEscape=!0,b(A,E)}function f(T,R,x,E){const A={};return E||(T=m(b(T,x),x),R=m(b(R,x),x)),x=x||{},!x.tolerant&&R.scheme?(A.scheme=R.scheme,A.userinfo=R.userinfo,A.host=R.host,A.port=R.port,A.path=t(R.path||""),A.query=R.query):(R.userinfo!==void 0||R.host!==void 0||R.port!==void 0?(A.userinfo=R.userinfo,A.host=R.host,A.port=R.port,A.path=t(R.path||""),A.query=R.query):(R.path?(R.path[0]==="/"?A.path=t(R.path):((T.userinfo!==void 0||T.host!==void 0||T.port!==void 0)&&!T.path?A.path="/"+R.path:T.path?A.path=T.path.slice(0,T.path.lastIndexOf("/")+1)+R.path:A.path=R.path,A.path=t(A.path)),A.query=R.query):(A.path=T.path,R.query!==void 0?A.query=R.query:A.query=T.query),A.userinfo=T.userinfo,A.host=T.host,A.port=T.port),A.scheme=T.scheme),A.fragment=R.fragment,A}function h(T,R,x){const E=_(T,x),A=_(R,x);return E!==void 0&&A!==void 0&&E.toLowerCase()===A.toLowerCase()}function b(T,R){const x={host:T.host,scheme:T.scheme,userinfo:T.userinfo,port:T.port,path:T.path,query:T.query,nid:T.nid,nss:T.nss,uuid:T.uuid,fragment:T.fragment,reference:T.reference,resourceName:T.resourceName,secure:T.secure,error:""},E=Object.assign({},R),A=[],D=u(E.scheme||x.scheme);D&&D.serialize&&D.serialize(x,E),x.path!==void 0&&(E.skipEscape?x.path=n(x.path):(x.path=a(x.path),x.scheme!==void 0&&(x.path=x.path.split("%3A").join(":")))),E.reference!=="suffix"&&x.scheme&&A.push(x.scheme,":");const U=r(x);if(U!==void 0&&(E.reference!=="suffix"&&A.push("//"),A.push(U),x.path&&x.path[0]!=="/"&&A.push("/")),x.path!==void 0){let K=x.path;!E.absolutePath&&(!D||!D.absolutePath)&&(K=t(K)),U===void 0&&K[0]==="/"&&K[1]==="/"&&(K="/%2F"+K.slice(2)),A.push(K)}return x.query!==void 0&&A.push("?",x.query),x.fragment!==void 0&&A.push("#",x.fragment),A.join("")}const y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function w(T,R){if(R[2]!==void 0&&T.path&&T.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof T.port=="number"&&(T.port<0||T.port>65535))return"URI port is malformed."}function g(T,R){const x=Object.assign({},R),E={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let A=!1,D=!1;x.reference==="suffix"&&(x.scheme?T=x.scheme+":"+T:T="//"+T);const U=T.match(y);if(U){E.scheme=U[1],E.userinfo=U[3],E.host=U[4],E.port=parseInt(U[5],10),E.path=U[6]||"",E.query=U[7],E.fragment=U[8],isNaN(E.port)&&(E.port=U[5]);const K=w(E,U);if(K!==void 0&&(E.error=E.error||K,A=!0),E.host)if(i(E.host)===!1){const X=e(E.host);E.host=X.host.toLowerCase(),D=X.isIPV6}else D=!0;E.scheme===void 0&&E.userinfo===void 0&&E.host===void 0&&E.port===void 0&&E.query===void 0&&!E.path?E.reference="same-document":E.scheme===void 0?E.reference="relative":E.fragment===void 0?E.reference="absolute":E.reference="uri",x.reference&&x.reference!=="suffix"&&x.reference!==E.reference&&(E.error=E.error||"URI is not a "+x.reference+" reference.");const G=u(x.scheme||E.scheme);if(!x.unicodeSupport&&(!G||!G.unicodeSupport)&&E.host&&(x.domainHost||G&&G.domainHost)&&D===!1&&l(E.host))try{E.host=new URL("http://"+E.host).hostname}catch(te){E.error=E.error||"Host's domain name can not be converted to ASCII: "+te}if((!G||G&&!G.skipNormalize)&&(T.indexOf("%")!==-1&&(E.scheme!==void 0&&(E.scheme=unescape(E.scheme)),E.host!==void 0&&(E.host=s(unescape(E.host),D))),E.path&&(E.path=o(E.path)),E.fragment))try{E.fragment=encodeURI(decodeURIComponent(E.fragment))}catch{E.error=E.error||"URI malformed"}G&&G.parse&&G.parse(E,x)}else E.error=E.error||"URI can not be parsed.";return{parsed:E,malformedAuthorityOrPort:A}}function m(T,R){return g(T,R).parsed}function S(T,R){return v(T,R).normalized}function v(T,R){const{parsed:x,malformedAuthorityOrPort:E}=g(T,R);return{normalized:E?T:b(x,R),malformedAuthorityOrPort:E}}function _(T,R){if(typeof T=="string"){const{normalized:x,malformedAuthorityOrPort:E}=v(T,R);return E?void 0:x}if(typeof T=="object")return b(T,R)}const $={SCHEMES:c,normalize:d,resolve:p,resolveComponent:f,equal:h,serialize:b,parse:m};return fastUri.exports=$,fastUri.exports.default=$,fastUri.exports.fastUri=$,fastUri.exports}var hasRequiredUri;function requireUri(){if(hasRequiredUri)return uri$1;hasRequiredUri=1,Object.defineProperty(uri$1,"__esModule",{value:!0});const e=requireFastUri();return e.code='require("ajv/dist/runtime/uri").default',uri$1.default=e,uri$1}var hasRequiredCore$1;function requireCore$1(){return hasRequiredCore$1||(hasRequiredCore$1=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=requireValidate();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=requireCodegen();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=requireValidation_error(),o=requireRef_error(),a=requireRules(),s=requireCompile(),i=requireCodegen(),l=requireResolve(),c=requireDataType(),u=requireUtil(),d=require$$9,p=requireUri(),f=(V,C)=>new RegExp(V,C);f.code="new RegExp";const h=["removeAdditional","useDefaults","coerceTypes"],b=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={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."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},g=200;function m(V){var C,N,L,I,k,O,q,B,F,j,M,Z,H,J,oe,se,_e,Te,Se,Q,ve,de,ne,ae,ee;const Y=V.strict,ce=(C=V.code)===null||C===void 0?void 0:C.optimize,le=ce===!0||ce===void 0?1:ce||0,P=(L=(N=V.code)===null||N===void 0?void 0:N.regExp)!==null&&L!==void 0?L:f,W=(I=V.uriResolver)!==null&&I!==void 0?I:p.default;return{strictSchema:(O=(k=V.strictSchema)!==null&&k!==void 0?k:Y)!==null&&O!==void 0?O:!0,strictNumbers:(B=(q=V.strictNumbers)!==null&&q!==void 0?q:Y)!==null&&B!==void 0?B:!0,strictTypes:(j=(F=V.strictTypes)!==null&&F!==void 0?F:Y)!==null&&j!==void 0?j:"log",strictTuples:(Z=(M=V.strictTuples)!==null&&M!==void 0?M:Y)!==null&&Z!==void 0?Z:"log",strictRequired:(J=(H=V.strictRequired)!==null&&H!==void 0?H:Y)!==null&&J!==void 0?J:!1,code:V.code?{...V.code,optimize:le,regExp:P}:{optimize:le,regExp:P},loopRequired:(oe=V.loopRequired)!==null&&oe!==void 0?oe:g,loopEnum:(se=V.loopEnum)!==null&&se!==void 0?se:g,meta:(_e=V.meta)!==null&&_e!==void 0?_e:!0,messages:(Te=V.messages)!==null&&Te!==void 0?Te:!0,inlineRefs:(Se=V.inlineRefs)!==null&&Se!==void 0?Se:!0,schemaId:(Q=V.schemaId)!==null&&Q!==void 0?Q:"$id",addUsedSchema:(ve=V.addUsedSchema)!==null&&ve!==void 0?ve:!0,validateSchema:(de=V.validateSchema)!==null&&de!==void 0?de:!0,validateFormats:(ne=V.validateFormats)!==null&&ne!==void 0?ne:!0,unicodeRegExp:(ae=V.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ee=V.int32range)!==null&&ee!==void 0?ee:!0,uriResolver:W}}class S{constructor(C={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,C=this.opts={...C,...m(C)};const{es5:N,lines:L}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:b,es5:N,lines:L}),this.logger=A(C.logger);const I=C.validateFormats;C.validateFormats=!1,this.RULES=(0,a.getRules)(),v.call(this,y,C,"NOT SUPPORTED"),v.call(this,w,C,"DEPRECATED","warn"),this._metaOpts=x.call(this),C.formats&&T.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),C.keywords&&R.call(this,C.keywords),typeof C.meta=="object"&&this.addMetaSchema(C.meta),$.call(this),C.validateFormats=I}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:C,meta:N,schemaId:L}=this.opts;let I=d;L==="id"&&(I={...d},I.id=I.$id,delete I.$id),N&&C&&this.addMetaSchema(I,I[L],!1)}defaultMeta(){const{meta:C,schemaId:N}=this.opts;return this.opts.defaultMeta=typeof C=="object"?C[N]||C:void 0}validate(C,N){let L;if(typeof C=="string"){if(L=this.getSchema(C),!L)throw new Error(`no schema with key or ref "${C}"`)}else L=this.compile(C);const I=L(N);return"$async"in L||(this.errors=L.errors),I}compile(C,N){const L=this._addSchema(C,N);return L.validate||this._compileSchemaEnv(L)}compileAsync(C,N){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:L}=this.opts;return I.call(this,C,N);async function I(j,M){await k.call(this,j.$schema);const Z=this._addSchema(j,M);return Z.validate||O.call(this,Z)}async function k(j){j&&!this.getSchema(j)&&await I.call(this,{$ref:j},!0)}async function O(j){try{return this._compileSchemaEnv(j)}catch(M){if(!(M instanceof o.default))throw M;return q.call(this,M),await B.call(this,M.missingSchema),O.call(this,j)}}function q({missingSchema:j,missingRef:M}){if(this.refs[j])throw new Error(`AnySchema ${j} is loaded but ${M} cannot be resolved`)}async function B(j){const M=await F.call(this,j);this.refs[j]||await k.call(this,M.$schema),this.refs[j]||this.addSchema(M,j,N)}async function F(j){const M=this._loading[j];if(M)return M;try{return await(this._loading[j]=L(j))}finally{delete this._loading[j]}}}addSchema(C,N,L,I=this.opts.validateSchema){if(Array.isArray(C)){for(const O of C)this.addSchema(O,void 0,L,I);return this}let k;if(typeof C=="object"){const{schemaId:O}=this.opts;if(k=C[O],k!==void 0&&typeof k!="string")throw new Error(`schema ${O} must be string`)}return N=(0,l.normalizeId)(N||k),this._checkUnique(N),this.schemas[N]=this._addSchema(C,L,N,I,!0),this}addMetaSchema(C,N,L=this.opts.validateSchema){return this.addSchema(C,N,!0,L),this}validateSchema(C,N){if(typeof C=="boolean")return!0;let L;if(L=C.$schema,L!==void 0&&typeof L!="string")throw new Error("$schema must be a string");if(L=L||this.opts.defaultMeta||this.defaultMeta(),!L)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const I=this.validate(L,C);if(!I&&N){const k="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(k);else throw new Error(k)}return I}getSchema(C){let N;for(;typeof(N=_.call(this,C))=="string";)C=N;if(N===void 0){const{schemaId:L}=this.opts,I=new s.SchemaEnv({schema:{},schemaId:L});if(N=s.resolveSchema.call(this,I,C),!N)return;this.refs[C]=N}return N.validate||this._compileSchemaEnv(N)}removeSchema(C){if(C instanceof RegExp)return this._removeAllSchemas(this.schemas,C),this._removeAllSchemas(this.refs,C),this;switch(typeof C){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const N=_.call(this,C);return typeof N=="object"&&this._cache.delete(N.schema),delete this.schemas[C],delete this.refs[C],this}case"object":{const N=C;this._cache.delete(N);let L=C[this.opts.schemaId];return L&&(L=(0,l.normalizeId)(L),delete this.schemas[L],delete this.refs[L]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(C){for(const N of C)this.addKeyword(N);return this}addKeyword(C,N){let L;if(typeof C=="string")L=C,typeof N=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),N.keyword=L);else if(typeof C=="object"&&N===void 0){if(N=C,L=N.keyword,Array.isArray(L)&&!L.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,L,N),!N)return(0,u.eachItem)(L,k=>K.call(this,k)),this;te.call(this,N);const I={...N,type:(0,c.getJSONTypes)(N.type),schemaType:(0,c.getJSONTypes)(N.schemaType)};return(0,u.eachItem)(L,I.type.length===0?k=>K.call(this,k,I):k=>I.type.forEach(O=>K.call(this,k,I,O))),this}getKeyword(C){const N=this.RULES.all[C];return typeof N=="object"?N.definition:!!N}removeKeyword(C){const{RULES:N}=this;delete N.keywords[C],delete N.all[C];for(const L of N.rules){const I=L.rules.findIndex(k=>k.keyword===C);I>=0&&L.rules.splice(I,1)}return this}addFormat(C,N){return typeof N=="string"&&(N=new RegExp(N)),this.formats[C]=N,this}errorsText(C=this.errors,{separator:N=", ",dataVar:L="data"}={}){return!C||C.length===0?"No errors":C.map(I=>`${L}${I.instancePath} ${I.message}`).reduce((I,k)=>I+N+k)}$dataMetaSchema(C,N){const L=this.RULES.all;C=JSON.parse(JSON.stringify(C));for(const I of N){const k=I.split("/").slice(1);let O=C;for(const q of k)O=O[q];for(const q in L){const B=L[q];if(typeof B!="object")continue;const{$data:F}=B.definition,j=O[q];F&&j&&(O[q]=ue(j))}}return C}_removeAllSchemas(C,N){for(const L in C){const I=C[L];(!N||N.test(L))&&(typeof I=="string"?delete C[L]:I&&!I.meta&&(this._cache.delete(I.schema),delete C[L]))}}_addSchema(C,N,L,I=this.opts.validateSchema,k=this.opts.addUsedSchema){let O;const{schemaId:q}=this.opts;if(typeof C=="object")O=C[q];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof C!="boolean")throw new Error("schema must be object or boolean")}let B=this._cache.get(C);if(B!==void 0)return B;L=(0,l.normalizeId)(O||L);const F=l.getSchemaRefs.call(this,C,L);return B=new s.SchemaEnv({schema:C,schemaId:q,meta:N,baseId:L,localRefs:F}),this._cache.set(B.schema,B),k&&!L.startsWith("#")&&(L&&this._checkUnique(L),this.refs[L]=B),I&&this.validateSchema(C,!0),B}_checkUnique(C){if(this.schemas[C]||this.refs[C])throw new Error(`schema with key or id "${C}" already exists`)}_compileSchemaEnv(C){if(C.meta?this._compileMetaSchema(C):s.compileSchema.call(this,C),!C.validate)throw new Error("ajv implementation error");return C.validate}_compileMetaSchema(C){const N=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,C)}finally{this.opts=N}}}S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function v(V,C,N,L="error"){for(const I in V){const k=I;k in C&&this.logger[L](`${N}: option ${I}. ${V[k]}`)}}function _(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function $(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const C in V)this.addSchema(V[C],C)}function T(){for(const V in this.opts.formats){const C=this.opts.formats[V];C&&this.addFormat(V,C)}}function R(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const C in V){const N=V[C];N.keyword||(N.keyword=C),this.addKeyword(N)}}function x(){const V={...this.opts};for(const C of h)delete V[C];return V}const E={log(){},warn(){},error(){}};function A(V){if(V===!1)return E;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const D=/^[a-z_$][a-z0-9_$:-]*$/i;function U(V,C){const{RULES:N}=this;if((0,u.eachItem)(V,L=>{if(N.keywords[L])throw new Error(`Keyword ${L} is already defined`);if(!D.test(L))throw new Error(`Keyword ${L} has invalid name`)}),!!C&&C.$data&&!("code"in C||"validate"in C))throw new Error('$data keyword must have "code" or "validate" function')}function K(V,C,N){var L;const I=C?.post;if(N&&I)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:k}=this;let O=I?k.post:k.rules.find(({type:B})=>B===N);if(O||(O={type:N,rules:[]},k.rules.push(O)),k.keywords[V]=!0,!C)return;const q={keyword:V,definition:{...C,type:(0,c.getJSONTypes)(C.type),schemaType:(0,c.getJSONTypes)(C.schemaType)}};C.before?G.call(this,O,q,C.before):O.rules.push(q),k.all[V]=q,(L=C.implements)===null||L===void 0||L.forEach(B=>this.addKeyword(B))}function G(V,C,N){const L=V.rules.findIndex(I=>I.keyword===N);L>=0?V.rules.splice(L,0,C):(V.rules.push(C),this.logger.warn(`rule ${N} is not defined`))}function te(V){let{metaSchema:C}=V;C!==void 0&&(V.$data&&this.opts.$data&&(C=ue(C)),V.validateSchema=this.compile(C,!0))}const X={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ue(V){return{anyOf:[V,X]}}})(core$1)),core$1}var draft7={},core={},id={},hasRequiredId;function requireId(){if(hasRequiredId)return id;hasRequiredId=1,Object.defineProperty(id,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return id.default=e,id}var ref={},hasRequiredRef;function requireRef(){if(hasRequiredRef)return ref;hasRequiredRef=1,Object.defineProperty(ref,"__esModule",{value:!0}),ref.callRef=ref.getValidate=void 0;const e=requireRef_error(),t=requireCode(),r=requireCodegen(),n=requireNames(),o=requireCompile(),a=requireUtil(),s={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:d,it:p}=c,{baseId:f,schemaEnv:h,validateName:b,opts:y,self:w}=p,{root:g}=h;if((d==="#"||d==="#/")&&f===g.baseId)return S();const m=o.resolveRef.call(w,g,f,d);if(m===void 0)throw new e.default(p.opts.uriResolver,f,d);if(m instanceof o.SchemaEnv)return v(m);return _(m);function S(){if(h===g)return l(c,b,h,h.$async);const $=u.scopeValue("root",{ref:g});return l(c,(0,r._)`${$}.validate`,g,g.$async)}function v($){const T=i(c,$);l(c,T,$,$.$async)}function _($){const T=u.scopeValue("schema",y.code.source===!0?{ref:$,code:(0,r.stringify)($)}:{ref:$}),R=u.name("valid"),x=c.subschema({schema:$,dataTypes:[],schemaPath:r.nil,topSchemaRef:T,errSchemaPath:d},R);c.mergeEvaluated(x),c.ok(R)}}};function i(c,u){const{gen:d}=c;return u.validate?d.scopeValue("validate",{ref:u.validate}):(0,r._)`${d.scopeValue("wrapper",{ref:u})}.validate`}ref.getValidate=i;function l(c,u,d,p){const{gen:f,it:h}=c,{allErrors:b,schemaEnv:y,opts:w}=h,g=w.passContext?n.default.this:r.nil;p?m():S();function m(){if(!y.$async)throw new Error("async schema referenced by sync schema");const $=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,g)}`),_(u),b||f.assign($,!0)},T=>{f.if((0,r._)`!(${T} instanceof ${h.ValidationError})`,()=>f.throw(T)),v(T),b||f.assign($,!1)}),c.ok($)}function S(){c.result((0,t.callValidateCode)(c,u,g),()=>_(u),()=>v(u))}function v($){const T=(0,r._)`${$}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${T} : ${n.default.vErrors}.concat(${T})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function _($){var T;if(!h.opts.unevaluated)return;const R=(T=d?.validate)===null||T===void 0?void 0:T.evaluated;if(h.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(h.props=a.mergeEvaluated.props(f,R.props,h.props));else{const x=f.var("props",(0,r._)`${$}.evaluated.props`);h.props=a.mergeEvaluated.props(f,x,h.props,r.Name)}if(h.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(h.items=a.mergeEvaluated.items(f,R.items,h.items));else{const x=f.var("items",(0,r._)`${$}.evaluated.items`);h.items=a.mergeEvaluated.items(f,x,h.items,r.Name)}}}return ref.callRef=l,ref.default=s,ref}var hasRequiredCore;function requireCore(){if(hasRequiredCore)return core;hasRequiredCore=1,Object.defineProperty(core,"__esModule",{value:!0});const e=requireId(),t=requireRef(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return core.default=r,core}var validation={},limitNumber={},hasRequiredLimitNumber;function requireLimitNumber(){if(hasRequiredLimitNumber)return limitNumber;hasRequiredLimitNumber=1,Object.defineProperty(limitNumber,"__esModule",{value:!0});const e=requireCodegen(),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:s})=>(0,e.str)`must be ${r[a].okStr} ${s}`,params:({keyword:a,schemaCode:s})=>(0,e._)`{comparison: ${r[a].okStr}, limit: ${s}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(a){const{keyword:s,data:i,schemaCode:l}=a;a.fail$data((0,e._)`${i} ${r[s].fail} ${l} || isNaN(${i})`)}};return limitNumber.default=o,limitNumber}var multipleOf={},hasRequiredMultipleOf;function requireMultipleOf(){if(hasRequiredMultipleOf)return multipleOf;hasRequiredMultipleOf=1,Object.defineProperty(multipleOf,"__esModule",{value:!0});const e=requireCodegen(),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:s,it:i}=n,l=i.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._)`(${s} === 0 || (${c} = ${a}/${s}, ${u}))`)}};return multipleOf.default=r,multipleOf}var limitLength={},ucs2length$1={},hasRequiredUcs2length;function requireUcs2length(){if(hasRequiredUcs2length)return ucs2length$1;hasRequiredUcs2length=1,Object.defineProperty(ucs2length$1,"__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 ucs2length$1.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ucs2length$1}var hasRequiredLimitLength;function requireLimitLength(){if(hasRequiredLimitLength)return limitLength;hasRequiredLimitLength=1,Object.defineProperty(limitLength,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),r=requireUcs2length(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:a,schemaCode:s}){const i=a==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${s} characters`},params:({schemaCode:a})=>(0,e._)`{limit: ${a}}`},code(a){const{keyword:s,data:i,schemaCode:l,it:c}=a,u=s==="maxLength"?e.operators.GT:e.operators.LT,d=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(a.gen,r.default)}(${i})`;a.fail$data((0,e._)`${d} ${u} ${l}`)}};return limitLength.default=o,limitLength}var pattern={},hasRequiredPattern;function requirePattern(){if(hasRequiredPattern)return pattern;hasRequiredPattern=1,Object.defineProperty(pattern,"__esModule",{value:!0});const e=requireCode(),t=requireUtil(),r=requireCodegen(),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:s,data:i,$data:l,schema:c,schemaCode:u,it:d}=a,p=d.opts.unicodeRegExp?"u":"";if(l){const{regExp:f}=d.opts.code,h=f.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(s,f),b=s.let("valid");s.try(()=>s.assign(b,(0,r._)`${h}(${u}, ${p}).test(${i})`),()=>s.assign(b,!1)),a.fail$data((0,r._)`!${b}`)}else{const f=(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${f}.test(${i})`)}}};return pattern.default=o,pattern}var limitProperties={},hasRequiredLimitProperties;function requireLimitProperties(){if(hasRequiredLimitProperties)return limitProperties;hasRequiredLimitProperties=1,Object.defineProperty(limitProperties,"__esModule",{value:!0});const e=requireCodegen(),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:s}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${a}).length ${i} ${s}`)}};return limitProperties.default=r,limitProperties}var required$1={},hasRequiredRequired;function requireRequired(){if(hasRequiredRequired)return required$1;hasRequiredRequired=1,Object.defineProperty(required$1,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireUtil(),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:s,schema:i,schemaCode:l,data:c,$data:u,it:d}=a,{opts:p}=d;if(!u&&i.length===0)return;const f=i.length>=p.loopRequired;if(d.allErrors?h():b(),p.strictRequired){const g=a.parentSchema.properties,{definedProperties:m}=a.it;for(const S of i)if(g?.[S]===void 0&&!m.has(S)){const v=d.schemaEnv.baseId+d.errSchemaPath,_=`required property "${S}" is not defined at "${v}" (strictRequired)`;(0,r.checkStrictMode)(d,_,d.opts.strictRequired)}}function h(){if(f||u)a.block$data(t.nil,y);else for(const g of i)(0,e.checkReportMissingProp)(a,g)}function b(){const g=s.let("missing");if(f||u){const m=s.let("valid",!0);a.block$data(m,()=>w(g,m)),a.ok(m)}else s.if((0,e.checkMissingProp)(a,i,g)),(0,e.reportMissingProp)(a,g),s.else()}function y(){s.forOf("prop",l,g=>{a.setParams({missingProperty:g}),s.if((0,e.noPropertyInData)(s,c,g,p.ownProperties),()=>a.error())})}function w(g,m){a.setParams({missingProperty:g}),s.forOf(g,l,()=>{s.assign(m,(0,e.propertyInData)(s,c,g,p.ownProperties)),s.if((0,t.not)(m),()=>{a.error(),s.break()})},t.nil)}}};return required$1.default=o,required$1}var limitItems={},hasRequiredLimitItems;function requireLimitItems(){if(hasRequiredLimitItems)return limitItems;hasRequiredLimitItems=1,Object.defineProperty(limitItems,"__esModule",{value:!0});const e=requireCodegen(),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:s}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${a}.length ${i} ${s}`)}};return limitItems.default=r,limitItems}var uniqueItems={},equal={},hasRequiredEqual;function requireEqual(){if(hasRequiredEqual)return equal;hasRequiredEqual=1,Object.defineProperty(equal,"__esModule",{value:!0});const e=requireFastDeepEqual();return e.code='require("ajv/dist/runtime/equal").default',equal.default=e,equal}var hasRequiredUniqueItems;function requireUniqueItems(){if(hasRequiredUniqueItems)return uniqueItems;hasRequiredUniqueItems=1,Object.defineProperty(uniqueItems,"__esModule",{value:!0});const e=requireDataType(),t=requireCodegen(),r=requireUtil(),n=requireEqual(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:s,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${s} are identical)`,params:({params:{i:s,j:i}})=>(0,t._)`{i: ${s}, j: ${i}}`},code(s){const{gen:i,data:l,$data:c,schema:u,parentSchema:d,schemaCode:p,it:f}=s;if(!c&&!u)return;const h=i.let("valid"),b=d.items?(0,e.getSchemaTypes)(d.items):[];s.block$data(h,y,(0,t._)`${p} === false`),s.ok(h);function y(){const S=i.let("i",(0,t._)`${l}.length`),v=i.let("j");s.setParams({i:S,j:v}),i.assign(h,!0),i.if((0,t._)`${S} > 1`,()=>(w()?g:m)(S,v))}function w(){return b.length>0&&!b.some(S=>S==="object"||S==="array")}function g(S,v){const _=i.name("item"),$=(0,e.checkDataTypes)(b,_,f.opts.strictNumbers,e.DataType.Wrong),T=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${S}--;`,()=>{i.let(_,(0,t._)`${l}[${S}]`),i.if($,(0,t._)`continue`),b.length>1&&i.if((0,t._)`typeof ${_} == "string"`,(0,t._)`${_} += "_"`),i.if((0,t._)`typeof ${T}[${_}] == "number"`,()=>{i.assign(v,(0,t._)`${T}[${_}]`),s.error(),i.assign(h,!1).break()}).code((0,t._)`${T}[${_}] = ${S}`)})}function m(S,v){const _=(0,r.useFunc)(i,n.default),$=i.name("outer");i.label($).for((0,t._)`;${S}--;`,()=>i.for((0,t._)`${v} = ${S}; ${v}--;`,()=>i.if((0,t._)`${_}(${l}[${S}], ${l}[${v}])`,()=>{s.error(),i.assign(h,!1).break($)})))}}};return uniqueItems.default=a,uniqueItems}var _const={},hasRequired_const;function require_const(){if(hasRequired_const)return _const;hasRequired_const=1,Object.defineProperty(_const,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),r=requireEqual(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:a})=>(0,e._)`{allowedValue: ${a}}`},code(a){const{gen:s,data:i,$data:l,schemaCode:c,schema:u}=a;l||u&&typeof u=="object"?a.fail$data((0,e._)`!${(0,t.useFunc)(s,r.default)}(${i}, ${c})`):a.fail((0,e._)`${u} !== ${i}`)}};return _const.default=o,_const}var _enum$1={},hasRequired_enum;function require_enum(){if(hasRequired_enum)return _enum$1;hasRequired_enum=1,Object.defineProperty(_enum$1,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),r=requireEqual(),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:s,data:i,$data:l,schema:c,schemaCode:u,it:d}=a;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=d.opts.loopEnum;let f;const h=()=>f??(f=(0,t.useFunc)(s,r.default));let b;if(p||l)b=s.let("valid"),a.block$data(b,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const g=s.const("vSchema",u);b=(0,e.or)(...c.map((m,S)=>w(g,S)))}a.pass(b);function y(){s.assign(b,!1),s.forOf("v",u,g=>s.if((0,e._)`${h()}(${i}, ${g})`,()=>s.assign(b,!0).break()))}function w(g,m){const S=c[m];return typeof S=="object"&&S!==null?(0,e._)`${h()}(${i}, ${g}[${m}])`:(0,e._)`${i} === ${S}`}}};return _enum$1.default=o,_enum$1}var hasRequiredValidation;function requireValidation(){if(hasRequiredValidation)return validation;hasRequiredValidation=1,Object.defineProperty(validation,"__esModule",{value:!0});const e=requireLimitNumber(),t=requireMultipleOf(),r=requireLimitLength(),n=requirePattern(),o=requireLimitProperties(),a=requireRequired(),s=requireLimitItems(),i=requireUniqueItems(),l=require_const(),c=require_enum(),u=[e.default,t.default,r.default,n.default,o.default,a.default,s.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return validation.default=u,validation}var applicator={},additionalItems={},hasRequiredAdditionalItems;function requireAdditionalItems(){if(hasRequiredAdditionalItems)return additionalItems;hasRequiredAdditionalItems=1,Object.defineProperty(additionalItems,"__esModule",{value:!0}),additionalItems.validateAdditionalItems=void 0;const e=requireCodegen(),t=requireUtil(),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:s,it:i}=a,{items:l}=s;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(a,l)}};function o(a,s){const{gen:i,schema:l,data:c,keyword:u,it:d}=a;d.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)a.setParams({len:s.length}),a.pass((0,e._)`${p} <= ${s.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(d,l)){const h=i.var("valid",(0,e._)`${p} <= ${s.length}`);i.if((0,e.not)(h),()=>f(h)),a.ok(h)}function f(h){i.forRange("i",s.length,p,b=>{a.subschema({keyword:u,dataProp:b,dataPropType:t.Type.Num},h),d.allErrors||i.if((0,e.not)(h),()=>i.break())})}}return additionalItems.validateAdditionalItems=o,additionalItems.default=n,additionalItems}var prefixItems={},items={},hasRequiredItems;function requireItems(){if(hasRequiredItems)return items;hasRequiredItems=1,Object.defineProperty(items,"__esModule",{value:!0}),items.validateTuple=void 0;const e=requireCodegen(),t=requireUtil(),r=requireCode(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){const{schema:s,it:i}=a;if(Array.isArray(s))return o(a,"additionalItems",s);i.items=!0,!(0,t.alwaysValidSchema)(i,s)&&a.ok((0,r.validateArray)(a))}};function o(a,s,i=a.schema){const{gen:l,parentSchema:c,data:u,keyword:d,it:p}=a;b(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const f=l.name("valid"),h=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${h} > ${w}`,()=>a.subschema({keyword:d,schemaProp:w,dataProp:w},f)),a.ok(f))});function b(y){const{opts:w,errSchemaPath:g}=p,m=i.length,S=m===y.minItems&&(m===y.maxItems||y[s]===!1);if(w.strictTuples&&!S){const v=`"${d}" is ${m}-tuple, but minItems or maxItems/${s} are not specified or different at path "${g}"`;(0,t.checkStrictMode)(p,v,w.strictTuples)}}}return items.validateTuple=o,items.default=n,items}var hasRequiredPrefixItems;function requirePrefixItems(){if(hasRequiredPrefixItems)return prefixItems;hasRequiredPrefixItems=1,Object.defineProperty(prefixItems,"__esModule",{value:!0});const e=requireItems(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return prefixItems.default=t,prefixItems}var items2020={},hasRequiredItems2020;function requireItems2020(){if(hasRequiredItems2020)return items2020;hasRequiredItems2020=1,Object.defineProperty(items2020,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),r=requireCode(),n=requireAdditionalItems(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{schema:i,parentSchema:l,it:c}=s,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(s,u):s.ok((0,r.validateArray)(s)))}};return items2020.default=a,items2020}var contains={},hasRequiredContains;function requireContains(){if(hasRequiredContains)return contains;hasRequiredContains=1,Object.defineProperty(contains,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),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:s,parentSchema:i,data:l,it:c}=o;let u,d;const{minContains:p,maxContains:f}=i;c.opts.next?(u=p===void 0?1:p,d=f):u=1;const h=a.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:d}),d===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(d!==void 0&&u>d){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,s)){let m=(0,e._)`${h} >= ${u}`;d!==void 0&&(m=(0,e._)`${m} && ${h} <= ${d}`),o.pass(m);return}c.items=!0;const b=a.name("valid");d===void 0&&u===1?w(b,()=>a.if(b,()=>a.break())):u===0?(a.let(b,!0),d!==void 0&&a.if((0,e._)`${l}.length > 0`,y)):(a.let(b,!1),y()),o.result(b,()=>o.reset());function y(){const m=a.name("_valid"),S=a.let("count",0);w(m,()=>a.if(m,()=>g(S)))}function w(m,S){a.forRange("i",0,h,v=>{o.subschema({keyword:"contains",dataProp:v,dataPropType:t.Type.Num,compositeRule:!0},m),S()})}function g(m){a.code((0,e._)`${m}++`),d===void 0?a.if((0,e._)`${m} >= ${u}`,()=>a.assign(b,!0).break()):(a.if((0,e._)`${m} > ${d}`,()=>a.assign(b,!1).break()),u===1?a.assign(b,!0):a.if((0,e._)`${m} >= ${u}`,()=>a.assign(b,!0)))}}};return contains.default=n,contains}var dependencies={},hasRequiredDependencies;function requireDependencies(){return hasRequiredDependencies||(hasRequiredDependencies=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=requireCodegen(),r=requireUtil(),n=requireCode();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const d=c===1?"property":"properties";return(0,t.str)`must have ${d} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:d}})=>(0,t._)`{property: ${l},
|
|
6
|
-
missingProperty: ${d},
|
|
7
|
-
depsCount: ${c},
|
|
8
|
-
deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=a(l);s(l,c),i(l,u)}};function a({schema:l}){const c={},u={};for(const d in l){if(d==="__proto__")continue;const p=Array.isArray(l[d])?c:u;p[d]=l[d]}return[c,u]}function s(l,c=l.schema){const{gen:u,data:d,it:p}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const h in c){const b=c[h];if(b.length===0)continue;const y=(0,n.propertyInData)(u,d,h,p.opts.ownProperties);l.setParams({property:h,depsCount:b.length,deps:b.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of b)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,b,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=s;function i(l,c=l.schema){const{gen:u,data:d,keyword:p,it:f}=l,h=u.name("valid");for(const b in c)(0,r.alwaysValidSchema)(f,c[b])||(u.if((0,n.propertyInData)(u,d,b,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:b},h);l.mergeValidEvaluated(y,h)},()=>u.var(h,!0)),l.ok(h))}e.validateSchemaDeps=i,e.default=o})(dependencies)),dependencies}var propertyNames={},hasRequiredPropertyNames;function requirePropertyNames(){if(hasRequiredPropertyNames)return propertyNames;hasRequiredPropertyNames=1,Object.defineProperty(propertyNames,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),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:s,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,s))return;const c=a.name("valid");a.forIn("key",i,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 propertyNames.default=n,propertyNames}var additionalProperties={},hasRequiredAdditionalProperties;function requireAdditionalProperties(){if(hasRequiredAdditionalProperties)return additionalProperties;hasRequiredAdditionalProperties=1,Object.defineProperty(additionalProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireNames(),n=requireUtil(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:s})=>(0,t._)`{additionalProperty: ${s.additionalProperty}}`},code(s){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:d,it:p}=s;if(!d)throw new Error("ajv implementation error");const{allErrors:f,opts:h}=p;if(p.props=!0,h.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const b=(0,e.allSchemaProperties)(c.properties),y=(0,e.allSchemaProperties)(c.patternProperties);w(),s.ok((0,t._)`${d} === ${r.default.errors}`);function w(){i.forIn("key",u,_=>{!b.length&&!y.length?S(_):i.if(g(_),()=>S(_))})}function g(_){let $;if(b.length>8){const T=(0,n.schemaRefOrVal)(p,c.properties,"properties");$=(0,e.isOwnProperty)(i,T,_)}else b.length?$=(0,t.or)(...b.map(T=>(0,t._)`${_} === ${T}`)):$=t.nil;return y.length&&($=(0,t.or)($,...y.map(T=>(0,t._)`${(0,e.usePattern)(s,T)}.test(${_})`))),(0,t.not)($)}function m(_){i.code((0,t._)`delete ${u}[${_}]`)}function S(_){if(h.removeAdditional==="all"||h.removeAdditional&&l===!1){m(_);return}if(l===!1){s.setParams({additionalProperty:_}),s.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const $=i.name("valid");h.removeAdditional==="failing"?(v(_,$,!1),i.if((0,t.not)($),()=>{s.reset(),m(_)})):(v(_,$),f||i.if((0,t.not)($),()=>i.break()))}}function v(_,$,T){const R={keyword:"additionalProperties",dataProp:_,dataPropType:n.Type.Str};T===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(R,$)}}};return additionalProperties.default=a,additionalProperties}var properties$1={},hasRequiredProperties;function requireProperties(){if(hasRequiredProperties)return properties$1;hasRequiredProperties=1,Object.defineProperty(properties$1,"__esModule",{value:!0});const e=requireValidate(),t=requireCode(),r=requireUtil(),n=requireAdditionalProperties(),o={keyword:"properties",type:"object",schemaType:"object",code(a){const{gen:s,schema:i,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 d=(0,t.allSchemaProperties)(i);for(const y of d)u.definedProperties.add(y);u.opts.unevaluated&&d.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(s,(0,r.toHash)(d),u.props));const p=d.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(p.length===0)return;const f=s.name("valid");for(const y of p)h(y)?b(y):(s.if((0,t.propertyInData)(s,c,y,u.opts.ownProperties)),b(y),u.allErrors||s.else().var(f,!0),s.endIf()),a.it.definedProperties.add(y),a.ok(f);function h(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function b(y){a.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return properties$1.default=o,properties$1}var patternProperties={},hasRequiredPatternProperties;function requirePatternProperties(){if(hasRequiredPatternProperties)return patternProperties;hasRequiredPatternProperties=1,Object.defineProperty(patternProperties,"__esModule",{value:!0});const e=requireCode(),t=requireCodegen(),r=requireUtil(),n=requireUtil(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(a){const{gen:s,schema:i,data:l,parentSchema:c,it:u}=a,{opts:d}=u,p=(0,e.allSchemaProperties)(i),f=p.filter(S=>(0,r.alwaysValidSchema)(u,i[S]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const h=d.strictSchema&&!d.allowMatchingProperties&&c.properties,b=s.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(s,u.props));const{props:y}=u;w();function w(){for(const S of p)h&&g(S),u.allErrors?m(S):(s.var(b,!0),m(S),s.if(b))}function g(S){for(const v in h)new RegExp(S).test(v)&&(0,r.checkStrictMode)(u,`property ${v} matches pattern ${S} (use allowMatchingProperties)`)}function m(S){s.forIn("key",l,v=>{s.if((0,t._)`${(0,e.usePattern)(a,S)}.test(${v})`,()=>{const _=f.includes(S);_||a.subschema({keyword:"patternProperties",schemaProp:S,dataProp:v,dataPropType:n.Type.Str},b),u.opts.unevaluated&&y!==!0?s.assign((0,t._)`${y}[${v}]`,!0):!_&&!u.allErrors&&s.if((0,t.not)(b),()=>s.break())})})}}};return patternProperties.default=o,patternProperties}var not={},hasRequiredNot;function requireNot(){if(hasRequiredNot)return not;hasRequiredNot=1,Object.defineProperty(not,"__esModule",{value:!0});const e=requireUtil(),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 s=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),r.failResult(s,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return not.default=t,not}var anyOf={},hasRequiredAnyOf;function requireAnyOf(){if(hasRequiredAnyOf)return anyOf;hasRequiredAnyOf=1,Object.defineProperty(anyOf,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:requireCode().validateUnion,error:{message:"must match a schema in anyOf"}};return anyOf.default=t,anyOf}var oneOf={},hasRequiredOneOf;function requireOneOf(){if(hasRequiredOneOf)return oneOf;hasRequiredOneOf=1,Object.defineProperty(oneOf,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),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:s,parentSchema:i,it:l}=o;if(!Array.isArray(s))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=s,u=a.let("valid",!1),d=a.let("passing",null),p=a.name("_valid");o.setParams({passing:d}),a.block(f),o.result(u,()=>o.reset(),()=>o.error(!0));function f(){c.forEach((h,b)=>{let y;(0,t.alwaysValidSchema)(l,h)?a.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:b,compositeRule:!0},p),b>0&&a.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(d,(0,e._)`[${d}, ${b}]`).else(),a.if(p,()=>{a.assign(u,!0),a.assign(d,b),y&&o.mergeEvaluated(y,e.Name)})})}}};return oneOf.default=n,oneOf}var allOf={},hasRequiredAllOf;function requireAllOf(){if(hasRequiredAllOf)return allOf;hasRequiredAllOf=1,Object.defineProperty(allOf,"__esModule",{value:!0});const e=requireUtil(),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 s=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(a,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},s);r.ok(s),r.mergeEvaluated(c)})}};return allOf.default=t,allOf}var _if={},hasRequired_if;function require_if(){if(hasRequired_if)return _if;hasRequired_if=1,Object.defineProperty(_if,"__esModule",{value:!0});const e=requireCodegen(),t=requireUtil(),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:s,parentSchema:i,it:l}=a;i.then===void 0&&i.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 d=s.let("valid",!0),p=s.name("_valid");if(f(),a.reset(),c&&u){const b=s.let("ifClause");a.setParams({ifClause:b}),s.if(p,h("then",b),h("else",b))}else c?s.if(p,h("then")):s.if((0,e.not)(p),h("else"));a.pass(d,()=>a.error(!0));function f(){const b=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);a.mergeEvaluated(b)}function h(b,y){return()=>{const w=a.subschema({keyword:b},p);s.assign(d,p),a.mergeValidEvaluated(w,d),y?s.assign(y,(0,e._)`${b}`):a.setParams({ifClause:b})}}}};function o(a,s){const i=a.schema[s];return i!==void 0&&!(0,t.alwaysValidSchema)(a,i)}return _if.default=n,_if}var thenElse={},hasRequiredThenElse;function requireThenElse(){if(hasRequiredThenElse)return thenElse;hasRequiredThenElse=1,Object.defineProperty(thenElse,"__esModule",{value:!0});const e=requireUtil(),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 thenElse.default=t,thenElse}var hasRequiredApplicator;function requireApplicator(){if(hasRequiredApplicator)return applicator;hasRequiredApplicator=1,Object.defineProperty(applicator,"__esModule",{value:!0});const e=requireAdditionalItems(),t=requirePrefixItems(),r=requireItems(),n=requireItems2020(),o=requireContains(),a=requireDependencies(),s=requirePropertyNames(),i=requireAdditionalProperties(),l=requireProperties(),c=requirePatternProperties(),u=requireNot(),d=requireAnyOf(),p=requireOneOf(),f=requireAllOf(),h=require_if(),b=requireThenElse();function y(w=!1){const g=[u.default,d.default,p.default,f.default,h.default,b.default,s.default,i.default,a.default,l.default,c.default];return w?g.push(t.default,n.default):g.push(e.default,r.default),g.push(o.default),g}return applicator.default=y,applicator}var format$2={},format$1={},hasRequiredFormat$1;function requireFormat$1(){if(hasRequiredFormat$1)return format$1;hasRequiredFormat$1=1,Object.defineProperty(format$1,"__esModule",{value:!0});const e=requireCodegen(),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:s,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:d,errSchemaPath:p,schemaEnv:f,self:h}=u;if(!d.validateFormats)return;i?b():y();function b(){const w=a.scopeValue("formats",{ref:h.formats,code:d.code.formats}),g=a.const("fDef",(0,e._)`${w}[${c}]`),m=a.let("fType"),S=a.let("format");a.if((0,e._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>a.assign(m,(0,e._)`${g}.type || "string"`).assign(S,(0,e._)`${g}.validate`),()=>a.assign(m,(0,e._)`"string"`).assign(S,g)),n.fail$data((0,e.or)(v(),_()));function v(){return d.strictSchema===!1?e.nil:(0,e._)`${c} && !${S}`}function _(){const $=f.$async?(0,e._)`(${g}.async ? await ${S}(${s}) : ${S}(${s}))`:(0,e._)`${S}(${s})`,T=(0,e._)`(typeof ${S} == "function" ? ${$} : ${S}.test(${s}))`;return(0,e._)`${S} && ${S} !== true && ${m} === ${o} && !${T}`}}function y(){const w=h.formats[l];if(!w){v();return}if(w===!0)return;const[g,m,S]=_(w);g===o&&n.pass($());function v(){if(d.strictSchema===!1){h.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function _(T){const R=T instanceof RegExp?(0,e.regexpCode)(T):d.code.formats?(0,e._)`${d.code.formats}${(0,e.getProperty)(l)}`:void 0,x=a.scopeValue("formats",{key:l,ref:T,code:R});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,e._)`${x}.validate`]:["string",T,x]}function $(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${s})`}return typeof m=="function"?(0,e._)`${S}(${s})`:(0,e._)`${S}.test(${s})`}}}};return format$1.default=r,format$1}var hasRequiredFormat;function requireFormat(){if(hasRequiredFormat)return format$2;hasRequiredFormat=1,Object.defineProperty(format$2,"__esModule",{value:!0});const t=[requireFormat$1().default];return format$2.default=t,format$2}var metadata={},hasRequiredMetadata;function requireMetadata(){return hasRequiredMetadata||(hasRequiredMetadata=1,Object.defineProperty(metadata,"__esModule",{value:!0}),metadata.contentVocabulary=metadata.metadataVocabulary=void 0,metadata.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],metadata.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),metadata}var hasRequiredDraft7;function requireDraft7(){if(hasRequiredDraft7)return draft7;hasRequiredDraft7=1,Object.defineProperty(draft7,"__esModule",{value:!0});const e=requireCore(),t=requireValidation(),r=requireApplicator(),n=requireFormat(),o=requireMetadata(),a=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return draft7.default=a,draft7}var discriminator={},types={},hasRequiredTypes;function requireTypes(){if(hasRequiredTypes)return types;hasRequiredTypes=1,Object.defineProperty(types,"__esModule",{value:!0}),types.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(types.DiscrError=e={})),types}var hasRequiredDiscriminator;function requireDiscriminator(){if(hasRequiredDiscriminator)return discriminator;hasRequiredDiscriminator=1,Object.defineProperty(discriminator,"__esModule",{value:!0});const e=requireCodegen(),t=requireTypes(),r=requireCompile(),n=requireRef_error(),o=requireUtil(),s={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:d,it:p}=i,{oneOf:f}=d;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=u.propertyName;if(typeof h!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!f)throw new Error("discriminator: requires oneOf keyword");const b=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(h)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:h})),i.ok(b);function w(){const S=m();l.if(!1);for(const v in S)l.elseIf((0,e._)`${y} === ${v}`),l.assign(b,g(S[v]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:h}),l.endIf()}function g(S){const v=l.name("valid"),_=i.subschema({keyword:"oneOf",schemaProp:S},v);return i.mergeEvaluated(_,e.Name),v}function m(){var S;const v={},_=T(d);let $=!0;for(let E=0;E<f.length;E++){let A=f[E];if(A?.$ref&&!(0,o.schemaHasRulesButRef)(A,p.self.RULES)){const U=A.$ref;if(A=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,U),A instanceof r.SchemaEnv&&(A=A.schema),A===void 0)throw new n.default(p.opts.uriResolver,p.baseId,U)}const D=(S=A?.properties)===null||S===void 0?void 0:S[h];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);$=$&&(_||T(A)),R(D,E)}if(!$)throw new Error(`discriminator: "${h}" must be required`);return v;function T({required:E}){return Array.isArray(E)&&E.includes(h)}function R(E,A){if(E.const)x(E.const,A);else if(E.enum)for(const D of E.enum)x(D,A);else throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}function x(E,A){if(typeof E!="string"||E in v)throw new Error(`discriminator: "${h}" values must be unique strings`);v[E]=A}}}};return discriminator.default=s,discriminator}const $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:"#"}},require$$3={$schema,$id,title,definitions,type,properties,default:!0};var hasRequiredAjv;function requireAjv(){return hasRequiredAjv||(hasRequiredAjv=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=requireCore$1(),n=requireDraft7(),o=requireDiscriminator(),a=require$$3,s=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const h=this.opts.$data?this.$dataMetaSchema(a,s):a;this.addMetaSchema(h,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=requireValidate();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=requireCodegen();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 d=requireValidation_error();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=requireRef_error();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(ajv,ajv.exports)),ajv.exports}var ajvExports=requireAjv();const Ajv=getDefaultExportFromCjs(ajvExports);var util;(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 s of o)a[s]=s;return a},e.getValidEnumValues=o=>{const a=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),s={};for(const i of a)s[i]=o[i];return e.objectValues(s)},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 s in o)Object.prototype.hasOwnProperty.call(o,s)&&a.push(s);return a},e.find=(o,a)=>{for(const s of o)if(a(s))return s},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(s=>typeof s=="string"?`'${s}'`:s).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a})(util||(util={}));var objectUtil;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=e=>{switch(typeof e){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&e instanceof Map?ZodParsedType.map:typeof Set<"u"&&e instanceof Set?ZodParsedType.set:typeof Date<"u"&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode$1=util.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"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError 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 s of a.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let i=n,l=0;for(;l<s.path.length;){const c=s.path[l];l===s.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(s))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof ZodError))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.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()}}ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let r;switch(e.code){case ZodIssueCode$1.invalid_type:e.received===ZodParsedType.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode$1.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode$1.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(e.keys,", ")}`;break;case ZodIssueCode$1.invalid_union:r="Invalid input";break;case ZodIssueCode$1.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode$1.invalid_enum_value:r=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode$1.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode$1.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode$1.invalid_date:r="Invalid date";break;case ZodIssueCode$1.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}"`:util.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ZodIssueCode$1.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 ZodIssueCode$1.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 ZodIssueCode$1.custom:r="Invalid input";break;case ZodIssueCode$1.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode$1.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode$1.not_finite:r="Number must be finite";break;default:r=t.defaultError,util.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function setErrorMap(e){overrideErrorMap=e}function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,a=[...r,...o.path||[]],s={...o,path:a};if(o.message!==void 0)return{...o,path:a,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(s,{data:t,defaultError:i}).message;return{...o,path:a,message:i}},EMPTY_PATH=[];function addIssueToContext(e,t){const r=getErrorMap(),n=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter(o=>!!o)});e.common.issues.push(n)}class ParseStatus{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 INVALID;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,s=await o.value;n.push({key:a,value:s})}return ParseStatus.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:a,value:s}=o;if(a.status==="aborted"||s.status==="aborted")return INVALID;a.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(n[a.value]=s.value)}return{status:t.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=e=>({status:"dirty",value:e}),OK=e=>({status:"valid",value:e}),isAborted=e=>e.status==="aborted",isDirty=e=>e.status==="dirty",isValid=e=>e.status==="valid",isAsync=e=>typeof Promise<"u"&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{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 handleResult=(e,t)=>{if(isValid(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 ZodError(e.common.issues);return this._error=r,this._error}}};function processCreateParams(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:(s,i)=>{const{message:l}=e;return s.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:s.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}let ZodType$1=class{get description(){return this._def.description}_getType(t){return getParsedType(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:getParsedType(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ParseStatus,ctx:{common:t.parent.common,data:t.data,parsedType:getParsedType(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(isAsync(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:getParsedType(t)},o=this._parseSync({data:t,path:n.path,parent:n});return handleResult(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:getParsedType(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return isValid(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=>isValid(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:getParsedType(t)},o=this._parse({data:t,path:n.path,parent:n}),a=await(isAsync(o)?o:Promise.resolve(o));return handleResult(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 s=t(o),i=()=>a.addIssue({code:ZodIssueCode$1.custom,...n(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(i(),!1)):s?!0:(i(),!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 ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.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 ZodOptional$1.create(this,this._def)}nullable(){return ZodNullable$1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray$1.create(this)}promise(){return ZodPromise.create(this,this._def)}or(t){return ZodUnion$1.create([this,t],this._def)}and(t){return ZodIntersection$1.create(this,t,this._def)}transform(t){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new ZodDefault$1({...processCreateParams(this._def),innerType:this,defaultValue:r,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ZodCatch$1({...processCreateParams(this._def),innerType:this,catchValue:r,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return ZodPipeline.create(this,t)}readonly(){return ZodReadonly$1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?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)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex$2;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(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 timeRegex(e){return new RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(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 isValidIP(e,t){return!!((t==="v4"||!t)&&ipv4Regex.test(e)||(t==="v6"||!t)&&ipv6Regex.test(e))}function isValidJWT$1(e,t){if(!jwtRegex.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 isValidCidr(e,t){return!!((t==="v4"||!t)&&ipv4CidrRegex.test(e)||(t==="v6"||!t)&&ipv6CidrRegex.test(e))}let ZodString$1=class $t extends ZodType$1{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ZodParsedType.string){const a=this._getOrReturnCtx(t);return addIssueToContext(a,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.string,received:a.parsedType}),INVALID}const n=new ParseStatus;let o;for(const a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.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),addIssueToContext(o,{code:ZodIssueCode$1.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const s=t.data.length>a.value,i=t.data.length<a.value;(s||i)&&(o=this._getOrReturnCtx(t,o),s?addIssueToContext(o,{code:ZodIssueCode$1.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&addIssueToContext(o,{code:ZodIssueCode$1.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")emailRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"email",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")emojiRegex$2||(emojiRegex$2=new RegExp(_emojiRegex,"u")),emojiRegex$2.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"emoji",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")uuidRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"uuid",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")nanoidRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"nanoid",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")cuidRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"cuid",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")cuid2Regex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"cuid2",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")ulidRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"ulid",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"url",code:ZodIssueCode$1.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),addIssueToContext(o,{validation:"regex",code:ZodIssueCode$1.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),addIssueToContext(o,{code:ZodIssueCode$1.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),addIssueToContext(o,{code:ZodIssueCode$1.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?datetimeRegex(a).test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?dateRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?timeRegex(a).test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?durationRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"duration",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?isValidIP(t.data,a.version)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"ip",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?isValidJWT$1(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"jwt",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?isValidCidr(t.data,a.version)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"cidr",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?base64Regex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"base64",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?base64urlRegex.test(t.data)||(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{validation:"base64url",code:ZodIssueCode$1.invalid_string,message:a.message}),n.dirty()):util.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:ZodIssueCode$1.invalid_string,...errorUtil.errToObj(n)})}_addCheck(t){return new $t({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...errorUtil.errToObj(t)})}url(t){return this._addCheck({kind:"url",...errorUtil.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...errorUtil.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...errorUtil.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...errorUtil.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...errorUtil.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...errorUtil.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...errorUtil.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...errorUtil.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...errorUtil.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...errorUtil.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,...errorUtil.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,...errorUtil.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...errorUtil.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...errorUtil.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...errorUtil.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...errorUtil.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...errorUtil.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...errorUtil.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...errorUtil.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...errorUtil.errToObj(r)})}nonempty(t){return this.min(1,errorUtil.errToObj(t))}trim(){return new $t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $t({...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}};ZodString$1.create=e=>new ZodString$1({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder$1(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(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return a%s/10**o}let ZodNumber$1=class Mt extends ZodType$1{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)!==ZodParsedType.number){const a=this._getOrReturnCtx(t);return addIssueToContext(a,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.number,received:a.parsedType}),INVALID}let n;const o=new ParseStatus;for(const a of this._def.checks)a.kind==="int"?util.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),addIssueToContext(n,{code:ZodIssueCode$1.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),addIssueToContext(n,{code:ZodIssueCode$1.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),addIssueToContext(n,{code:ZodIssueCode$1.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="multipleOf"?floatSafeRemainder$1(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),addIssueToContext(n,{code:ZodIssueCode$1.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),addIssueToContext(n,{code:ZodIssueCode$1.not_finite,message:a.message}),o.dirty()):util.assertNever(a);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,errorUtil.toString(r))}gt(t,r){return this.setLimit("min",t,!1,errorUtil.toString(r))}lte(t,r){return this.setLimit("max",t,!0,errorUtil.toString(r))}lt(t,r){return this.setLimit("max",t,!1,errorUtil.toString(r))}setLimit(t,r,n,o){return new Mt({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:errorUtil.toString(o)}]})}_addCheck(t){return new Mt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:errorUtil.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:errorUtil.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:errorUtil.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.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"&&util.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)}};ZodNumber$1.create=e=>new ZodNumber$1({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});class ZodBigInt extends ZodType$1{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)!==ZodParsedType.bigint)return this._getInvalidInput(t);let n;const o=new ParseStatus;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),addIssueToContext(n,{code:ZodIssueCode$1.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),addIssueToContext(n,{code:ZodIssueCode$1.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),addIssueToContext(n,{code:ZodIssueCode$1.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):util.assertNever(a);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.bigint,received:r.parsedType}),INVALID}gte(t,r){return this.setLimit("min",t,!0,errorUtil.toString(r))}gt(t,r){return this.setLimit("min",t,!1,errorUtil.toString(r))}lte(t,r){return this.setLimit("max",t,!0,errorUtil.toString(r))}lt(t,r){return this.setLimit("max",t,!1,errorUtil.toString(r))}setLimit(t,r,n,o){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:errorUtil.toString(o)}]})}_addCheck(t){return new ZodBigInt({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:errorUtil.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}}ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});let ZodBoolean$1=class extends ZodType$1{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(t.data)}};ZodBoolean$1.create=e=>new ZodBoolean$1({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});class ZodDate extends ZodType$1{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ZodParsedType.date){const a=this._getOrReturnCtx(t);return addIssueToContext(a,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.date,received:a.parsedType}),INVALID}if(Number.isNaN(t.data.getTime())){const a=this._getOrReturnCtx(t);return addIssueToContext(a,{code:ZodIssueCode$1.invalid_date}),INVALID}const n=new ParseStatus;let o;for(const a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),addIssueToContext(o,{code:ZodIssueCode$1.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),addIssueToContext(o,{code:ZodIssueCode$1.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):util.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ZodDate({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:errorUtil.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:errorUtil.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}}ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});class ZodSymbol extends ZodType$1{_parse(t){if(this._getType(t)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(t.data)}}ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});class ZodUndefined extends ZodType$1{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(t.data)}}ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});let ZodNull$1=class extends ZodType$1{_parse(t){if(this._getType(t)!==ZodParsedType.null){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(t.data)}};ZodNull$1.create=e=>new ZodNull$1({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});let ZodAny$1=class extends ZodType$1{constructor(){super(...arguments),this._any=!0}_parse(t){return OK(t.data)}};ZodAny$1.create=e=>new ZodAny$1({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});let ZodUnknown$1=class extends ZodType$1{constructor(){super(...arguments),this._unknown=!0}_parse(t){return OK(t.data)}};ZodUnknown$1.create=e=>new ZodUnknown$1({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});let ZodNever$1=class extends ZodType$1{_parse(t){const r=this._getOrReturnCtx(t);return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.never,received:r.parsedType}),INVALID}};ZodNever$1.create=e=>new ZodNever$1({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});class ZodVoid extends ZodType$1{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(t.data)}}ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});let ZodArray$1=class It extends ZodType$1{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(o.exactLength!==null){const s=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(s||i)&&(addIssueToContext(r,{code:s?ZodIssueCode$1.too_big:ZodIssueCode$1.too_small,minimum:i?o.exactLength.value:void 0,maximum:s?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&&(addIssueToContext(r,{code:ZodIssueCode$1.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&&(addIssueToContext(r,{code:ZodIssueCode$1.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((s,i)=>o.type._parseAsync(new ParseInputLazyPath(r,s,r.path,i)))).then(s=>ParseStatus.mergeArray(n,s));const a=[...r.data].map((s,i)=>o.type._parseSync(new ParseInputLazyPath(r,s,r.path,i)));return ParseStatus.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new It({...this._def,minLength:{value:t,message:errorUtil.toString(r)}})}max(t,r){return new It({...this._def,maxLength:{value:t,message:errorUtil.toString(r)}})}length(t,r){return new It({...this._def,exactLength:{value:t,message:errorUtil.toString(r)}})}nonempty(t){return this.min(1,t)}};ZodArray$1.create=(e,t)=>new ZodArray$1({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject$1){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional$1.create(deepPartialify(n))}return new ZodObject$1({...e._def,shape:()=>t})}else return e instanceof ZodArray$1?new ZodArray$1({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional$1?ZodOptional$1.create(deepPartialify(e.unwrap())):e instanceof ZodNullable$1?ZodNullable$1.create(deepPartialify(e.unwrap())):e instanceof ZodTuple?ZodTuple.create(e.items.map(t=>deepPartialify(t))):e}let ZodObject$1=class We extends ZodType$1{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=util.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ZodParsedType.object){const c=this._getOrReturnCtx(t);return addIssueToContext(c,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.object,received:c.parsedType}),INVALID}const{status:n,ctx:o}=this._processInputParams(t),{shape:a,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof ZodNever$1&&this._def.unknownKeys==="strip"))for(const c in o.data)s.includes(c)||i.push(c);const l=[];for(const c of s){const u=a[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof ZodNever$1){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(addIssueToContext(o,{code:ZodIssueCode$1.unrecognized_keys,keys:i}),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 i){const d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const d=await u.key,p=await u.value;c.push({key:d,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>ParseStatus.mergeObjectSync(n,c)):ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new We({...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:errorUtil.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new We({...this._def,unknownKeys:"strip"})}passthrough(){return new We({...this._def,unknownKeys:"passthrough"})}extend(t){return new We({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new We({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new We({...this._def,catchall:t})}pick(t){const r={};for(const n of util.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new We({...this._def,shape:()=>r})}omit(t){const r={};for(const n of util.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new We({...this._def,shape:()=>r})}deepPartial(){return deepPartialify(this)}partial(t){const r={};for(const n of util.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new We({...this._def,shape:()=>r})}required(t){const r={};for(const n of util.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof ZodOptional$1;)a=a._def.innerType;r[n]=a}return new We({...this._def,shape:()=>r})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject$1.create=(e,t)=>new ZodObject$1({shape:()=>e,unknownKeys:"strip",catchall:ZodNever$1.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject$1.strictCreate=(e,t)=>new ZodObject$1({shape:()=>e,unknownKeys:"strict",catchall:ZodNever$1.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject$1.lazycreate=(e,t)=>new ZodObject$1({shape:e,unknownKeys:"strip",catchall:ZodNever$1.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});let ZodUnion$1=class extends ZodType$1{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(a){for(const i of a)if(i.result.status==="valid")return i.result;for(const i of a)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const s=a.map(i=>new ZodError(i.ctx.common.issues));return addIssueToContext(r,{code:ZodIssueCode$1.invalid_union,unionErrors:s}),INVALID}if(r.common.async)return Promise.all(n.map(async a=>{const s={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(o);{let a;const s=[];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&&s.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const i=s.map(l=>new ZodError(l));return addIssueToContext(r,{code:ZodIssueCode$1.invalid_union,unionErrors:i}),INVALID}}get options(){return this._def.options}};ZodUnion$1.create=(e,t)=>new ZodUnion$1({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy$1?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral$1?[e.value]:e instanceof ZodEnum$1?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault$1?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull$1?[null]:e instanceof ZodOptional$1?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable$1?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly$1?getDiscriminator(e.unwrap()):e instanceof ZodCatch$1?getDiscriminator(e._def.innerType):[];let ZodDiscriminatedUnion$1=class zt extends ZodType$1{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const n=this.discriminator,o=r.data[n],a=this.optionsMap.get(o);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(addIssueToContext(r,{code:ZodIssueCode$1.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const a of r){const s=getDiscriminator(a.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of s){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,a)}}return new zt({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...processCreateParams(n)})}};function mergeValues$1(e,t){const r=getParsedType(e),n=getParsedType(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType.object&&n===ZodParsedType.object){const o=util.objectKeys(t),a=util.objectKeys(e).filter(i=>o.indexOf(i)!==-1),s={...e,...t};for(const i of a){const l=mergeValues$1(e[i],t[i]);if(!l.valid)return{valid:!1};s[i]=l.data}return{valid:!0,data:s}}else if(r===ZodParsedType.array&&n===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let a=0;a<e.length;a++){const s=e[a],i=t[a],l=mergeValues$1(s,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ZodParsedType.date&&n===ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let ZodIntersection$1=class extends ZodType$1{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(a,s)=>{if(isAborted(a)||isAborted(s))return INVALID;const i=mergeValues$1(a.value,s.value);return i.valid?((isDirty(a)||isDirty(s))&&r.dirty(),{status:r.value,value:i.data}):(addIssueToContext(n,{code:ZodIssueCode$1.invalid_intersection_types}),INVALID)};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,s])=>o(a,s)):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}))}};ZodIntersection$1.create=(e,t,r)=>new ZodIntersection$1({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType$1{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode$1.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode$1.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((s,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new ParseInputLazyPath(n,s,n.path,i)):null}).filter(s=>!!s);return n.common.async?Promise.all(a).then(s=>ParseStatus.mergeArray(r,s)):ParseStatus.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new ZodTuple({...this._def,rest:t})}}ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};let ZodRecord$1=class Ot extends ZodType$1{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!==ZodParsedType.object)return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID;const o=[],a=this._def.keyType,s=this._def.valueType;for(const i in n.data)o.push({key:a._parse(new ParseInputLazyPath(n,i,n.path,i)),value:s._parse(new ParseInputLazyPath(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ParseStatus.mergeObjectAsync(r,o):ParseStatus.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof ZodType$1?new Ot({keyType:t,valueType:r,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(n)}):new Ot({keyType:ZodString$1.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)})}};class ZodMap extends ZodType$1{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!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const o=this._def.keyType,a=this._def.valueType,s=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new ParseInputLazyPath(n,i,n.path,[c,"key"])),value:a._parse(new ParseInputLazyPath(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of s){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of s){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}ZodMap.create=(e,t,r)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType$1{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode$1.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&&(addIssueToContext(n,{code:ZodIssueCode$1.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const a=this._def.valueType;function s(l){const c=new Set;for(const u of l){if(u.status==="aborted")return INVALID;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>a._parse(new ParseInputLazyPath(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>s(l)):s(i)}min(t,r){return new ZodSet({...this._def,minSize:{value:t,message:errorUtil.toString(r)}})}max(t,r){return new ZodSet({...this._def,maxSize:{value:t,message:errorUtil.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});class ZodFunction extends ZodType$1{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.function)return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.function,received:r.parsedType}),INVALID;function n(i,l){return makeIssue({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,getErrorMap(),errorMap].filter(c=>!!c),issueData:{code:ZodIssueCode$1.invalid_arguments,argumentsError:l}})}function o(i,l){return makeIssue({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,getErrorMap(),errorMap].filter(c=>!!c),issueData:{code:ZodIssueCode$1.invalid_return_type,returnTypeError:l}})}const a={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof ZodPromise){const i=this;return OK(async function(...l){const c=new ZodError([]),u=await i._def.args.parseAsync(l,a).catch(f=>{throw c.addIssue(n(l,f)),c}),d=await Reflect.apply(s,this,u);return await i._def.returns._def.type.parseAsync(d,a).catch(f=>{throw c.addIssue(o(d,f)),c})})}else{const i=this;return OK(function(...l){const c=i._def.args.safeParse(l,a);if(!c.success)throw new ZodError([n(l,c.error)]);const u=Reflect.apply(s,this,c.data),d=i._def.returns.safeParse(u,a);if(!d.success)throw new ZodError([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new ZodFunction({...this._def,args:ZodTuple.create(t).rest(ZodUnknown$1.create())})}returns(t){return new ZodFunction({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new ZodFunction({args:t||ZodTuple.create([]).rest(ZodUnknown$1.create()),returns:r||ZodUnknown$1.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(n)})}}let ZodLazy$1=class extends ZodType$1{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})}};ZodLazy$1.create=(e,t)=>new ZodLazy$1({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});let ZodLiteral$1=class extends ZodType$1{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode$1.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:t.data}}get value(){return this._def.value}};ZodLiteral$1.create=(e,t)=>new ZodLiteral$1({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum$1({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}let ZodEnum$1=class Nt extends ZodType$1{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return addIssueToContext(r,{expected:util.joinValues(n),received:r.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID}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 addIssueToContext(r,{received:r.data,code:ZodIssueCode$1.invalid_enum_value,options:n}),INVALID}return OK(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 Nt.create(t,{...this._def,...r})}exclude(t,r=this._def){return Nt.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};ZodEnum$1.create=createZodEnum;class ZodNativeEnum extends ZodType$1{_parse(t){const r=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const o=util.objectValues(r);return addIssueToContext(n,{expected:util.joinValues(o),received:n.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=util.objectValues(r);return addIssueToContext(n,{received:n.data,code:ZodIssueCode$1.invalid_enum_value,options:o}),INVALID}return OK(t.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});class ZodPromise extends ZodType$1{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.promise&&r.common.async===!1)return addIssueToContext(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.promise,received:r.parsedType}),INVALID;const n=r.parsedType===ZodParsedType.promise?r.data:Promise.resolve(r.data);return OK(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});class ZodEffects extends ZodType$1{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.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:s=>{addIssueToContext(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){const s=o.transform(n.data,a);if(n.common.async)return Promise.resolve(s).then(async i=>{if(r.value==="aborted")return INVALID;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?INVALID:l.status==="dirty"||r.value==="dirty"?DIRTY(l.value):l});{if(r.value==="aborted")return INVALID;const i=this._def.schema._parseSync({data:s,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"||r.value==="dirty"?DIRTY(i.value):i}}if(o.type==="refinement"){const s=i=>{const l=o.refinement(i,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 i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:(i.status==="dirty"&&r.dirty(),s(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?INVALID:(i.status==="dirty"&&r.dirty(),s(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(s))return INVALID;const i=o.transform(s.value,a);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>isValid(s)?Promise.resolve(o.transform(s.value,a)).then(i=>({status:r.value,value:i})):INVALID);util.assertNever(o)}}ZodEffects.create=(e,t,r)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(e,t,r)=>new ZodEffects({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});let ZodOptional$1=class extends ZodType$1{_parse(t){return this._getType(t)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodOptional$1.create=(e,t)=>new ZodOptional$1({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});let ZodNullable$1=class extends ZodType$1{_parse(t){return this._getType(t)===ZodParsedType.null?OK(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodNullable$1.create=(e,t)=>new ZodNullable$1({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});let ZodDefault$1=class extends ZodType$1{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ZodDefault$1.create=(e,t)=>new ZodDefault$1({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...processCreateParams(t)});let ZodCatch$1=class extends ZodType$1{_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 isAsync(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ZodCatch$1.create=(e,t)=>new ZodCatch$1({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...processCreateParams(t)});class ZodNaN extends ZodType$1{_parse(t){if(this._getType(t)!==ZodParsedType.nan){const n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:t.data}}}ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType$1{_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 ZodPipeline extends ZodType$1{_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"?INVALID:a.status==="dirty"?(r.dirty(),DIRTY(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"?INVALID: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 ZodPipeline({in:t,out:r,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}let ZodReadonly$1=class extends ZodType$1{_parse(t){const r=this._def.innerType._parse(t),n=o=>(isValid(o)&&(o.value=Object.freeze(o.value)),o);return isAsync(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};ZodReadonly$1.create=(e,t)=>new ZodReadonly$1({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});function cleanParams(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function custom$1(e,t={},r){return e?ZodAny$1.create().superRefine((n,o)=>{const a=e(n);if(a instanceof Promise)return a.then(s=>{if(!s){const i=cleanParams(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!a){const s=cleanParams(t,n),i=s.fatal??r??!0;o.addIssue({code:"custom",...s,fatal:i})}}):ZodAny$1.create()}const late={object:ZodObject$1.lazycreate};var ZodFirstPartyTypeKind;(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"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom$1(r=>r instanceof e,t),stringType=ZodString$1.create,numberType=ZodNumber$1.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean$1.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull$1.create,anyType=ZodAny$1.create,unknownType=ZodUnknown$1.create,neverType=ZodNever$1.create,voidType=ZodVoid.create,arrayType=ZodArray$1.create,objectType=ZodObject$1.create,strictObjectType=ZodObject$1.strictCreate,unionType=ZodUnion$1.create,discriminatedUnionType=ZodDiscriminatedUnion$1.create,intersectionType=ZodIntersection$1.create,tupleType=ZodTuple.create,recordType=ZodRecord$1.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy$1.create,literalType=ZodLiteral$1.create,enumType=ZodEnum$1.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional$1.create,nullableType=ZodNullable$1.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:(e=>ZodString$1.create({...e,coerce:!0})),number:(e=>ZodNumber$1.create({...e,coerce:!0})),boolean:(e=>ZodBoolean$1.create({...e,coerce:!0})),bigint:(e=>ZodBigInt.create({...e,coerce:!0})),date:(e=>ZodDate.create({...e,coerce:!0}))},NEVER$1=INVALID,z=Object.freeze(Object.defineProperty({__proto__:null,BRAND,DIRTY,EMPTY_PATH,INVALID,NEVER:NEVER$1,OK,ParseStatus,Schema:ZodType$1,ZodAny:ZodAny$1,ZodArray:ZodArray$1,ZodBigInt,ZodBoolean:ZodBoolean$1,ZodBranded,ZodCatch:ZodCatch$1,ZodDate,ZodDefault:ZodDefault$1,ZodDiscriminatedUnion:ZodDiscriminatedUnion$1,ZodEffects,ZodEnum:ZodEnum$1,ZodError,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},ZodFunction,ZodIntersection:ZodIntersection$1,ZodIssueCode:ZodIssueCode$1,ZodLazy:ZodLazy$1,ZodLiteral:ZodLiteral$1,ZodMap,ZodNaN,ZodNativeEnum,ZodNever:ZodNever$1,ZodNull:ZodNull$1,ZodNullable:ZodNullable$1,ZodNumber:ZodNumber$1,ZodObject:ZodObject$1,ZodOptional:ZodOptional$1,ZodParsedType,ZodPipeline,ZodPromise,ZodReadonly:ZodReadonly$1,ZodRecord:ZodRecord$1,ZodSchema:ZodType$1,ZodSet,ZodString:ZodString$1,ZodSymbol,ZodTransformer:ZodEffects,ZodTuple,ZodType:ZodType$1,ZodUndefined,ZodUnion:ZodUnion$1,ZodUnknown:ZodUnknown$1,ZodVoid,addIssueToContext,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,coerce,custom:custom$1,date:dateType,datetimeRegex,defaultErrorMap:errorMap,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,getErrorMap,getParsedType,instanceof:instanceOfType,intersection:intersectionType,isAborted,isAsync,isDirty,isValid,late,lazy:lazyType,literal:literalType,makeIssue,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,get objectUtil(){return objectUtil},oboolean,onumber,optional:optionalType,ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,quotelessJson,record:recordType,set:setType,setErrorMap,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,get util(){return util},void:voidType},Symbol.toStringTag,{value:"Module"})),NEVER=Object.freeze({status:"aborted"});function $constructor(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in s.prototype)u in i||Object.defineProperty(i,u,{value:s.prototype[u].bind(i)});i._zod.constr=s,i._zod.def=l}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function s(i){var l;const c=r?.Parent?new a:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const globalConfig={};function config(e){return globalConfig}function getEnumValues(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 jsonStringifyReplacer(e,t){return typeof t=="bigint"?t.toString():t}function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish(e){return e==null}function cleanRegex(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function floatSafeRemainder(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(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return a%s/10**o}function defineLazy(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 assignProp(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function esc(e){return JSON.stringify(e)}const captureStackTrace=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function isPlainObject$2(e){if(isObject(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(isObject(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function normalizeParams(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 optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const NUMBER_FORMAT_RANGES={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 pick(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 clone(e,{...e._zod.def,shape:r,checks:[]})}function omit(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 clone(e,{...e._zod.def,shape:r,checks:[]})}function extend(e,t){if(!isPlainObject$2(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 assignProp(this,"shape",n),n},checks:[]};return clone(e,r)}function merge(e,t){return clone(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function partial(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 clone(t,{...t._zod.def,shape:o,checks:[]})}function required(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 clone(t,{...t._zod.def,shape:o,checks:[]})}function aborted(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function prefixIssues(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function unwrapMessage(e){return typeof e=="string"?e:e?.message}function finalizeIssue(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(r.customError?.(e))??unwrapMessage(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function getLengthableOrigin(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function issue(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const initializer$1=(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,jsonStringifyReplacer,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError$1(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 formatError(e,t){const r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(const s of a.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>o({issues:i}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let i=n,l=0;for(;l<s.path.length;){const c=s.path[l];l===s.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(s))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const _parse$2=e=>(t,r,n,o)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},a);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const i=new(o?.Err??e)(s.issues.map(l=>finalizeIssue(l,a,config())));throw captureStackTrace(i,o?.callee),i}return s.value},parse$1=_parse$2($ZodRealError),_parseAsync=e=>async(t,r,n,o)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){const i=new(o?.Err??e)(s.issues.map(l=>finalizeIssue(l,a,config())));throw captureStackTrace(i,o?.callee),i}return s.value},parseAsync$1=_parseAsync($ZodRealError),_safeParse=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 $ZodAsyncError;return a.issues.length?{success:!1,error:new(e??$ZodError)(a.issues.map(s=>finalizeIssue(s,o,config())))}:{success:!0,data:a.value}},safeParse$2=_safeParse($ZodRealError),_safeParseAsync=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(s=>finalizeIssue(s,o,config())))}:{success:!0,data:a.value}},safeParseAsync$2=_safeParseAsync($ZodRealError),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([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})$/,uuid=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)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}const 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])$/,ipv6=/^(([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})$/,cidrv4=/^((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])$/,cidrv6=/^(([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])$/,base64$1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,hostname=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,e164=/^\+(?:[0-9]){6,14}[0-9]$/,dateSource="(?:(?:\\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])))",date$2=new RegExp(`^${dateSource}$`);function timeSource(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 time$2(e){return new RegExp(`^${timeSource(e)}$`)}function datetime$1(e){const t=timeSource({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(`^${dateSource}T(?:${n})$`)}const string$1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},integer=/^\d+$/,number$2=/^-?\d+(?:\.\d+)?/i,boolean$1=/true|false/i,_null$2=/null/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(e,t)=>{$ZodCheck.init(e,t);const r=numericOriginMap[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})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(e,t)=>{$ZodCheck.init(e,t);const r=numericOriginMap[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})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(e,t)=>{$ZodCheck.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):floatSafeRemainder(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})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,a]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(s=>{const i=s._zod.bag;i.format=t.format,i.minimum=o,i.maximum=a,r&&(i.pattern=integer)}),e._zod.check=s=>{const i=s.value;if(r){if(!Number.isInteger(i)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?s.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:i,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}}i<o&&s.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>a&&s.issues.push({origin:"number",input:i,code:"too_big",maximum:a,inst:e})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nullish(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 s=getLengthableOrigin(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nullish(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 s=getLengthableOrigin(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nullish(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 s=getLengthableOrigin(o),i=a>t.length;n.issues.push({origin:s,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var r,n;$ZodCheck.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=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(e,t)=>{$ZodCheckStringFormat.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})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=lowercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uppercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(e,t)=>{$ZodCheck.init(e,t);const r=escapeRegex(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})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`^${escapeRegex(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})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`.*${escapeRegex(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})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Doc{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(`
|
|
9
|
-
`).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),a=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of a)this.content.push(s)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
10
|
-
`))}}const version$1={major:4,minor:0,patch:0},$ZodType=$constructor("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version$1;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,s,i)=>{let l=aborted(a),c;for(const u of s){if(u._zod.def.when){if(!u._zod.def.when(a))continue}else if(l)continue;const d=a.issues.length,p=u._zod.check(a);if(p instanceof Promise&&i?.async===!1)throw new $ZodAsyncError;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==d&&(l||(l=aborted(a,d)))});else{if(a.issues.length===d)continue;l||(l=aborted(a,d))}}return c?c.then(()=>a):a};e._zod.run=(a,s)=>{const i=e._zod.parse(a,s);if(i instanceof Promise){if(s.async===!1)throw new $ZodAsyncError;return i.then(l=>o(l,n,s))}return o(i,n,s)}}e["~standard"]={validate:o=>{try{const a=safeParse$2(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return safeParseAsync$2(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(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}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=guid),$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor("$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=uuid(n))}else t.pattern??(t.pattern=uuid());$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=email),$ZodStringFormat.init(e,t)}),$ZodURL=$constructor("$ZodURL",(e,t)=>{$ZodStringFormat.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:hostname.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})}}}),$ZodEmoji=$constructor("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=emoji()),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nanoid),$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cuid),$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cuid2),$ZodStringFormat.init(e,t)}),$ZodULID=$constructor("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ulid),$ZodStringFormat.init(e,t)}),$ZodXID=$constructor("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xid),$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ksuid),$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$2),$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=time$2(t)),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=duration$1),$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ipv4),$ZodStringFormat.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),$ZodIPv6=$constructor("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ipv6),$ZodStringFormat.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})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cidrv4),$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cidrv6),$ZodStringFormat.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 isValidBase64(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const $ZodBase64=$constructor("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=base64$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{isValidBase64(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return isValidBase64(r)}const $ZodBase64URL=$constructor("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=base64url),$ZodStringFormat.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{isValidBase64URL(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e164),$ZodStringFormat.init(e,t)});function isValidJWT(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 $ZodJWT=$constructor("$ZodJWT",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{isValidJWT(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$2,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}}),$ZodNumberFormat=$constructor("$ZodNumber",(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,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}}),$ZodNull=$constructor("$ZodNull",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,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}}),$ZodAny=$constructor("$ZodAny",(e,t)=>{$ZodType.init(e,t),e._zod.parse=r=>r}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=r=>r}),$ZodNever=$constructor("$ZodNever",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function handleArrayResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.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 s=0;s<o.length;s++){const i=o[s],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?a.push(l.then(c=>handleArrayResult(c,r,s))):handleArrayResult(l,r,s)}return a.length?Promise.all(a).then(()=>r):r}});function handleObjectResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}function handleOptionalObjectResult(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(...prefixIssues(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const $ZodObject=$constructor("$ZodObject",(e,t)=>{$ZodType.init(e,t);const r=cached(()=>{const d=Object.keys(t.shape);for(const f of d)if(!(t.shape[f]instanceof $ZodType))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=optionalKeys(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});defineLazy(e._zod,"propValues",()=>{const d=t.shape,p={};for(const f in d){const h=d[f]._zod;if(h.values){p[f]??(p[f]=new Set);for(const b of h.values)p[f].add(b)}}return p});const n=d=>{const p=new Doc(["shape","payload","ctx"]),f=r.value,h=g=>{const m=esc(g);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const b=Object.create(null);let y=0;for(const g of f.keys)b[g]=`key_${y++}`;p.write("const newResult = {}");for(const g of f.keys)if(f.optionalKeys.has(g)){const m=b[g];p.write(`const ${m} = ${h(g)};`);const S=esc(g);p.write(`
|
|
11
|
-
if (${m}.issues.length) {
|
|
12
|
-
if (input[${S}] === undefined) {
|
|
13
|
-
if (${S} in input) {
|
|
14
|
-
newResult[${S}] = undefined;
|
|
15
|
-
}
|
|
16
|
-
} else {
|
|
17
|
-
payload.issues = payload.issues.concat(
|
|
18
|
-
${m}.issues.map((iss) => ({
|
|
19
|
-
...iss,
|
|
20
|
-
path: iss.path ? [${S}, ...iss.path] : [${S}],
|
|
21
|
-
}))
|
|
22
|
-
);
|
|
23
|
-
}
|
|
24
|
-
} else if (${m}.value === undefined) {
|
|
25
|
-
if (${S} in input) newResult[${S}] = undefined;
|
|
26
|
-
} else {
|
|
27
|
-
newResult[${S}] = ${m}.value;
|
|
28
|
-
}
|
|
29
|
-
`)}else{const m=b[g];p.write(`const ${m} = ${h(g)};`),p.write(`
|
|
30
|
-
if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
|
|
31
|
-
...iss,
|
|
32
|
-
path: iss.path ? [${esc(g)}, ...iss.path] : [${esc(g)}]
|
|
33
|
-
})));`),p.write(`newResult[${esc(g)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(g,m)=>w(d,g,m)};let o;const a=isObject,s=!globalConfig.jitless,l=s&&allowsEval.value,c=t.catchall;let u;e._zod.parse=(d,p)=>{u??(u=r.value);const f=d.value;if(!a(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d;const h=[];if(s&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};const m=u.shape;for(const S of u.keys){const v=m[S],_=v._zod.run({value:f[S],issues:[]},p),$=v._zod.optin==="optional"&&v._zod.optout==="optional";_ instanceof Promise?h.push(_.then(T=>$?handleOptionalObjectResult(T,d,S,f):handleObjectResult(T,d,S))):$?handleOptionalObjectResult(_,d,S,f):handleObjectResult(_,d,S)}}if(!c)return h.length?Promise.all(h).then(()=>d):d;const b=[],y=u.keySet,w=c._zod,g=w.def.type;for(const m of Object.keys(f)){if(y.has(m))continue;if(g==="never"){b.push(m);continue}const S=w.run({value:f[m],issues:[]},p);S instanceof Promise?h.push(S.then(v=>handleObjectResult(v,d,m))):handleObjectResult(S,d,m)}return b.length&&d.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function handleUnionResults(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=>finalizeIssue(a,n,config())))}),t}const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),defineLazy(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=>cleanRegex(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const a=[];for(const s of t.options){const i=s._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)a.push(i),o=!0;else{if(i.issues.length===0)return i;a.push(i)}}return o?Promise.all(a).then(s=>handleUnionResults(s,r,e,n)):handleUnionResults(a,r,e,n)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(e,t)=>{$ZodUnion.init(e,t);const r=e._zod.parse;defineLazy(e._zod,"propValues",()=>{const o={};for(const a of t.options){const s=a._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const[i,l]of Object.entries(s)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=cached(()=>{const o=t.options,a=new Map;for(const s of o){const i=s._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const l of i){if(a.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);a.set(l,s)}}return a});e._zod.parse=(o,a)=>{const s=o.value;if(!isObject(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const i=n.value.get(s?.[t.discriminator]);return i?i._zod.run(o,a):t.unionFallback?r(o,a):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),$ZodIntersection=$constructor("$ZodIntersection",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return a instanceof Promise||s instanceof Promise?Promise.all([a,s]).then(([l,c])=>handleIntersectionResults(r,l,c)):handleIntersectionResults(r,a,s)}});function mergeValues(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(isPlainObject$2(e)&&isPlainObject$2(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 s=mergeValues(e[a],t[a]);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};o[a]=s.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],s=mergeValues(o,a);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),aborted(e))return e;const n=mergeValues(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 $ZodRecord=$constructor("$ZodRecord",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!isPlainObject$2(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const a=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;r.value={};for(const l of s)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(...prefixIssues(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...prefixIssues(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)s.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const s of Reflect.ownKeys(o)){if(s==="__proto__")continue;const i=t.keyType._zod.run({value:s,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>finalizeIssue(c,n,config())),input:s,path:[s],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[s],issues:[]},n);l instanceof Promise?a.push(l.then(c=>{c.issues.length&&r.issues.push(...prefixIssues(s,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...prefixIssues(s,l.issues)),r.value[i.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),$ZodEnum=$constructor("$ZodEnum",(e,t)=>{$ZodType.init(e,t);const r=getEnumValues(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>propertyKeyTypes.has(typeof n)).map(n=>typeof n=="string"?escapeRegex(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}}),$ZodLiteral=$constructor("$ZodLiteral",(e,t)=>{$ZodType.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?escapeRegex(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}}),$ZodTransform=$constructor("$ZodTransform",(e,t)=>{$ZodType.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(s=>(r.value=s,r));if(o instanceof Promise)throw new $ZodAsyncError;return r.value=o,r}}),$ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${cleanRegex(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)}),$ZodNullable=$constructor("$ZodNullable",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${cleanRegex(r.source)}|null)$`):void 0}),defineLazy(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)}),$ZodDefault=$constructor("$ZodDefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(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=>handleDefaultResult(a,t)):handleDefaultResult(o,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const $ZodPrefault=$constructor("$ZodPrefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(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))}),$ZodNonOptional=$constructor("$ZodNonOptional",(e,t)=>{$ZodType.init(e,t),defineLazy(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=>handleNonOptionalResult(a,e)):handleNonOptionalResult(o,e)}});function handleNonOptionalResult(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 $ZodCatch=$constructor("$ZodCatch",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(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(s=>finalizeIssue(s,n,config()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>finalizeIssue(a,n,config()))},input:r.value}),r.issues=[]),r)}}),$ZodPipe=$constructor("$ZodPipe",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>t.in._zod.values),defineLazy(e._zod,"optin",()=>t.in._zod.optin),defineLazy(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=>handlePipeResult(a,t,n)):handlePipeResult(o,t,n)}});function handlePipeResult(e,t,r){return aborted(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const $ZodReadonly=$constructor("$ZodReadonly",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"propValues",()=>t.innerType._zod.propValues),defineLazy(e._zod,"values",()=>t.innerType._zod.values),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(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(handleReadonlyResult):handleReadonlyResult(o)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}const $ZodLazy=$constructor("$ZodLazy",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"innerType",()=>t.getter()),defineLazy(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),defineLazy(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),defineLazy(e._zod,"optin",()=>e._zod.innerType._zod.optin),defineLazy(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),$ZodCustom=$constructor("$ZodCustom",(e,t)=>{$ZodCheck.init(e,t),$ZodType.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=>handleRefineResult(a,r,n,e));handleRefineResult(o,r,n,e)}});function handleRefineResult(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(issue(o))}}class $ZodRegistry{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 registry(){return new $ZodRegistry}const globalRegistry=registry();function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _email(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(t)})}function _url$1(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _isoTime(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:"string",format:"duration",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _coercedNumber(e,t){return new e({type:"number",coerce:!0,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _null$1(e,t){return new e({type:"null",...normalizeParams(t)})}function _any(e){return new e({type:"any"})}function _unknown(e){return new e({type:"unknown"})}function _never(e,t){return new e({type:"never",...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!0})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(t),value:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:"overwrite",tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _array(e,t,r){return new e({type:"array",element:t,...normalizeParams(r)})}function _custom(e,t,r){const n=normalizeParams(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function _refine(e,t,r){return new e({type:"custom",check:"custom",fn:t,...normalizeParams(r)})}class JSONSchemaGenerator{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??globalRegistry,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:""},s=this.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const d={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{const f=i.schema;switch(o.type){case"string":{const h=f;h.type="string";const{minimum:b,maximum:y,format:w,patterns:g,contentEncoding:m}=t._zod.bag;if(typeof b=="number"&&(h.minLength=b),typeof y=="number"&&(h.maxLength=y),w&&(h.format=a[w]??w,h.format===""&&delete h.format),m&&(h.contentEncoding=m),g&&g.size>0){const S=[...g];S.length===1?h.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{const h=f,{minimum:b,maximum:y,format:w,multipleOf:g,exclusiveMaximum:m,exclusiveMinimum:S}=t._zod.bag;typeof w=="string"&&w.includes("int")?h.type="integer":h.type="number",typeof S=="number"&&(h.exclusiveMinimum=S),typeof b=="number"&&(h.minimum=b,typeof S=="number"&&(S>=b?delete h.minimum:delete h.exclusiveMinimum)),typeof m=="number"&&(h.exclusiveMaximum=m),typeof y=="number"&&(h.maximum=y,typeof m=="number"&&(m<=y?delete h.maximum:delete h.exclusiveMaximum)),typeof g=="number"&&(h.multipleOf=g);break}case"boolean":{const h=f;h.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const h=f,{minimum:b,maximum:y}=t._zod.bag;typeof b=="number"&&(h.minItems=b),typeof y=="number"&&(h.maxItems=y),h.type="array",h.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{const h=f;h.type="object",h.properties={};const b=o.shape;for(const g in b)h.properties[g]=this.process(b[g],{...d,path:[...d.path,"properties",g]});const y=new Set(Object.keys(b)),w=new Set([...y].filter(g=>{const m=o.shape[g]._zod;return this.io==="input"?m.optin===void 0:m.optout===void 0}));w.size>0&&(h.required=Array.from(w)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{const h=f;h.anyOf=o.options.map((b,y)=>this.process(b,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{const h=f,b=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),y=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),w=m=>"allOf"in m&&Object.keys(m).length===1,g=[...w(b)?b.allOf:[b],...w(y)?y.allOf:[y]];h.allOf=g;break}case"tuple":{const h=f;h.type="array";const b=o.items.map((g,m)=>this.process(g,{...d,path:[...d.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?h.prefixItems=b:h.items=b,o.rest){const g=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?h.items=g:h.additionalItems=g}o.rest&&(h.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(h.minItems=y),typeof w=="number"&&(h.maxItems=w);break}case"record":{const h=f;h.type="object",h.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...d,path:[...d.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 h=f,b=getEnumValues(o.entries);b.every(y=>typeof y=="number")&&(h.type="number"),b.every(y=>typeof y=="string")&&(h.type="string"),h.enum=b;break}case"literal":{const h=f,b=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(y))}else b.push(y);if(b.length!==0)if(b.length===1){const y=b[0];h.type=y===null?"null":typeof y,h.const=y}else b.every(y=>typeof y=="number")&&(h.type="number"),b.every(y=>typeof y=="string")&&(h.type="string"),b.every(y=>typeof y=="boolean")&&(h.type="string"),b.every(y=>y===null)&&(h.type="null"),h.enum=b;break}case"file":{const h=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:g}=t._zod.bag;y!==void 0&&(b.minLength=y),w!==void 0&&(b.maxLength=w),g?g.length===1?(b.contentMediaType=g[0],Object.assign(h,b)):h.anyOf=g.map(m=>({...b,contentMediaType:m})):Object.assign(h,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const h=this.process(o.innerType,d);f.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),i.ref=o.innerType;break}case"success":{const h=f;h.type="boolean";break}case"default":{this.process(o.innerType,d),i.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),i.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),i.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const h=f,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=b.source;break}case"pipe":{const h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,d),i.ref=h;break}case"readonly":{this.process(o.innerType,d),i.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,d),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),i.ref=o.innerType;break}case"lazy":{const h=t._zod.innerType;this.process(h,d),i.ref=h;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(i.schema,c),this.io==="input"&&isTransforming(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.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 d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const b=n.external.registry.get(u[0])?.id,y=n.external.uri??(g=>g);if(b)return{ref:y(b)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${y("__shared")}#/${d}/${w}`}}if(u[1]===o)return{ref:"#"};const f=`#/${d}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:f+h}},s=u=>{if(u[1].schema.$ref)return;const d=u[1],{ref:p,defId:f}=a(u);d.def={...d.schema},f&&(d.defId=f);const h=d.schema;for(const b in h)delete h[b];h.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
34
|
-
|
|
35
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const d=u[1];if(t===u[0]){s(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(d.cycle){s(u);continue}if(d.count>1&&n.reused==="ref"){s(u);continue}}const i=(u,d)=>{const p=this.seen.get(u),f=p.def??p.schema,h={...f};if(p.ref===null)return;const b=p.ref;if(p.ref=null,b){i(b,d);const y=this.seen.get(b).schema;y.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,h))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(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 d=u[1];d.def&&d.defId&&(c[d.defId]=d.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 toJSONSchema(e,t){if(e instanceof $ZodRegistry){const n=new JSONSchemaGenerator(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const a={},s={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;a[l]=n.emit(c,{...t,external:s})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[i]:o}}return{schemas:a}}const r=new JSONSchemaGenerator(t);return r.process(e),r.emit(e,t)}function isTransforming(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 isTransforming(o.element,r);case"object":{for(const a in o.shape)if(isTransforming(o.shape[a],r))return!0;return!1}case"union":{for(const a of o.options)if(isTransforming(a,r))return!0;return!1}case"intersection":return isTransforming(o.left,r)||isTransforming(o.right,r);case"tuple":{for(const a of o.items)if(isTransforming(a,r))return!0;return!!(o.rest&&isTransforming(o.rest,r))}case"record":return isTransforming(o.keyType,r)||isTransforming(o.valueType,r);case"map":return isTransforming(o.keyType,r)||isTransforming(o.valueType,r);case"set":return isTransforming(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return isTransforming(o.innerType,r);case"lazy":return isTransforming(o.getter(),r);case"default":return isTransforming(o.innerType,r);case"prefault":return isTransforming(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return isTransforming(o.in,r)||isTransforming(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const ZodISODateTime=$constructor("ZodISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor("ZodISODate",(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date$1(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor("ZodISOTime",(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time$1(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor("ZodISODuration",(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>formatError(e,r)},flatten:{value:r=>flattenError$1(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse=_parse$2(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse$1=_safeParse(ZodRealError),safeParseAsync$1=_safeParseAsync(ZodRealError),ZodType=$constructor("ZodType",(e,t)=>($ZodType.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)=>clone(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>parse(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>safeParse$1(e,r,n),e.parseAsync=async(r,n)=>parseAsync(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>safeParseAsync$1(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(refine(r,n)),e.superRefine=r=>e.check(superRefine(r)),e.overwrite=r=>e.check(_overwrite(r)),e.optional=()=>optional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=r=>nonoptional(e,r),e.array=()=>array$1(e),e.or=r=>union([e,r]),e.and=r=>intersection(e,r),e.transform=r=>pipe(e,transform(r)),e.default=r=>_default(e,r),e.prefault=r=>prefault(e,r),e.catch=r=>_catch(e,r),e.pipe=r=>pipe(e,r),e.readonly=()=>readonly(e),e.describe=r=>{const n=e.clone();return globalRegistry.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return globalRegistry.get(e);const n=e.clone();return globalRegistry.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_ZodString=$constructor("_ZodString",(e,t)=>{$ZodString.init(e,t),ZodType.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(_regex(...n)),e.includes=(...n)=>e.check(_includes(...n)),e.startsWith=(...n)=>e.check(_startsWith(...n)),e.endsWith=(...n)=>e.check(_endsWith(...n)),e.min=(...n)=>e.check(_minLength(...n)),e.max=(...n)=>e.check(_maxLength(...n)),e.length=(...n)=>e.check(_length(...n)),e.nonempty=(...n)=>e.check(_minLength(1,...n)),e.lowercase=n=>e.check(_lowercase(n)),e.uppercase=n=>e.check(_uppercase(n)),e.trim=()=>e.check(_trim()),e.normalize=(...n)=>e.check(_normalize(...n)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase())}),ZodString=$constructor("ZodString",(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=r=>e.check(_email(ZodEmail,r)),e.url=r=>e.check(_url$1(ZodURL,r)),e.jwt=r=>e.check(_jwt(ZodJWT,r)),e.emoji=r=>e.check(_emoji(ZodEmoji,r)),e.guid=r=>e.check(_guid(ZodGUID,r)),e.uuid=r=>e.check(_uuid(ZodUUID,r)),e.uuidv4=r=>e.check(_uuidv4(ZodUUID,r)),e.uuidv6=r=>e.check(_uuidv6(ZodUUID,r)),e.uuidv7=r=>e.check(_uuidv7(ZodUUID,r)),e.nanoid=r=>e.check(_nanoid(ZodNanoID,r)),e.guid=r=>e.check(_guid(ZodGUID,r)),e.cuid=r=>e.check(_cuid(ZodCUID,r)),e.cuid2=r=>e.check(_cuid2(ZodCUID2,r)),e.ulid=r=>e.check(_ulid(ZodULID,r)),e.base64=r=>e.check(_base64(ZodBase64,r)),e.base64url=r=>e.check(_base64url(ZodBase64URL,r)),e.xid=r=>e.check(_xid(ZodXID,r)),e.ksuid=r=>e.check(_ksuid(ZodKSUID,r)),e.ipv4=r=>e.check(_ipv4(ZodIPv4,r)),e.ipv6=r=>e.check(_ipv6(ZodIPv6,r)),e.cidrv4=r=>e.check(_cidrv4(ZodCIDRv4,r)),e.cidrv6=r=>e.check(_cidrv6(ZodCIDRv6,r)),e.e164=r=>e.check(_e164(ZodE164,r)),e.datetime=r=>e.check(datetime(r)),e.date=r=>e.check(date$1(r)),e.time=r=>e.check(time$1(r)),e.duration=r=>e.check(duration(r))});function string(e){return _string(ZodString,e)}const ZodStringFormat=$constructor("ZodStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor("ZodEmail",(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor("ZodGUID",(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor("ZodUUID",(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor("ZodURL",(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url$1(ZodURL,e)}const ZodEmoji=$constructor("ZodEmoji",(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor("ZodNanoID",(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor("ZodCUID",(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor("ZodCUID2",(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor("ZodULID",(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor("ZodXID",(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor("ZodKSUID",(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor("ZodIPv4",(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor("ZodIPv6",(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor("ZodCIDRv4",(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor("ZodCIDRv6",(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor("ZodBase64",(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)});function base64(e){return _base64(ZodBase64,e)}const ZodBase64URL=$constructor("ZodBase64URL",(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor("ZodE164",(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor("ZodJWT",(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber=$constructor("ZodNumber",(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e.gt=(n,o)=>e.check(_gt(n,o)),e.gte=(n,o)=>e.check(_gte(n,o)),e.min=(n,o)=>e.check(_gte(n,o)),e.lt=(n,o)=>e.check(_lt(n,o)),e.lte=(n,o)=>e.check(_lte(n,o)),e.max=(n,o)=>e.check(_lte(n,o)),e.int=n=>e.check(int(n)),e.safe=n=>e.check(int(n)),e.positive=n=>e.check(_gt(0,n)),e.nonnegative=n=>e.check(_gte(0,n)),e.negative=n=>e.check(_lt(0,n)),e.nonpositive=n=>e.check(_lte(0,n)),e.multipleOf=(n,o)=>e.check(_multipleOf(n,o)),e.step=(n,o)=>e.check(_multipleOf(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 number$1(e){return _number(ZodNumber,e)}const ZodNumberFormat=$constructor("ZodNumberFormat",(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean=$constructor("ZodBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t)});function boolean(e){return _boolean(ZodBoolean,e)}const ZodNull=$constructor("ZodNull",(e,t)=>{$ZodNull.init(e,t),ZodType.init(e,t)});function _null(e){return _null$1(ZodNull,e)}const ZodAny=$constructor("ZodAny",(e,t)=>{$ZodAny.init(e,t),ZodType.init(e,t)});function any(){return _any(ZodAny)}const ZodUnknown=$constructor("ZodUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t)});function unknown(){return _unknown(ZodUnknown)}const ZodNever=$constructor("ZodNever",(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t)});function never(e){return _never(ZodNever,e)}const ZodArray=$constructor("ZodArray",(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(_minLength(r,n)),e.nonempty=r=>e.check(_minLength(1,r)),e.max=(r,n)=>e.check(_maxLength(r,n)),e.length=(r,n)=>e.check(_length(r,n)),e.unwrap=()=>e.element});function array$1(e,t){return _array(ZodArray,e,t)}const ZodObject=$constructor("ZodObject",(e,t)=>{$ZodObject.init(e,t),ZodType.init(e,t),defineLazy(e,"shape",()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>extend(e,r),e.merge=r=>merge(e,r),e.pick=r=>pick(e,r),e.omit=r=>omit(e,r),e.partial=(...r)=>partial(ZodOptional,e,r[0]),e.required=(...r)=>required(ZodNonOptional,e,r[0])});function object$2(e,t){const r={type:"object",get shape(){return assignProp(this,"shape",{...e}),this.shape},...normalizeParams(t)};return new ZodObject(r)}function looseObject(e,t){return new ZodObject({type:"object",get shape(){return assignProp(this,"shape",{...e}),this.shape},catchall:unknown(),...normalizeParams(t)})}const ZodUnion=$constructor("ZodUnion",(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e.options=t.options});function union(e,t){return new ZodUnion({type:"union",options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(e,t)=>{ZodUnion.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,r){return new ZodDiscriminatedUnion({type:"union",options:t,discriminator:e,...normalizeParams(r)})}const ZodIntersection=$constructor("ZodIntersection",(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t)});function intersection(e,t){return new ZodIntersection({type:"intersection",left:e,right:t})}const ZodRecord=$constructor("ZodRecord",(e,t)=>{$ZodRecord.init(e,t),ZodType.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,r){return new ZodRecord({type:"record",keyType:e,valueType:t,...normalizeParams(r)})}const ZodEnum=$constructor("ZodEnum",(e,t)=>{$ZodEnum.init(e,t),ZodType.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 s of n)if(r.has(s))a[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(o),entries:a})},e.exclude=(n,o)=>{const a={...t.entries};for(const s of n)if(r.has(s))delete a[s];else throw new Error(`Key ${s} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(o),entries:a})}});function _enum(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ZodEnum({type:"enum",entries:r,...normalizeParams(t)})}const ZodLiteral=$constructor("ZodLiteral",(e,t)=>{$ZodLiteral.init(e,t),ZodType.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 literal(e,t){return new ZodLiteral({type:"literal",values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor("ZodTransform",(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(issue(a,r.value,t));else{const s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(issue(s))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function transform(e){return new ZodTransform({type:"transform",transform:e})}const ZodOptional=$constructor("ZodOptional",(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:"optional",innerType:e})}const ZodNullable=$constructor("ZodNullable",(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}const ZodDefault=$constructor("ZodDefault",(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ZodPrefault=$constructor("ZodPrefault",(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ZodNonOptional=$constructor("ZodNonOptional",(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}const ZodCatch=$constructor("ZodCatch",(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const ZodPipe=$constructor("ZodPipe",(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}const ZodReadonly=$constructor("ZodReadonly",(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t)});function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}const ZodLazy=$constructor("ZodLazy",(e,t)=>{$ZodLazy.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.getter()});function lazy(e){return new ZodLazy({type:"lazy",getter:e})}const ZodCustom=$constructor("ZodCustom",(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t)});function check(e){const t=new $ZodCheck({check:"custom"});return t._zod.check=e,t}function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){const t=check(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(issue(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(issue(o))}},e(r.value,r)));return t}function _instanceof(e,t={error:`Input not instance of ${e.name}`}){const r=new ZodCustom({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...normalizeParams(t)});return r._zod.bag.Class=e,r}function preprocess(e,t){return pipe(transform(e),t)}const ZodIssueCode={custom:"custom"};function number(e){return _coercedNumber(ZodNumber,e)}const LATEST_PROTOCOL_VERSION$1="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS$1=[LATEST_PROTOCOL_VERSION$1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION$1="2.0",AssertObjectSchema=custom(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ProgressTokenSchema=union([string(),number$1().int()]),CursorSchema=string();looseObject({ttl:union([number$1(),_null()]).optional(),pollInterval:number$1().optional()});const TaskMetadataSchema=object$2({ttl:number$1().optional()}),RelatedTaskMetadataSchema=object$2({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$2({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema$1=object$2({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$2({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$2({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema$1=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number$1().int()]),JSONRPCRequestSchema$1=object$2({jsonrpc:literal(JSONRPC_VERSION$1),id:RequestIdSchema,...RequestSchema$1.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema$1.safeParse(e).success,JSONRPCNotificationSchema$1=object$2({jsonrpc:literal(JSONRPC_VERSION$1),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema$1.safeParse(e).success,JSONRPCResultResponseSchema=object$2({jsonrpc:literal(JSONRPC_VERSION$1),id:RequestIdSchema,result:ResultSchema$1}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(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"})(ErrorCode||(ErrorCode={}));const JSONRPCErrorResponseSchema=object$2({jsonrpc:literal(JSONRPC_VERSION$1),id:RequestIdSchema.optional(),error:object$2({code:number$1().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema$1=union([JSONRPCRequestSchema$1,JSONRPCNotificationSchema$1,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]);union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]);const EmptyResultSchema=ResultSchema$1.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object$2({src:string(),mimeType:string().optional(),sizes:array$1(string()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object$2({icons:array$1(IconSchema).optional()}),BaseMetadataSchema=object$2({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$2({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema$1=preprocess(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$2({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$2({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$2({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema$1.optional(),roots:object$2({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema$1.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),ServerCapabilitiesSchema$1=object$2({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$2({listChanged:boolean().optional()}).optional(),resources:object$2({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$2({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema$1=ResultSchema$1.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema$1,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema$1.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$2({progress:number$1(),total:optional(number$1()),message:optional(string())}),ProgressNotificationParamsSchema=object$2({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema$1.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema$1=ResultSchema$1.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object$2({taskId:string(),status:TaskStatusSchema,ttl:union([number$1(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number$1()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema$1.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema$1.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema$1.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema$1.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string()})});ResultSchema$1.loose();const ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema$1.extend({tasks:array$1(TaskSchema)}),CancelTaskRequestSchema=RequestSchema$1.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema$1.merge(TaskSchema),ResourceContentsSchema$1=object$2({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object$2({audience:array$1(RoleSchema).optional(),priority:number$1().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema$1=object$2({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object$2({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema$1=PaginatedResultSchema$1.extend({resources:array$1(ResourceSchema$1)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema$1=PaginatedResultSchema$1.extend({resourceTemplates:array$1(ResourceTemplateSchema$1)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema$1.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema$1=ResultSchema$1.extend({contents:array$1(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema$1.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema$1.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema$1=object$2({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema$1=object$2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array$1(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema$1=PaginatedResultSchema$1.extend({prompts:array$1(PromptSchema$1)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema$1.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema$1=object$2({type:literal("text"),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema$1=object$2({type:literal("image"),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$2({type:literal("audio"),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$2({type:literal("tool_use"),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema$1=object$2({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object$2({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema$1=ResultSchema$1.extend({description:string().optional(),messages:array$1(PromptMessageSchema$1)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$2({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$2({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema$1=object$2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$2({type:literal("object"),properties:record(string(),AssertObjectSchema).optional(),required:array$1(string()).optional()}).catchall(unknown()),outputSchema:object$2({type:literal("object"),properties:record(string(),AssertObjectSchema).optional(),required:array$1(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema$1=PaginatedResultSchema$1.extend({tools:array$1(ToolSchema$1)}),CallToolResultSchema$1=ResultSchema$1.extend({content:array$1(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()});CallToolResultSchema$1.or(ResultSchema$1.extend({toolResult:unknown()}));const CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema$1.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$2({autoRefresh:boolean().default(!0),debounceMs:number$1().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema$1.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$2({name:string().optional()}),ModelPreferencesSchema=object$2({hints:array$1(ModelHintSchema).optional(),costPriority:number$1().min(0).max(1).optional(),speedPriority:number$1().min(0).max(1).optional(),intelligencePriority:number$1().min(0).max(1).optional()}),ToolChoiceSchema=object$2({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object$2({type:literal("tool_result"),toolUseId:string().describe("The unique identifier for the corresponding tool call."),content:array$1(ContentBlockSchema).default([]),structuredContent:object$2({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$2({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array$1(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array$1(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number$1().optional(),maxTokens:number$1().int(),stopSequences:array$1(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array$1(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema$1.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema$1.extend({model:string(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema$1.extend({model:string(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array$1(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$2({type:literal("boolean"),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$2({type:literal("string"),title:string().optional(),description:string().optional(),minLength:number$1().optional(),maxLength:number$1().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string().optional()}),NumberSchemaSchema=object$2({type:_enum(["number","integer"]),title:string().optional(),description:string().optional(),minimum:number$1().optional(),maximum:number$1().optional(),default:number$1().optional()}),UntitledSingleSelectEnumSchemaSchema=object$2({type:literal("string"),title:string().optional(),description:string().optional(),enum:array$1(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$2({type:literal("string"),title:string().optional(),description:string().optional(),oneOf:array$1(object$2({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$2({type:literal("string"),title:string().optional(),description:string().optional(),enum:array$1(string()),enumNames:array$1(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$2({type:literal("array"),title:string().optional(),description:string().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$2({type:literal("string"),enum:array$1(string())}),default:array$1(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$2({type:literal("array"),title:string().optional(),description:string().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$2({anyOf:array$1(object$2({const:string(),title:string()}))}),default:array$1(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string(),requestedSchema:object$2({type:literal("object"),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array$1(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema$1.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema$1=ResultSchema$1.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number$1(),boolean(),array$1(string())])).optional())}),ResourceTemplateReferenceSchema=object$2({type:literal("ref/resource"),uri:string()}),PromptReferenceSchema$1=object$2({type:literal("ref/prompt"),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema]),argument:object$2({name:string(),value:string()}),context:object$2({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema$1.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema$1=ResultSchema$1.extend({completion:looseObject({values:array$1(string()).max(100),total:optional(number$1().int()),hasMore:optional(boolean())})}),RootSchema=object$2({uri:string().startsWith("file://"),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema$1.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema$1.extend({roots:array$1(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()});union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema$1,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),union([EmptyResultSchema,InitializeResultSchema$1,CompleteResultSchema$1,GetPromptResultSchema$1,ListPromptsResultSchema$1,ListResourcesResultSchema$1,ListResourceTemplatesResultSchema$1,ReadResourceResultSchema$1,CallToolResultSchema$1,ListToolsResultSchema$1,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);class McpError 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===ErrorCode.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new UrlElicitationRequiredError(o.elicitations,r)}return new McpError(t,r,n)}}class UrlElicitationRequiredError extends McpError{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const ZodMiniType=$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");$ZodType.init(e,t),e.def=t,e.parse=(r,n)=>parse$1(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>safeParse$2(e,r,n),e.parseAsync=async(r,n)=>parseAsync$1(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>safeParseAsync$2(e,r,n),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)=>clone(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),ZodMiniObject=$constructor("ZodMiniObject",(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,"shape",()=>t.shape)});function object$1(e,t){const r={type:"object",get shape(){return assignProp(this,"shape",{...e}),this.shape},...normalizeParams(t)};return new ZodMiniObject(r)}function isZ4Schema(e){return!!e._zod}function objectFromShape(e){const t=Object.values(e);if(t.length===0)return object$1({});const r=t.every(isZ4Schema),n=t.every(o=>!isZ4Schema(o));if(r)return object$1(e);if(n)return objectType(e);throw new Error("Mixed Zod versions detected in object shape.")}function safeParse(e,t){return isZ4Schema(e)?safeParse$2(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$2(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(isZ4Schema(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e=="object"){const t=e,r=e;if(!t._def&&!r._zod){const n=Object.values(e);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return objectFromShape(e)}}if(isZ4Schema(e)){const r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function getLiteralValue(e){if(isZ4Schema(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 isTerminal(e){return e==="completed"||e==="failed"||e==="cancelled"}const ignoreOverride$1=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions$1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions$1=e=>typeof e=="string"?{...defaultOptions$1,name:e}:{...defaultOptions$1,...e},getRefs$1=e=>{const t=getDefaultOptions$1(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},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}]))}};function addErrorMessage(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function setResponseValueAndErrors(e,t,r,n,o){e[t]=r,addErrorMessage(e,t,n,o)}const getRelativePath$1=(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 parseAnyDef$1(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?getRelativePath$1(t,e.currentPath):t.join("/")}}function parseArrayDef$1(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef$1(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&setResponseValueAndErrors(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(r,"minItems",e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function parseBigintDef$1(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t);break}return r}function parseBooleanDef$1(){return{type:"boolean"}}function parseBrandedDef$1(e,t){return parseDef$1(e.type._def,t)}const parseCatchDef$1=(e,t)=>parseDef$1(e.innerType._def,t);function parseDateDef$1(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>parseDateDef$1(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 integerDateParser$1(e,t)}}const integerDateParser$1=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,t);break}return r};function parseDefaultDef$1(e,t){return{...parseDef$1(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef$1(e,t){return t.effectStrategy==="input"?parseDef$1(e.schema._def,t):parseAnyDef$1(t)}function parseEnumDef$1(e){return{type:"string",enum:Array.from(e.values)}}const isJsonSchema7AllOfType$1=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function parseIntersectionDef$1(e,t){const r=[parseDef$1(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),parseDef$1(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(a=>{if(isJsonSchema7AllOfType$1(a))o.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let s=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:i,...l}=a;s=l}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function parseLiteralDef$1(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let emojiRegex$1;const zodPatterns$1={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:()=>(emojiRegex$1===void 0&&(emojiRegex$1=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex$1),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 parseStringDef$1(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":addFormat$1(r,"email",n.message,t);break;case"format:idn-email":addFormat$1(r,"idn-email",n.message,t);break;case"pattern:zod":addPattern$1(r,zodPatterns$1.email,n.message,t);break}break;case"url":addFormat$1(r,"uri",n.message,t);break;case"uuid":addFormat$1(r,"uuid",n.message,t);break;case"regex":addPattern$1(r,n.regex,n.message,t);break;case"cuid":addPattern$1(r,zodPatterns$1.cuid,n.message,t);break;case"cuid2":addPattern$1(r,zodPatterns$1.cuid2,n.message,t);break;case"startsWith":addPattern$1(r,RegExp(`^${escapeLiteralCheckValue$1(n.value,t)}`),n.message,t);break;case"endsWith":addPattern$1(r,RegExp(`${escapeLiteralCheckValue$1(n.value,t)}$`),n.message,t);break;case"datetime":addFormat$1(r,"date-time",n.message,t);break;case"date":addFormat$1(r,"date",n.message,t);break;case"time":addFormat$1(r,"time",n.message,t);break;case"duration":addFormat$1(r,"duration",n.message,t);break;case"length":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{addPattern$1(r,RegExp(escapeLiteralCheckValue$1(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&addFormat$1(r,"ipv4",n.message,t),n.version!=="v4"&&addFormat$1(r,"ipv6",n.message,t);break}case"base64url":addPattern$1(r,zodPatterns$1.base64url,n.message,t);break;case"jwt":addPattern$1(r,zodPatterns$1.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&addPattern$1(r,zodPatterns$1.ipv4Cidr,n.message,t),n.version!=="v4"&&addPattern$1(r,zodPatterns$1.ipv6Cidr,n.message,t);break}case"emoji":addPattern$1(r,zodPatterns$1.emoji(),n.message,t);break;case"ulid":{addPattern$1(r,zodPatterns$1.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{addFormat$1(r,"binary",n.message,t);break}case"contentEncoding:base64":{setResponseValueAndErrors(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{addPattern$1(r,zodPatterns$1.base64,n.message,t);break}}break}case"nanoid":addPattern$1(r,zodPatterns$1.nanoid,n.message,t)}return r}function escapeLiteralCheckValue$1(e,t){return t.patternStrategy==="escape"?escapeNonAlphaNumeric$1(e):e}const ALPHA_NUMERIC$1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric$1(e){let t="";for(let r=0;r<e.length;r++)ALPHA_NUMERIC$1.has(e[r])||(t+="\\"),t+=e[r];return t}function addFormat$1(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(e,"format",t,r,n)}function addPattern$1(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags$1(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(e,"pattern",stringifyRegExpWithFlags$1(t,n),r,n)}function stringifyRegExpWithFlags$1(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",a=!1,s=!1,i=!1;for(let l=0;l<n.length;l++){if(a){o+=n[l],a=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){i?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],i=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
36
|
-
]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
|
|
37
|
-
]))`;continue}}if(r.s&&n[l]==="."){o+=s?`${n[l]}\r
|
|
38
|
-
`:`[${n[l]}\r
|
|
39
|
-
]`;continue}o+=n[l],n[l]==="\\"?a=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function parseRecordDef$1(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:parseDef$1(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??parseAnyDef$1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef$1(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){const{type:n,...o}=parseStringDef$1(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...o}=parseBrandedDef$1(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function parseMapDef$1(e,t){if(t.mapStrategy==="record")return parseRecordDef$1(e,t);const r=parseDef$1(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||parseAnyDef$1(t),n=parseDef$1(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||parseAnyDef$1(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef$1(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 parseNeverDef$1(e){return e.target==="openAi"?void 0:{not:parseAnyDef$1({...e,currentPath:[...e.currentPath,"not"]})}}function parseNullDef$1(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings$1={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef$1(e,t){if(t.target==="openApi3")return asAnyOf$1(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in primitiveMappings$1&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,a)=>{const s=primitiveMappings$1[a._def.typeName];return s&&!o.includes(s)?[...o,s]: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 s=typeof a._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];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,s,i)=>i.indexOf(a)===s);return{type:o.length>1?o:o[0],enum:r.reduce((a,s)=>a.includes(s._def.value)?a:[...a,s._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 asAnyOf$1(e,t)}const asAnyOf$1=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>parseDef$1(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 parseNullableDef$1(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:primitiveMappings$1[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings$1[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=parseDef$1(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=parseDef$1(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef$1(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t);break}return r}function parseObjectDef$1(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},o=[],a=e.shape();for(const i in a){let l=a[i];if(l===void 0||l._def===void 0)continue;let c=safeIsOptional$1(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=parseDef$1(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||o.push(i))}o.length&&(n.required=o);const s=decideAdditionalProperties$1(e,t);return s!==void 0&&(n.additionalProperties=s),n}function decideAdditionalProperties$1(e,t){if(e.catchall._def.typeName!=="ZodNever")return parseDef$1(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 safeIsOptional$1(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef$1=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef$1(e.innerType._def,t);const r=parseDef$1(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:parseAnyDef$1(t)},r]}:parseAnyDef$1(t)},parsePipelineDef$1=(e,t)=>{if(t.pipeStrategy==="input")return parseDef$1(e.in._def,t);if(t.pipeStrategy==="output")return parseDef$1(e.out._def,t);const r=parseDef$1(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=parseDef$1(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function parsePromiseDef$1(e,t){return parseDef$1(e.type._def,t)}function parseSetDef$1(e,t){const n={type:"array",uniqueItems:!0,items:parseDef$1(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&setResponseValueAndErrors(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function parseTupleDef$1(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>parseDef$1(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef$1(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>parseDef$1(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef$1(e){return{not:parseAnyDef$1(e)}}function parseUnknownDef$1(e){return parseAnyDef$1(e)}const parseReadonlyDef$1=(e,t)=>parseDef$1(e.innerType._def,t),selectParser$1=(e,t,r)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef$1(e,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef$1(e,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef$1(e,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef$1(e,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef$1();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef$1(e,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef$1(r);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef$1(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef$1(e,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef$1(e,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef$1(e,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef$1(e,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef$1(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef$1(e,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef$1(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef$1(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef$1(e,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef$1(e,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef$1(e,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef$1(e,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef$1(e,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef$1(r);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef$1(e,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef$1(r);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef$1(r);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef$1(e,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef$1(e,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef$1(e,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef$1(e,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef$1(e,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}};function parseDef$1(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==ignoreOverride$1)return i}if(n&&!r){const i=get$ref$1(n,t);if(i!==void 0)return i}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const a=selectParser$1(e,e.typeName,t),s=typeof a=="function"?parseDef$1(a(),t):a;if(s&&addMeta$1(e,t,s),t.postProcess){const i=t.postProcess(s,e,t);return o.jsonSchema=s,i}return o.jsonSchema=s,s}const get$ref$1=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath$1(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`),parseAnyDef$1(t)):t.$refStrategy==="seen"?parseAnyDef$1(t):void 0}},addMeta$1=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema=(e,t)=>{const r=getRefs$1(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:parseDef$1(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??parseAnyDef$1(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=parseDef$1(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??parseAnyDef$1(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=o===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:a}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function mapMiniTarget(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function toJsonSchemaCompat(e,t){return isZ4Schema(e)?toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??"input"}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function getMethodLiteral(e){const r=getObjectShape(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=getLiteralValue(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function parseWithCompat(e,t){const r=safeParse(e,t);if(!r.success)throw r.error;return r.data}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;class Protocol{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(CancelledNotificationSchema,r=>{this._oncancel(r)}),this.setNotificationHandler(ProgressNotificationSchema,r=>{this._onprogress(r)}),this.setRequestHandler(PingRequestSchema,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(r,n)=>{const o=async()=>{const a=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const d=l,p=new McpError(d.error.code,d.error.message,d.error.data);u(p)}else{const d=i.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const s=await this._taskStore.getTask(a,n.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${a}`);if(!isTerminal(s.status))return await this._waitForTaskUpdate(a,n.signal),await o();if(isTerminal(s.status)){const i=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...i,_meta:{...i._meta,[RELATED_TASK_META_KEY]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(ListTasksRequestSchema,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 McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${r.params.taskId}`);if(isTerminal(o.status))throw new McpError(ErrorCode.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 McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(o){throw o instanceof McpError?o:new McpError(ErrorCode.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),McpError.fromError(ErrorCode.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,s)=>{o?.(a,s),isJSONRPCResultResponse(a)||isJSONRPCErrorResponse(a)?this._onresponse(a):isJSONRPCRequest(a)?this._onrequest(a,s):isJSONRPCNotification(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=McpError.fromError(ErrorCode.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?.[RELATED_TASK_META_KEY]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);const i=isTaskAugmentedRequestParams(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const d={relatedRequestId:t.id};a&&(d.relatedTask={taskId:a}),await this.notification(u,d)},sendRequest:async(u,d,p)=>{const f={...p,relatedRequestId:t.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});const h=f.relatedTask?.taskId??a;return h&&l&&await l.updateTaskStatus(h,"input_required"),await this.request(u,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(s.signal.aborted)return;const d={result:u,jsonrpc:"2.0",id:t.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:ErrorCode.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).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 s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(l);return}a(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),isJSONRPCResultResponse(t))n(t);else{const s=new McpError(t.error.code,t.error.message,t.error.data);n(s)}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(isJSONRPCResultResponse(t)&&t.result&&typeof t.result=="object"){const s=t.result;if(s.task&&typeof s.task=="object"){const i=s.task;typeof i.taskId=="string"&&(a=!0,this._taskProgressTokens.set(i.taskId,r))}}if(a||this._progressHandlers.delete(r),isJSONRPCResultResponse(t))o(t);else{const s=McpError.fromError(t.error.code,t.error.message,t.error.data);o(s)}}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(s){yield{type:"error",error:s instanceof McpError?s:new McpError(ErrorCode.InternalError,String(s))}}return}let a;try{const s=await this.request(t,CreateTaskResultSchema,n);if(s.task)a=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:i},isTerminal(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:i.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${a} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${a} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof McpError?s:new McpError(ErrorCode.InternalError,String(s))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const d=g=>{u(g)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(g){d(g);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[RELATED_TASK_META_KEY]:l}});const h=g=>{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(g)}},{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));const m=g instanceof McpError?g:new McpError(ErrorCode.RequestTimeout,String(g));u(m)};this._responseHandlers.set(p,g=>{if(!n?.signal?.aborted){if(g instanceof Error)return u(g);try{const m=safeParse(r,g.result);m.success?c(m.data):u(m.error)}catch(m){u(m)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const b=n?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,y=()=>h(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(p,b,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const g=m=>{const S=this._responseHandlers.get(p);S?S(m):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,g),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(m=>{this._cleanupTimeout(p),u(m)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(g=>{this._cleanupTimeout(p),u(g)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},GetTaskResultSchema,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},ListTasksResultSchema,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},CancelTaskResultSchema,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 i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[RELATED_TASK_META_KEY]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,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 i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[RELATED_TASK_META_KEY]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[RELATED_TASK_META_KEY]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){const n=getMethodLiteral(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,a)=>{const s=parseWithCompat(t,o);return Promise.resolve(r(s,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=getMethodLiteral(t);this._notificationHandlers.set(n,o=>{const a=parseWithCompat(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"&&isJSONRPCRequest(o.message)){const a=o.message.id,s=this._requestResolvers.get(a);s?(s(new McpError(ErrorCode.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 McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}const s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),a(new McpError(ErrorCode.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 McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(o,a,s)=>{await n.storeTaskResult(o,a,s,r);const i=await n.getTask(o,r);if(i){const l=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:i});await this.notification(l),isTerminal(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,a,s)=>{const i=await n.getTask(o,r);if(!i)throw new McpError(ErrorCode.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(isTerminal(i.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,a,s,r);const l=await n.getTask(o,r);if(l){const c=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:l});await this.notification(c),isTerminal(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function isPlainObject$1(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mergeCapabilities(e,t){const r={...e};for(const n in t){const o=n,a=t[o];if(a===void 0)continue;const s=r[o];isPlainObject$1(s)&&isPlainObject$1(a)?r[o]={...s,...a}:r[o]=a}return r}var dist={exports:{}},formats={},hasRequiredFormats;function requireFormats(){return hasRequiredFormats||(hasRequiredFormats=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(E,A){return{validate:E,compare:A}}e.fullFormats={date:t(a,s),time:t(l(!0),c),"date-time":t(p(!0),f),"iso-time":t(l(),u),"iso-date-time":t(p(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"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:x,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:m,int32:{type:"number",validate:_},int64:{type:"number",validate:$},float:{type:"number",validate:T},double:{type:"number",validate:T},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),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,f),"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,h),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(E){return E%4===0&&(E%100!==0||E%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(E){const A=n.exec(E);if(!A)return!1;const D=+A[1],U=+A[2],K=+A[3];return U>=1&&U<=12&&K>=1&&K<=(U===2&&r(D)?29:o[U])}function s(E,A){if(E&&A)return E>A?1:E<A?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(E){return function(D){const U=i.exec(D);if(!U)return!1;const K=+U[1],G=+U[2],te=+U[3],X=U[4],ue=U[5]==="-"?-1:1,V=+(U[6]||0),C=+(U[7]||0);if(V>23||C>59||E&&!X)return!1;if(K<=23&&G<=59&&te<60)return!0;const N=G-C*ue,L=K-V*ue-(N<0?1:0);return(L===23||L===-1)&&(N===59||N===-1)&&te<61}}function c(E,A){if(!(E&&A))return;const D=new Date("2020-01-01T"+E).valueOf(),U=new Date("2020-01-01T"+A).valueOf();if(D&&U)return D-U}function u(E,A){if(!(E&&A))return;const D=i.exec(E),U=i.exec(A);if(D&&U)return E=D[1]+D[2]+D[3],A=U[1]+U[2]+U[3],E>A?1:E<A?-1:0}const d=/t|\s/i;function p(E){const A=l(E);return function(U){const K=U.split(d);return K.length===2&&a(K[0])&&A(K[1])}}function f(E,A){if(!(E&&A))return;const D=new Date(E).valueOf(),U=new Date(A).valueOf();if(D&&U)return D-U}function h(E,A){if(!(E&&A))return;const[D,U]=E.split(d),[K,G]=A.split(d),te=s(D,K);if(te!==void 0)return te||c(U,G)}const b=/\/|:/,y=/^(?:[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 w(E){return b.test(E)&&y.test(E)}const g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(E){return g.lastIndex=0,g.test(E)}const S=-2147483648,v=2**31-1;function _(E){return Number.isInteger(E)&&E<=v&&E>=S}function $(E){return Number.isInteger(E)}function T(){return!0}const R=/[^\\]\\Z/;function x(E){if(R.test(E))return!1;try{return new RegExp(E),!0}catch{return!1}}})(formats)),formats}var limit={},hasRequiredLimit;function requireLimit(){return hasRequiredLimit||(hasRequiredLimit=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=requireAjv(),r=requireCodegen(),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:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:a,code(i){const{gen:l,data:c,schemaCode:u,keyword:d,it:p}=i,{opts:f,self:h}=p;if(!f.validateFormats)return;const b=new t.KeywordCxt(p,h.RULES.all.format.definition,"format");b.$data?y():w();function y(){const m=l.scopeValue("formats",{ref:h.formats,code:f.code.formats}),S=l.const("fmt",(0,r._)`${m}[${b.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,g(S)))}function w(){const m=b.schema,S=h.formats[m];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${d}": format "${m}" does not define "compare" function`);const v=l.scopeValue("formats",{key:m,ref:S,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(m)}`:void 0});i.fail$data(g(v))}function g(m){return(0,r._)`${m}.compare(${c}, ${u}) ${o[d].fail} 0`}},dependencies:["format"]};const s=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=s})(limit)),limit}var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=requireFormats(),n=requireLimit(),o=requireCodegen(),a=new o.Name("fullFormats"),s=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,a),c;const[d,p]=u.mode==="fast"?[r.fastFormats,s]:[r.fullFormats,a],f=u.formats||r.formatNames;return l(c,f,d,p),u.keywords&&(0,n.default)(c),c};i.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,d,p){var f,h;(f=(h=c.opts.code).formats)!==null&&f!==void 0||(h.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const b of u)c.addFormat(b,d[b])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(dist,dist.exports)),dist.exports}var distExports=requireDist();const _addFormats=getDefaultExportFromCjs(distExports);function createDefaultAjvInstance(){const e=new Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _addFormats(e),e}class AjvJsonSchemaValidator{constructor(t){this._ajv=t??createDefaultAjvInstance()}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 ExperimentalClientTasks{constructor(t){this._client=t}async*callToolStream(t,r=CallToolResultSchema$1,n){const o=this._client,a={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,a),i=o.getToolOutputValidator(t.name);for await(const l of s){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new McpError(ErrorCode.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof McpError){yield{type:"error",error:u};return}yield{type:"error",error:new McpError(ErrorCode.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 assertToolsCallTaskCapability(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 assertClientRequestTaskCapability(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 applyElicitationDefaults(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&&applyElicitationDefaults(a,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&applyElicitationDefaults(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&applyElicitationDefaults(r,t)}}function getSupportedElicitationModes(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 Client extends Protocol{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 AjvJsonSchemaValidator,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ToolListChangedNotificationSchema,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",PromptListChangedNotificationSchema,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ResourceListChangedNotificationSchema,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalClientTasks(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,t)}setRequestHandler(t,r){const o=getObjectShape(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let a;if(isZ4Schema(o)){const i=o;a=i._zod?.def?.value??i.value}else{const i=o;a=i._def?.value??i.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");const s=a;if(s==="elicitation/create"){const i=async(l,c)=>{const u=safeParse(ElicitRequestSchema,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation request: ${g}`)}const{params:d}=u.data;d.mode=d.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=getSupportedElicitationModes(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new McpError(ErrorCode.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new McpError(ErrorCode.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(r(l,c));if(d.task){const g=safeParse(CreateTaskResultSchema,h);if(!g.success){const m=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${m}`)}return g.data}const b=safeParse(ElicitResultSchema$1,h);if(!b.success){const g=b.error instanceof Error?b.error.message:String(b.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation result: ${g}`)}const y=b.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{applyElicitationDefaults(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(s==="sampling/createMessage"){const i=async(l,c)=>{const u=safeParse(CreateMessageRequestSchema,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling request: ${y}`)}const{params:d}=u.data,p=await Promise.resolve(r(l,c));if(d.task){const y=safeParse(CreateTaskResultSchema,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const h=d.tools||d.toolChoice?CreateMessageResultWithToolsSchema:CreateMessageResultSchema,b=safeParse(h,p);if(!b.success){const y=b.error instanceof Error?b.error.message:String(b.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling result: ${y}`)}return b.data};return super.setRequestHandler(t,i)}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:LATEST_PROTOCOL_VERSION$1,capabilities:this._capabilities,clientInfo:this._clientInfo}},InitializeResultSchema$1,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!SUPPORTED_PROTOCOL_VERSIONS$1.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){assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&assertClientRequestTaskCapability(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},EmptyResultSchema,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},CompleteResultSchema$1,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},EmptyResultSchema,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},GetPromptResultSchema$1,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},ListPromptsResultSchema$1,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},ListResourcesResultSchema$1,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ListResourceTemplatesResultSchema$1,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},ReadResourceResultSchema$1,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},EmptyResultSchema,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},EmptyResultSchema,r)}async callTool(t,r=CallToolResultSchema$1,n){if(this.isToolTaskRequired(t.name))throw new McpError(ErrorCode.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 McpError(ErrorCode.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const s=a(o.structuredContent);if(!s.valid)throw new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof McpError?s:new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}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},ListToolsResultSchema$1,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const a=ListChangedOptionsBaseSchema.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:s,debounceMs:i}=a.data,{onChanged:l}=n,c=async()=>{if(!s){l(null,null);return}try{const d=await o();l(null,d)}catch(d){const p=d instanceof Error?d:new Error(String(d));l(p,null)}},u=()=>{if(i){const d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class ParseError 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 LF=10,CR=13,SPACE=32;function noop(e){}function createParser(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=noop,onError:r=noop,onRetry:n=noop,onComment:o,maxBufferSize:a}=e,s=[];let i=0,l=!0,c,u="",d=0,p,f=!1;function h(v){if(f)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,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),s.length===0){const T=y(v);T!==""&&(s.push(T),i=T.length),b();return}if(v.indexOf(`
|
|
40
|
-
`)===-1&&v.indexOf("\r")===-1){s.push(v),i+=v.length,b();return}s.push(v);const _=s.join("");s.length=0,i=0;const $=y(_);$!==""&&(s.push($),i=$.length),b()}function b(){a!==void 0&&(i+u.length<=a||(f=!0,s.length=0,i=0,c=void 0,u="",d=0,p=void 0,r(new ParseError(`Buffered data exceeded max buffer size of ${a} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let _=0;if(v.indexOf("\r")===-1){let $=v.indexOf(`
|
|
41
|
-
`,_);for(;$!==-1;){if(_===$){d>0&&t({id:c,event:p,data:u}),c=void 0,u="",d=0,p=void 0,_=$+1,$=v.indexOf(`
|
|
42
|
-
`,_);continue}const T=v.charCodeAt(_);if(isDataPrefix(v,_,T)){const R=v.charCodeAt(_+5)===SPACE?_+6:_+5,x=v.slice(R,$);if(d===0&&v.charCodeAt($+1)===LF){t({id:c,event:p,data:x}),c=void 0,u="",p=void 0,_=$+2,$=v.indexOf(`
|
|
43
|
-
`,_);continue}u=d===0?x:`${u}
|
|
44
|
-
${x}`,d++}else isEventPrefix(v,_,T)?p=v.slice(v.charCodeAt(_+6)===SPACE?_+7:_+6,$)||void 0:w(v,_,$);_=$+1,$=v.indexOf(`
|
|
45
|
-
`,_)}return v.slice(_)}for(;_<v.length;){const $=v.indexOf("\r",_),T=v.indexOf(`
|
|
46
|
-
`,_);let R=-1;if($!==-1&&T!==-1?R=$<T?$:T:$!==-1?$===v.length-1?R=-1:R=$:T!==-1&&(R=T),R===-1)break;w(v,_,R),_=R+1,v.charCodeAt(_-1)===CR&&v.charCodeAt(_)===LF&&_++}return v.slice(_)}function w(v,_,$){if(_===$){m();return}const T=v.charCodeAt(_);if(isDataPrefix(v,_,T)){const U=v.charCodeAt(_+5)===SPACE?_+6:_+5,K=v.slice(U,$);u=d===0?K:`${u}
|
|
47
|
-
${K}`,d++;return}if(isEventPrefix(v,_,T)){p=v.slice(v.charCodeAt(_+6)===SPACE?_+7:_+6,$)||void 0;return}if(T===105&&v.charCodeAt(_+1)===100&&v.charCodeAt(_+2)===58){const U=v.slice(v.charCodeAt(_+3)===SPACE?_+4:_+3,$);c=U.includes("\0")?void 0:U;return}if(T===58){if(o){const U=v.slice(_,$);o(U.slice(v.charCodeAt(_+1)===SPACE?2:1))}return}const R=v.slice(_,$),x=R.indexOf(":");if(x===-1){g(R,"",R);return}const E=R.slice(0,x),A=R.charCodeAt(x+1)===SPACE?2:1,D=R.slice(x+A);g(E,D,R)}function g(v,_,$){switch(v){case"event":p=_||void 0;break;case"data":u=d===0?_:`${u}
|
|
48
|
-
${_}`,d++;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new ParseError(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:$}));break;default:r(new ParseError(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:$}));break}}function m(){d>0&&t({id:c,event:p,data:u}),c=void 0,u="",d=0,p=void 0}function S(v={}){if(v.consume&&s.length>0){const _=s.join("");w(_,0,_.length)}l=!0,c=void 0,u="",d=0,p=void 0,s.length=0,i=0,f=!1}return{feed:h,reset:S}}function isDataPrefix(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 isEventPrefix(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 ErrorEvent 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(inspectableError(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(inspectableError(this),r)}}function syntaxError(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function flattenError(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(flattenError).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${flattenError(e.cause)}`:e.message:`${e}`}function inspectableError(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var __typeError=e=>{throw TypeError(e)},__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),_readyState,_url,_redirectUrl,_withCredentials,_fetch,_reconnectInterval,_reconnectTimer,_lastEventId,_controller,_parser,_onError,_onMessage,_onOpen,_EventSource_instances,connect_fn,_onFetchResponse,_onFetchError,getRequestOptions_fn,_onEvent,_onRetryChange,failConnection_fn,scheduleReconnect_fn,_reconnect;class EventSource extends EventTarget{constructor(t,r){var n,o;super(),__privateAdd(this,_EventSource_instances),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,__privateAdd(this,_readyState),__privateAdd(this,_url),__privateAdd(this,_redirectUrl),__privateAdd(this,_withCredentials),__privateAdd(this,_fetch),__privateAdd(this,_reconnectInterval),__privateAdd(this,_reconnectTimer),__privateAdd(this,_lastEventId,null),__privateAdd(this,_controller),__privateAdd(this,_parser),__privateAdd(this,_onError,null),__privateAdd(this,_onMessage,null),__privateAdd(this,_onOpen,null),__privateAdd(this,_onFetchResponse,async a=>{var s;__privateGet(this,_parser).reset();const{body:i,redirected:l,status:c,headers:u}=a;if(c===204){__privateMethod(this,_EventSource_instances,failConnection_fn).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?__privateSet(this,_redirectUrl,new URL(a.url)):__privateSet(this,_redirectUrl,void 0),c!==200){__privateMethod(this,_EventSource_instances,failConnection_fn).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){__privateMethod(this,_EventSource_instances,failConnection_fn).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(__privateGet(this,_readyState)===this.CLOSED)return;__privateSet(this,_readyState,this.OPEN);const d=new Event("open");if((s=__privateGet(this,_onOpen))==null||s.call(this,d),this.dispatchEvent(d),typeof i!="object"||!i||!("getReader"in i)){__privateMethod(this,_EventSource_instances,failConnection_fn).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=i.getReader();let h=!0;do{const{done:b,value:y}=await f.read();y&&__privateGet(this,_parser).feed(p.decode(y,{stream:!b})),b&&(h=!1,__privateGet(this,_parser).reset(),__privateMethod(this,_EventSource_instances,scheduleReconnect_fn).call(this))}while(h)}),__privateAdd(this,_onFetchError,a=>{__privateSet(this,_controller,void 0),!(a.name==="AbortError"||a.type==="aborted")&&__privateMethod(this,_EventSource_instances,scheduleReconnect_fn).call(this,flattenError(a))}),__privateAdd(this,_onEvent,a=>{typeof a.id=="string"&&__privateSet(this,_lastEventId,a.id);const s=new MessageEvent(a.event||"message",{data:a.data,origin:__privateGet(this,_redirectUrl)?__privateGet(this,_redirectUrl).origin:__privateGet(this,_url).origin,lastEventId:a.id||""});__privateGet(this,_onMessage)&&(!a.event||a.event==="message")&&__privateGet(this,_onMessage).call(this,s),this.dispatchEvent(s)}),__privateAdd(this,_onRetryChange,a=>{__privateSet(this,_reconnectInterval,a)}),__privateAdd(this,_reconnect,()=>{__privateSet(this,_reconnectTimer,void 0),__privateGet(this,_readyState)===this.CONNECTING&&__privateMethod(this,_EventSource_instances,connect_fn).call(this)});try{if(t instanceof URL)__privateSet(this,_url,t);else if(typeof t=="string")__privateSet(this,_url,new URL(t,getBaseURL()));else throw new Error("Invalid URL")}catch{throw syntaxError("An invalid or illegal string was specified")}__privateSet(this,_parser,createParser({onEvent:__privateGet(this,_onEvent),onRetry:__privateGet(this,_onRetryChange)})),__privateSet(this,_readyState,this.CONNECTING),__privateSet(this,_reconnectInterval,3e3),__privateSet(this,_fetch,(n=r?.fetch)!=null?n:globalThis.fetch),__privateSet(this,_withCredentials,(o=r?.withCredentials)!=null?o:!1),__privateMethod(this,_EventSource_instances,connect_fn).call(this)}get readyState(){return __privateGet(this,_readyState)}get url(){return __privateGet(this,_url).href}get withCredentials(){return __privateGet(this,_withCredentials)}get onerror(){return __privateGet(this,_onError)}set onerror(t){__privateSet(this,_onError,t)}get onmessage(){return __privateGet(this,_onMessage)}set onmessage(t){__privateSet(this,_onMessage,t)}get onopen(){return __privateGet(this,_onOpen)}set onopen(t){__privateSet(this,_onOpen,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(){__privateGet(this,_reconnectTimer)&&clearTimeout(__privateGet(this,_reconnectTimer)),__privateGet(this,_readyState)!==this.CLOSED&&(__privateGet(this,_controller)&&__privateGet(this,_controller).abort(),__privateSet(this,_readyState,this.CLOSED),__privateSet(this,_controller,void 0))}}_readyState=new WeakMap,_url=new WeakMap,_redirectUrl=new WeakMap,_withCredentials=new WeakMap,_fetch=new WeakMap,_reconnectInterval=new WeakMap,_reconnectTimer=new WeakMap,_lastEventId=new WeakMap,_controller=new WeakMap,_parser=new WeakMap,_onError=new WeakMap,_onMessage=new WeakMap,_onOpen=new WeakMap,_EventSource_instances=new WeakSet,connect_fn=function(){__privateSet(this,_readyState,this.CONNECTING),__privateSet(this,_controller,new AbortController),__privateGet(this,_fetch)(__privateGet(this,_url),__privateMethod(this,_EventSource_instances,getRequestOptions_fn).call(this)).then(__privateGet(this,_onFetchResponse)).catch(__privateGet(this,_onFetchError))},_onFetchResponse=new WeakMap,_onFetchError=new WeakMap,getRequestOptions_fn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...__privateGet(this,_lastEventId)?{"Last-Event-ID":__privateGet(this,_lastEventId)}:void 0},cache:"no-store",signal:(e=__privateGet(this,_controller))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},_onEvent=new WeakMap,_onRetryChange=new WeakMap,failConnection_fn=function(e,t){var r;__privateGet(this,_readyState)!==this.CLOSED&&__privateSet(this,_readyState,this.CLOSED);const n=new ErrorEvent("error",{code:t,message:e});(r=__privateGet(this,_onError))==null||r.call(this,n),this.dispatchEvent(n)},scheduleReconnect_fn=function(e,t){var r;if(__privateGet(this,_readyState)===this.CLOSED)return;__privateSet(this,_readyState,this.CONNECTING);const n=new ErrorEvent("error",{code:t,message:e});(r=__privateGet(this,_onError))==null||r.call(this,n),this.dispatchEvent(n),__privateSet(this,_reconnectTimer,setTimeout(__privateGet(this,_reconnect),__privateGet(this,_reconnectInterval)))},_reconnect=new WeakMap,EventSource.CONNECTING=0,EventSource.OPEN=1,EventSource.CLOSED=2;function getBaseURL(){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}function normalizeHeaders$2(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function createFetchWithInit(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...normalizeHeaders$2(t.headers),...normalizeHeaders$2(n.headers)}:t.headers};return e(r,o)}:e}let crypto$1;crypto$1=globalThis.crypto;async function getRandomValues(e){return(await crypto$1).getRandomValues(new Uint8Array(e))}async function random(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await getRandomValues(e-n.length);for(const a of o)a<r&&(n+=t[a%t.length])}return n}async function generateVerifier(e){return await random(e)}async function generateChallenge(e){const t=await(await crypto$1).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await generateVerifier(e),r=await generateChallenge(t);return{code_verifier:t,code_challenge:r}}const SafeUrlSchema$1=url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).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"}),OAuthProtectedResourceMetadataSchema$1=looseObject({resource:string().url(),authorization_servers:array$1(SafeUrlSchema$1).optional(),jwks_uri:string().url().optional(),scopes_supported:array$1(string()).optional(),bearer_methods_supported:array$1(string()).optional(),resource_signing_alg_values_supported:array$1(string()).optional(),resource_name:string().optional(),resource_documentation:string().optional(),resource_policy_uri:string().url().optional(),resource_tos_uri:string().url().optional(),tls_client_certificate_bound_access_tokens:boolean().optional(),authorization_details_types_supported:array$1(string()).optional(),dpop_signing_alg_values_supported:array$1(string()).optional(),dpop_bound_access_tokens_required:boolean().optional()}),OAuthMetadataSchema$1=looseObject({issuer:string(),authorization_endpoint:SafeUrlSchema$1,token_endpoint:SafeUrlSchema$1,registration_endpoint:SafeUrlSchema$1.optional(),scopes_supported:array$1(string()).optional(),response_types_supported:array$1(string()),response_modes_supported:array$1(string()).optional(),grant_types_supported:array$1(string()).optional(),token_endpoint_auth_methods_supported:array$1(string()).optional(),token_endpoint_auth_signing_alg_values_supported:array$1(string()).optional(),service_documentation:SafeUrlSchema$1.optional(),revocation_endpoint:SafeUrlSchema$1.optional(),revocation_endpoint_auth_methods_supported:array$1(string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array$1(string()).optional(),introspection_endpoint:string().optional(),introspection_endpoint_auth_methods_supported:array$1(string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array$1(string()).optional(),code_challenge_methods_supported:array$1(string()).optional(),client_id_metadata_document_supported:boolean().optional()}),OpenIdProviderMetadataSchema$1=looseObject({issuer:string(),authorization_endpoint:SafeUrlSchema$1,token_endpoint:SafeUrlSchema$1,userinfo_endpoint:SafeUrlSchema$1.optional(),jwks_uri:SafeUrlSchema$1,registration_endpoint:SafeUrlSchema$1.optional(),scopes_supported:array$1(string()).optional(),response_types_supported:array$1(string()),response_modes_supported:array$1(string()).optional(),grant_types_supported:array$1(string()).optional(),acr_values_supported:array$1(string()).optional(),subject_types_supported:array$1(string()),id_token_signing_alg_values_supported:array$1(string()),id_token_encryption_alg_values_supported:array$1(string()).optional(),id_token_encryption_enc_values_supported:array$1(string()).optional(),userinfo_signing_alg_values_supported:array$1(string()).optional(),userinfo_encryption_alg_values_supported:array$1(string()).optional(),userinfo_encryption_enc_values_supported:array$1(string()).optional(),request_object_signing_alg_values_supported:array$1(string()).optional(),request_object_encryption_alg_values_supported:array$1(string()).optional(),request_object_encryption_enc_values_supported:array$1(string()).optional(),token_endpoint_auth_methods_supported:array$1(string()).optional(),token_endpoint_auth_signing_alg_values_supported:array$1(string()).optional(),display_values_supported:array$1(string()).optional(),claim_types_supported:array$1(string()).optional(),claims_supported:array$1(string()).optional(),service_documentation:string().optional(),claims_locales_supported:array$1(string()).optional(),ui_locales_supported:array$1(string()).optional(),claims_parameter_supported:boolean().optional(),request_parameter_supported:boolean().optional(),request_uri_parameter_supported:boolean().optional(),require_request_uri_registration:boolean().optional(),op_policy_uri:SafeUrlSchema$1.optional(),op_tos_uri:SafeUrlSchema$1.optional(),client_id_metadata_document_supported:boolean().optional()}),OpenIdProviderDiscoveryMetadataSchema$1=object$2({...OpenIdProviderMetadataSchema$1.shape,...OAuthMetadataSchema$1.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema$1=object$2({access_token:string(),id_token:string().optional(),token_type:string(),expires_in:number().optional(),scope:string().optional(),refresh_token:string().optional()}).strip(),OAuthErrorResponseSchema$1=object$2({error:string(),error_description:string().optional(),error_uri:string().optional()}),OptionalSafeUrlSchema=SafeUrlSchema$1.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema$1=object$2({redirect_uris:array$1(SafeUrlSchema$1),token_endpoint_auth_method:string().optional(),grant_types:array$1(string()).optional(),response_types:array$1(string()).optional(),client_name:string().optional(),client_uri:SafeUrlSchema$1.optional(),logo_uri:OptionalSafeUrlSchema,scope:string().optional(),contacts:array$1(string()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string().optional(),jwks_uri:SafeUrlSchema$1.optional(),jwks:any().optional(),software_id:string().optional(),software_version:string().optional(),software_statement:string().optional()}).strip(),OAuthClientInformationSchema$1=object$2({client_id:string(),client_secret:string().optional(),client_id_issued_at:number$1().optional(),client_secret_expires_at:number$1().optional()}).strip(),OAuthClientInformationFullSchema$1=OAuthClientMetadataSchema$1.merge(OAuthClientInformationSchema$1);object$2({error:string(),error_description:string().optional()}).strip(),object$2({token:string(),token_type_hint:string().optional()}).strip();function resourceUrlFromServerUrl$1(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function checkResourceAllowed$1({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 OAuthError 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 InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";let InvalidClientError$1=class extends OAuthError{};InvalidClientError$1.errorCode="invalid_client";let InvalidGrantError$1=class extends OAuthError{};InvalidGrantError$1.errorCode="invalid_grant";let UnauthorizedClientError$1=class extends OAuthError{};UnauthorizedClientError$1.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";let ServerError$1=class extends OAuthError{};ServerError$1.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";class InvalidTargetError extends OAuthError{}InvalidTargetError.errorCode="invalid_target";const OAUTH_ERRORS$1={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError$1.errorCode]:InvalidClientError$1,[InvalidGrantError$1.errorCode]:InvalidGrantError$1,[UnauthorizedClientError$1.errorCode]:UnauthorizedClientError$1,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError$1.errorCode]:ServerError$1,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError,[InvalidTargetError.errorCode]:InvalidTargetError};let UnauthorizedError$1=class extends Error{constructor(t){super(t??"Unauthorized")}};function isClientAuthMethod(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod$1(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&&isClientAuthMethod(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 applyClientAuthentication$1(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":applyBasicAuth$1(o,a,r);return;case"client_secret_post":applyPostAuth$1(o,a,n);return;case"none":applyPublicAuth$1(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function applyBasicAuth$1(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 applyPostAuth$1(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function applyPublicAuth$1(e,t){t.set("client_id",e)}async function parseErrorResponse$1(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=OAuthErrorResponseSchema$1.parse(JSON.parse(r)),{error:o,error_description:a,error_uri:s}=n,i=OAUTH_ERRORS$1[o]||ServerError$1;return new i(a||"",s)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ServerError$1(o)}}async function auth$1(e,t){try{return await authInternal$1(e,t)}catch(r){if(r instanceof InvalidClientError$1||r instanceof UnauthorizedClientError$1)return await e.invalidateCredentials?.("all"),await authInternal$1(e,t);if(r instanceof InvalidGrantError$1)return await e.invalidateCredentials?.("tokens"),await authInternal$1(e,t);throw r}}async function authInternal$1(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:a}){let s,i;try{s=await discoverOAuthProtectedResourceMetadata$1(t,{resourceMetadataUrl:o},a),s.authorization_servers&&s.authorization_servers.length>0&&(i=s.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await selectResourceURL$1(t,e,s),c=await discoverAuthorizationServerMetadata$1(i,{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 y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!isHttpsUrl(w))throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const m=await registerClient$1(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(m),u=m}}const d=!e.redirectUrl;if(r!==void 0||d){const y=await fetchToken(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:a});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await refreshAuthorization$1(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof OAuthError)||y instanceof ServerError$1))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:b}=await startAuthorization$1(i,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(h),"REDIRECT"}function isHttpsUrl(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function selectResourceURL$1(e,t,r){const n=resourceUrlFromServerUrl$1(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!checkResourceAllowed$1({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 extractWWWAuthenticateParams(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=extractFieldFromWwwAuth(e,"resource_metadata")||void 0;let a;if(o)try{a=new URL(o)}catch{}const s=extractFieldFromWwwAuth(e,"scope")||void 0,i=extractFieldFromWwwAuth(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:i}}function extractFieldFromWwwAuth(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 discoverOAuthProtectedResourceMetadata$1(e,t,r=fetch){const n=await discoverMetadataWithFallback$1(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 OAuthProtectedResourceMetadataSchema$1.parse(await n.json())}async function fetchWithCorsRetry$1(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?fetchWithCorsRetry$1(e,void 0,r):void 0;throw n}}function buildWellKnownPath$1(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tryMetadataDiscovery$1(e,t,r=fetch){return await fetchWithCorsRetry$1(e,{"MCP-Protocol-Version":t},r)}function shouldAttemptFallback$1(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function discoverMetadataWithFallback$1(e,t,r,n){const o=new URL(e),a=n?.protocolVersion??LATEST_PROTOCOL_VERSION$1;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const l=buildWellKnownPath$1(t,o.pathname);s=new URL(l,n?.metadataServerUrl??o),s.search=o.search}let i=await tryMetadataDiscovery$1(s,a,r);if(!n?.metadataUrl&&shouldAttemptFallback$1(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await tryMetadataDiscovery$1(l,a,r)}return i}function buildDiscoveryUrls$1(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 discoverAuthorizationServerMetadata$1(e,{fetchFn:t=fetch,protocolVersion:r=LATEST_PROTOCOL_VERSION$1}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=buildDiscoveryUrls$1(e);for(const{url:a,type:s}of o){const i=await fetchWithCorsRetry$1(a,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?OAuthMetadataSchema$1.parse(await i.json()):OpenIdProviderDiscoveryMetadataSchema$1.parse(await i.json())}}}async function startAuthorization$1(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:s}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else i=new URL("/authorize",e);const l=await pkceChallenge(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),i.searchParams.set("redirect_uri",String(n)),a&&i.searchParams.set("state",a),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),s&&i.searchParams.set("resource",s.href),{authorizationUrl:i,codeVerifier:c}}function prepareAuthorizationCodeRequest(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function executeTokenRequest(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:a,fetchFn:s}){const i=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,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],d=selectClientAuthMethod$1(n,u);applyClientAuthentication$1(d,n,l,r)}const c=await(s??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await parseErrorResponse$1(c);return OAuthTokensSchema$1.parse(await c.json())}async function refreshAuthorization$1(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:s}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await executeTokenRequest(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:a,resource:o,fetchFn:s});return{refresh_token:n,...l}}async function fetchToken(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:a}={}){const s=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(s)),!i){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();i=prepareAuthorizationCodeRequest(o,c,e.redirectUrl)}const l=await e.clientInformation();return executeTokenRequest(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:a})}async function registerClient$1(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 parseErrorResponse$1(a);return OAuthClientInformationFullSchema$1.parse(await a.json())}class SseError extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class SSEClientTransport{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=createFetchWithInit(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new UnauthorizedError$1("No auth provider");let t;try{t=await auth$1(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 UnauthorizedError$1;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=normalizeHeaders$2(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 EventSource(this._url.href,{...this._eventSourceInit,fetch:async(o,a)=>{const s=await this._commonHeaders();s.set("Accept","text/event-stream");const i=await t(o,{...a,headers:s});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=extractWWWAuthenticateParams(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const a=new SseError(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(s){n(s),this.onerror?.(s),this.close();return}r()}),this._eventSource.onmessage=o=>{const a=o;let s;try{s=JSONRPCMessageSchema$1.parse(JSON.parse(a.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(s)}})}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 UnauthorizedError$1("No auth provider");if(await auth$1(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError$1("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:s,scope:i}=extractWWWAuthenticateParams(o);if(this._resourceMetadataUrl=s,this._scope=i,await auth$1(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError$1;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 EventSourceParserStream extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let a;super({start(s){a=createParser({onEvent:i=>{s.enqueue(i)},onError(i){typeof t=="function"&&t(i),(t==="terminate"||i.type==="max-buffer-size-exceeded")&&s.error(i)},onRetry:r,onComment:n,maxBufferSize:o})},transform(s){a.feed(s)}})}}const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class StreamableHTTPError extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class StreamableHTTPClientTransport{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=createFetchWithInit(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS}async _authThenStart(){if(!this._authProvider)throw new UnauthorizedError$1("No auth provider");let t;try{t=await auth$1(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 UnauthorizedError$1;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=normalizeHeaders$2(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 StreamableHTTPError(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 s,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:h}=await u.read();if(h)break;if(f.id&&(s=f.id,i=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const b=JSONRPCMessageSchema$1.parse(JSON.parse(f.data));isJSONRPCResultResponse(b)&&(l=!0,a!==void 0&&(b.id=a)),this.onmessage?.(b)}catch(b){this.onerror?.(b)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:a},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:a},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}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 UnauthorizedError$1("No auth provider");if(await auth$1(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError$1("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:isJSONRPCRequest(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 s={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,s),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new StreamableHTTPError(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:h}=extractWWWAuthenticateParams(i);if(this._resourceMetadataUrl=f,this._scope=h,await auth$1(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError$1;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:h,error:b}=extractWWWAuthenticateParams(i);if(b==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new StreamableHTTPError(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await auth$1(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new UnauthorizedError$1;return this.send(t)}}throw new StreamableHTTPError(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),isInitializedNotification(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,d=i.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){const p=await i.json(),f=Array.isArray(p)?p.map(h=>JSONRPCMessageSchema$1.parse(h)):[JSONRPCMessageSchema$1.parse(p)];for(const h of f)this.onmessage?.(h)}else throw await i.body?.cancel(),new StreamableHTTPError(-1,`Unexpected content type: ${d}`);else await i.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 StreamableHTTPError(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})}}const SUBPROTOCOL="mcp";class WebSocketClientTransport{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,SUBPROTOCOL),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=JSONRPCMessageSchema$1.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 _0x4f2826=_0xad7a;(function(e,t){const r=_0xad7a,n=_0xad7a,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())}})(_0xf7c7,-118057+3521*-35+-2099*-233);const getGlobalObject=()=>{const e=_0xad7a,t=_0xad7a,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(s,i){return s!==i},r[t(394)]=t(414),r.ktWqD=function(s,i){return s!==i},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}},sendMessage=(e,t,r)=>{const n=_0xad7a,o=_0xad7a,a={};a.eOzBp=function(i,l){return i!==l},a.ooaJk="undefined",a[n(402)]=function(i,l){return i===l},a[n(421)]="function";const s=a;s[o(389)](typeof window,s.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&s.pTvSc(typeof e[o(423)],s[n(421)])&&e.postMessage(t,r)},setMessageHandler=(e,t)=>{const r=_0xad7a,n=_0xad7a,o={};o.nTCfA=function(s,i){return s in i},o[r(390)]="addEventListener",o[r(385)]=function(s,i){return s===i},o[r(409)]="function",o.VaHpd=n(392),o[n(384)]=r(417),o.FPOYW=function(s,i){return s!==i};const a=o;a.nTCfA(a.ogKey,e)&&a[n(385)](typeof e.addEventListener,a[n(409)])?e[n(386)](a.VaHpd,t):a[n(384)]in e&&a[r(398)](typeof e[n(417)],r(414))&&(e.onmessage=t)};class MessageChannelTransport{constructor(t){this._port=t}async[_0x4f2826(401)](){const t=_0x4f2826,r=_0x4f2826;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,a;const s=t;try{const i=JSONRPCMessageSchema$1.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[s(412)][s(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(a=this[s(383)])==null||a.call(this,l)}},this._port.onmessageerror=n=>{var o;const a=r,s=new Error("MessageChannel transport error: "+JSON[a(415)](n));(o=this.onerror)==null||o.call(this,s)},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 s;const i=_0xad7a,l=_0xad7a;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(s=this.onerror)==null||s.call(this,u),a(u)}})}async close(){var t,r;const n=_0x4f2826,o=_0x4f2826;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class MessageChannelClientTransport extends MessageChannelTransport{constructor(t,r=getGlobalObject()){const n=_0x4f2826,o={lSpBh:function(s,i,l,c){return s(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const a=new MessageChannel;this._port=a[n(410)],o[n(418)](sendMessage,this._globalObject,{endpoint:this[n(397)]},[a[n(429)]])}}class MessageChannelServerTransport extends MessageChannelTransport{constructor(t,r=getGlobalObject()){const n=_0x4f2826,o=_0x4f2826,a={HITdC:function(s,i){return s===i},QdDxM:function(s){return s()},jowPp:function(s,i,l){return s(i,l)}};super(),this[n(397)]=t,this[o(388)]=r,this[o(416)]=new Promise(s=>{const i=n,l={XlglK:function(c,u){return a.HITdC(c,u)},pXlad:function(c){return a.QdDxM(c)}};a[i(427)](setMessageHandler,this._globalObject,c=>{const u=i,d=i;c[u(412)]&&l.XlglK(c.data[d(396)],this._endpoint)&&(this[u(422)]=c[d(430)][-3036+-1518*-2],l.pXlad(s))})})}async listen(){return this._listen}}function _0xf7c7(){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 _0xf7c7=function(){return e},_0xf7c7()}function _0xad7a(e,t){const r=_0xf7c7();return _0xad7a=function(n,o){return n=n-(17227+1*-16844),r[n]},_0xad7a(e,t)}const createTransportPair=()=>{const e=new MessageChannel;return[new MessageChannelTransport(e.port1),new MessageChannelTransport(e.port2)]};(function(e,t){const r=_0x21a3,n=_0x21a3,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())}})(_0x3610,-411935*1+228107+208149*2);const forwardServerRequest=async(e,t,r)=>{var n;const o=_0x21a3,a=_0x21a3,s={};s.VRyiJ="tools/list",s.VkPYu="tools/call",s[o(475)]=o(411),s.SoCaE="resources/templates/list",s[a(484)]="resources/read",s[o(461)]="prompts/get",s.srIIC=a(477),s[a(436)]=a(478),s[a(442)]=o(437),s.dEmVs=o(465);const i=s,{id:l,method:c,params:u}=r;let d={};switch(c){case i.VRyiJ:d=await t.listTools(u);break;case i.VkPYu:d=await t.callTool(u);break;case i.fgMSD:d=await t.listResources(u);break;case i[a(466)]:d=await t.listResourceTemplates(u);break;case i.sthgI:d=await t[o(455)](u);break;case a(486):d=await t.subscribeResource(u);break;case o(410):d=await t.unsubscribeResource(u);break;case i[a(461)]:d=await t[a(414)](u);break;case i[o(412)]:d=await t[o(491)](u);break;case i[o(436)]:d=await t[o(478)]();break;case i.kkNqg:d=await t.complete(u);break;case o(464):d=await t.setLoggingLevel(u?.[a(443)]);break}const p={};p.result=d,p.jsonrpc=i[a(472)],p.id=l,await((n=e?.[a(488)])==null?void 0:n[o(460)](p))},forwardClientRequest=async(e,t,r)=>{var n;const o=_0x21a3,a=_0x21a3,s={};s[o(487)]=a(462),s.ypHTC="ping",s.fPExS=o(465);const i=s,{id:l,method:c,params:u}=r;let d={};switch(c){case"roots/list":const f={};f.method=c,f[a(446)]=u,d=await t[o(469)](f,ListRootsResultSchema);break;case"sampling/createMessage":const h={};h[o(481)]=c,h[o(446)]=u,d=await t.request(h,CreateMessageResultSchema);break;case i[o(487)]:const b={};b.method=c,b[a(446)]=u,d=await t.request(b,ElicitResultSchema$1);break;case i.ypHTC:const y={};y.method=c,d=await t.request(y,EmptyResultSchema);break}const p={};return p.result=d,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),d};function _0x21a3(e,t){const r=_0x3610();return _0x21a3=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},_0x21a3(e,t)}const forwardServerOnRequest=(e,t)=>{const r=_0x21a3,n=_0x21a3,o={vYlhn:function(s,i){return s===i},DhPFX:r(470),NYVNC:function(s,i,l,c){return s(i,l,c)},yfZbw:"2.0"},a=e._onrequest;e[n(463)]=async(s,i)=>{var l,c,u,d,p;const f=n,h=r,{id:b,method:y}=s;try{o[f(451)](y,o.DhPFX)?await a.call(e,s,i):await o[h(474)](forwardServerRequest,e,t,s)}catch(w){const{code:g,message:m,data:S}=w;try{if(g){const v={};v[h(485)]=g,v[f(422)]=m,v.data=S;const _={};_[h(448)]=v,_.jsonrpc=o[f(417)],_.id=b,await((l=e?.transport)==null?void 0:l[h(460)](_))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(v){(p=(d=e?.transport)==null?void 0:d.onerror)==null||p.call(d,v)}}}},forwardServerOnNotification=(e,t)=>{const r=_0x21a3,n=_0x21a3,o={};o[r(476)]=r(439),o[r(431)]=function(s,i){return s!==i},o.UPdQt="notifications/cancelled";const a=o;e[r(421)]=async s=>{var i,l;const c=r,u=n,{method:d,params:p}=s;if(d!==a[c(476)]&&(a.QWYMz(d,a.UPdQt)||p?.[u(490)]))try{await t[c(445)](s)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},forwardClientOnRequest=(e,t)=>async r=>{var n,o,a,s,i;const l=_0x21a3,c=_0x21a3,u={TJhyV:function(d,p,f,h){return d(p,f,h)},MMNTY:l(465)};try{return await u.TJhyV(forwardClientRequest,e,t,r)}catch(d){const{code:p,message:f,data:h}=d;try{if(p){const b={};b.code=p,b[l(422)]=f,b[c(419)]=h;const y={};y[l(448)]=b,y[l(424)]=u.MMNTY,y.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](y))}else(a=(o=e?.transport)==null?void 0:o[l(480)])==null||a.call(o,d)}catch(b){(i=(s=e?.[l(488)])==null?void 0:s.onerror)==null||i.call(s,b)}}},forwardClientOnNotification=(e,t)=>async r=>{var n,o,a;const s=_0x21a3,i=_0x21a3,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[s(420)]=i(453);const c=l,{method:u,params:d}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||d?.[i(490)]))try{const p={...r};p.jsonrpc=s(465),await((n=t?.[s(488)])==null?void 0:n.send(p))}catch(p){(a=(o=e?.transport)==null?void 0:o.onerror)==null||a.call(o,p)}};function _0x3610(){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 _0x3610=function(){return e},_0x3610()}const forwardClientOnResponse=(e,t)=>async r=>{var n,o,a,s,i,l;const c=_0x21a3,u=_0x21a3,d={};d.kSvAZ=c(465);const p=d;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:h,message:b,data:y}=f;try{if(h){const w={};w.code=h,w.message=b,w.data=y;const g={};g.error=w,g[u(424)]=p.kSvAZ,g.id=r.id,await((o=e?.transport)==null?void 0:o.send(g))}else(s=(a=e?.transport)==null?void 0:a[c(480)])==null||s.call(a,f)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},createHandleListener=()=>{const e=_0x21a3,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=_0x21a3;if(c){const d=[];for(const p of r)try{d.push(p(l,c))}catch{}for(const p of d)if(t.rgPZO(p,null))return p}else for(const d of r)try{t[u(427)](d,l)}catch{}},o=l=>{const c=_0x21a3,u=_0x21a3;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},a=l=>{const c=_0x21a3,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},s=()=>{const l=_0x21a3;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=a,i.clearListener=s,i},setClientListener=e=>{const t=_0x21a3,r=_0x21a3,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:a,removeListener:s,clearListener:i}=n[t(423)](createHandleListener);e._onresponse=o,e[r(438)]=a,e.removeResponseListener=s,e.clearResponseListener=i}{const{handleListener:o,addListener:a,removeListener:s,clearListener:i}=n[t(489)](createHandleListener);e[t(432)]=o,e[r(473)]=a,e.removeRequestListener=s,e.clearRequestListener=i}{const{handleListener:o,addListener:a,removeListener:s,clearListener:i}=n.jsmFN(createHandleListener);e.fallbackNotificationHandler=o,e[t(444)]=a,e.removeNotificationListener=s,e[r(426)]=i}},initClientHandler=(e,{beforeInit:t,afterInit:r}={})=>{const n=_0x21a3,o=_0x21a3,a={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},s=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(setClientListener,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),a[n(429)](typeof r,a.HicFO)&&a[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=s[l(483)](c);a[l(467)](typeof u,"function")&&u(i)})},_0x580c11=_0x3345;(function(e,t){const r=_0x3345,n=_0x3345,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())}})(_0x15b2,995159+-6*-266138+-1619768);const randomUUID$1=()=>{const e=_0x3345,t=_0x3345,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,s=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[a(225)](o,"x")?s:n[a(209)](s,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},randomBytes=e=>{const t=_0x3345,r=_0x3345,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)]("")},_0x5e2e0a={};_0x5e2e0a[_0x580c11(211)]=randomUUID$1,_0x5e2e0a.randomBytes=randomBytes;function _0x3345(e,t){const r=_0x15b2();return _0x3345=function(n,o){return n=n-(-7373+7187*1+395),r[n]},_0x3345(e,t)}function _0x15b2(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return _0x15b2=function(){return e},_0x15b2()}function _0xd139(e,t){const r=_0x3ca7();return _0xd139=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},_0xd139(e,t)}const _0x403f63=_0xd139,_0x165645=_0xd139;(function(e,t){const r=_0xd139,n=_0xd139,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())}})(_0x3ca7,-4*308317+753182*2+658196);const forwardProxyClient=(e,t)=>{const r=_0xd139,n=_0xd139,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)](forwardServerOnRequest,e,t),forwardServerOnNotification(e,t);const a=o[n(283)](forwardClientOnRequest,t,e),s=o[n(294)](forwardClientOnResponse,t,e),i=o[r(277)](forwardClientOnNotification,t,e);t.addRequestListener(a),t.addResponseListener(s),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](a),t.removeResponseListener(s),t[c(252)](i)}},initWebClientHandler=(e,t,r)=>{const n={QhPqi:function(s,i){return s instanceof i},AIICR:"close",Qalmc:function(s,i,l){return s(i,l)}},o=()=>{var s;n.QhPqi(r,SSEClientTransport)&&((s=r._eventSource)==null||s.addEventListener(n.AIICR,()=>{var i;(i=r[_0xd139(295)])==null||i.close()})),n.Qalmc(forwardProxyClient,e,t)},a={};a.afterInit=o,n.Qalmc(initClientHandler,t,a)},sseOptions=(e,t=_0x5e2e0a[_0x403f63(299)]())=>{const r=_0x403f63,n=_0x403f63,o={RVabx:function(u,d,p){return u(d,p)},crCTs:"include"},a={};a["sse-session-id"]=t;const s=a,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,d){const p=r,f=r,h=new Headers(d?.[p(268)]||{});Object.entries(s).forEach(([y,w])=>{h.set(y,w)});const b={...d};return b.headers=h,o[f(279)](fetch,u,b)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,s.Authorization=n(256)+e),c},streamOptions=(e,t=_0x5e2e0a[_0x403f63(299)]())=>{const r=_0x165645,n=_0x403f63,o={};o[r(271)]="include";const a=o,s={};s["stream-session-id"]=t;const i={};i[n(268)]=s,i.credentials=a[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},attemptConnection=async(e,t,r)=>{const n=_0x403f63,o=_0x403f63,a={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},s=a[n(276)](r);try{return await e[o(260)](s),s}catch(i){if(a[n(275)](i,UnauthorizedError$1)){const l=await t();return await s[n(257)](l),await attemptConnection(e,t,r)}else throw i}},getWaitForOAuthCodeFunction=(e,t)=>{const r=_0x165645,n=_0x165645,o={};o[r(267)]=function(s,i){return s in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(s,i){return s===i},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 _0x3ca7(){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 _0x3ca7=function(){return e},_0x3ca7()}const createSseProxy=async e=>{const t=_0x165645,r=_0x403f63,n={GKDjq:function(R,x,E){return R(x,E)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(R){return R()},kdowC:function(R,x,E,A){return R(x,E,A)},KkViY:"sessionId"},{client:o,url:a,token:s,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:d}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,h=i||_0x5e2e0a[r(299)](),b=n[t(289)](sseOptions,s,h);if(c){const R={...b.requestInit,...c};R[r(268)]={...b[r(280)][t(268)],...c.headers},f.requestInit=R}else f.requestInit=b[t(280)];if(u){const R={...b[t(270)],...u};f.eventSourceInit=R}else f.eventSourceInit=b[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const g=w,m={};m.name=n[r(261)],m[t(288)]=n.mcbiU;const S={};S[t(251)]=g;const v=new Client(m,S),_=()=>new SSEClientTransport(new URL(a),f);let $=n[t(282)](_);if(l){const R=getWaitForOAuthCodeFunction(l,d);$=await n[t(263)](attemptConnection,v,R,_)}else await v.connect($);initWebClientHandler(v,o,$),$.sessionId=$[r(274)].searchParams[t(297)](n.KkViY);const T={};return T.transport=$,T.sessionId=$[r(286)],T},createStreamProxy=async e=>{const t=_0x165645,r=_0x403f63,n={wfHUn:function(R,x,E){return R(x,E)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(R){return R()},PdsSn:function(R,x,E,A){return R(x,E,A)}},{client:o,url:a,token:s,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:d}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,h=i||_0x5e2e0a.randomUUID(),b=n[r(272)](streamOptions,s,h);if(c){const R={...b[t(280)],...c};R.headers={...b.requestInit[t(268)],...c.headers},f.requestInit=R}else f[r(280)]=b[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const g=w,m={};m.name=n[t(262)],m.version=n.omKPe;const S={};S.capabilities=g;const v=new Client(m,S),_=()=>new StreamableHTTPClientTransport(new URL(a),f);let $=n.rSiEq(_);if(l){const R=n[t(272)](getWaitForOAuthCodeFunction,l,d);$=await n[t(296)](attemptConnection,v,R,_)}else await v[t(260)]($);n.PdsSn(initWebClientHandler,v,o,$);const T={};return T.transport=$,T[r(286)]=$[r(286)],T},createSocketProxy=async e=>{const t=_0x403f63,r=_0x403f63,n={eZwNI:function(w,g,m,S){return w(g,m,S)}},{client:o,url:a,token:s,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,d={};d.name="mcp-socket-proxy-client",d.version=r(248);const p={};p[r(251)]=u;const f=new Client(d,p),h=i||_0x5e2e0a[r(299)](),b=new WebSocketClientTransport(new URL(a+"?sessionId="+h+r(265)+s));await f.connect(b),n[t(259)](initWebClientHandler,f,o,b);const y={};return y.transport=b,y[r(286)]=h,y},_0x5d6a74=_0x155f,_0x2395ea=_0x155f;(function(e,t){const r=_0x155f,n=_0x155f,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())}})(_0x3878,1297719+-42747*-22+-1289197);function _0x155f(e,t){const r=_0x3878();return _0x155f=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},_0x155f(e,t)}const generateStateFunction=()=>_0x5e2e0a.randomBytes(-8746+-382*-23);class AuthClientProvider{constructor(t){const r=_0x155f,n=_0x155f,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:a,state:s,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=a,this[r(206)]=a.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=s||o.HbwOh(generateStateFunction),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,a,s,i;const l=_0x155f,c=_0x155f,u={};u[l(198)]="GET";const d=await fetch(t,u);!d.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+d[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 f=await p.json();(i=(s=this._callBackPromise).resolve)==null||i.call(s,f.code)}async[_0x5d6a74(191)](t,r){const n=_0x5d6a74,o={};o.xAOmI="POST";const a=o,s={};s["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:a.xAOmI,headers:s,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=_0x155f;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[_0x5d6a74(206)]}get[_0x2395ea(190)](){return this._clientMetadata}[_0x5d6a74(213)](){return this[_0x5d6a74(197)]}[_0x2395ea(218)](){return this[_0x2395ea(200)]}[_0x5d6a74(194)](t){this._clientInformation=t}tokens(){return this[_0x2395ea(210)]}saveTokens(t){const r=_0x2395ea;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[_0x5d6a74(212)](){const t=_0x5d6a74,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function _0x3878(){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 _0x3878=function(){return e},_0x3878()}(function(e,t){for(var r=_0x275e,n=_0x275e,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())}})(_0x204d,262*-2438+1346066*-1+2*1373311);function _0x204d(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return _0x204d=function(){return e},_0x204d()}function _0x275e(e,t){var r=_0x204d();return _0x275e=function(n,o){n=n-287;var a=r[n];return a},_0x275e(e,t)}class ExperimentalServerTasks{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}class Server extends Protocol{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{const a=this._loggingLevels.get(o);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,n=>this._oninitialize(n)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(n,o)=>{const a=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,i=LoggingLevelSchema.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,t)}setRequestHandler(t,r){const o=getObjectShape(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let a;if(isZ4Schema(o)){const i=o;a=i._zod?.def?.value??i.value}else{const i=o;a=i._def?.value??i.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){const i=async(l,c)=>{const u=safeParse(CallToolRequestSchema,l);if(!u.success){const h=u.error instanceof Error?u.error.message:String(u.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${h}`)}const{params:d}=u.data,p=await Promise.resolve(r(l,c));if(d.task){const h=safeParse(CreateTaskResultSchema,p);if(!h.success){const b=h.error instanceof Error?h.error.message:String(h.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}const f=safeParse(CallToolResultSchema$1,p);if(!f.success){const h=f.error instanceof Error?f.error.message:String(f.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){const r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS$1.includes(r)?r:LATEST_PROTOCOL_VERSION$1,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){const n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],a=o.some(c=>c.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],l=i.some(c=>c.type==="tool_use");if(a){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const c=new Set(i.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==u.size||![...c].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},CreateMessageResultWithToolsSchema,r):this.request({method:"sampling/createMessage",params:t},CreateMessageResultSchema,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const o=t;return this.request({method:"elicitation/create",params:o},ElicitResultSchema$1,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const o=t.mode==="form"?t:{...t,mode:"form"},a=await this.request({method:"elicitation/create",params:o},ElicitResultSchema$1,r);if(a.action==="accept"&&a.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(a.content);if(!i.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){throw s instanceof McpError?s:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return a}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},ListRootsResultSchema,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function completable(e,t){return Object.defineProperty(e,COMPLETABLE_SYMBOL,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function isCompletable(e){return!!e&&typeof e=="object"&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));const MAX_TEMPLATE_LENGTH=1e6,MAX_VARIABLE_LENGTH=1e6,MAX_TEMPLATE_EXPRESSIONS=1e4,MAX_REGEX_LENGTH=1e6;class UriTemplate{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){UriTemplate.validateLength(t,MAX_TEMPLATE_LENGTH,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){const r=[];let n="",o=0,a=0;for(;o<t.length;)if(t[o]==="{"){n&&(r.push(n),n="");const s=t.indexOf("}",o);if(s===-1)throw new Error("Unclosed template expression");if(a++,a>MAX_TEMPLATE_EXPRESSIONS)throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);const i=t.slice(o+1,s),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),d=u[0];for(const p of u)UriTemplate.validateLength(p,MAX_VARIABLE_LENGTH,"Variable name");r.push({name:d,operator:l,names:u,exploded:c}),o=s+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(n=>t.startsWith(n))||""}getNames(t){const r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return UriTemplate.validateLength(t,MAX_VARIABLE_LENGTH,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){const s=t.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(d=>this.encodeValue(d,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${l}=${u}`}).filter(l=>l.length>0);return s.length===0?"":(t.operator==="?"?"?":"&")+s.join("&")}if(t.names.length>1){const s=t.names.map(i=>r[i]).filter(i=>i!==void 0);return s.length===0?"":s.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[t.name];if(n===void 0)return"";const a=(Array.isArray(n)?n:[n]).map(s=>this.encodeValue(s,t.operator));switch(t.operator){case"":return a.join(",");case"+":return a.join(",");case"#":return"#"+a.join(",");case".":return"."+a.join(".");case"/":return"/"+a.join("/");default:return a.join(",")}}expand(t){let r="",n=!1;for(const o of this.parts){if(typeof o=="string"){r+=o;continue}const a=this.expandPart(o,t);a&&((o.operator==="?"||o.operator==="&")&&n?r+=a.replace("?","&"):r+=a,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){const r=[];for(const a of t.names)UriTemplate.validateLength(a,MAX_VARIABLE_LENGTH,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let a=0;a<t.names.length;a++){const s=t.names[a],i=a===0?"\\"+t.operator:"&";r.push({pattern:i+this.escapeRegExp(s)+"=([^&]+)",name:s})}return r}let n;const o=t.name;switch(t.operator){case"":n=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(t){UriTemplate.validateLength(t,MAX_TEMPLATE_LENGTH,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)r+=c,n.push({name:u,exploded:i.exploded})}r+="$",UriTemplate.validateLength(r,MAX_REGEX_LENGTH,"Generated regex pattern");const o=new RegExp(r),a=t.match(o);if(!a)return null;const s={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=a[i+1],d=l.replace("*","");c&&u.includes(",")?s[d]=u.split(","):s[d]=u}return s}}const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(e)){const r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,a)=>a.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(e){const t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}class ExperimentalMcpServerTasks{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){const o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}class McpServer{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalMcpServerTasks(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{const n={name:t,title:r.title,description:r.description,inputSchema:(()=>{const o=normalizeObjectSchema(r.inputSchema);return o?toJsonSchemaCompat(o,{strictUnions:!0,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=normalizeObjectSchema(r.outputSchema);o&&(n.outputSchema=toJsonSchemaCompat(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(CallToolRequestSchema,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new McpError(ErrorCode.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,a=n.execution?.taskSupport,s="createTask"in n.handler;if((a==="required"||a==="optional")&&!s)throw new McpError(ErrorCode.InternalError,`Tool ${t.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new McpError(ErrorCode.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof McpError&&n.code===ErrorCode.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const a=normalizeObjectSchema(t.inputSchema)??t.inputSchema,s=await safeParseAsync(a,r);if(!s.success){const i="error"in s?s.error:"Unknown error",l=getParseErrorMessage(i);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=normalizeObjectSchema(t.outputSchema),a=await safeParseAsync(o,r.structuredContent);if(!a.success){const s="error"in a?a.error:"Unknown error",i=getParseErrorMessage(s);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const s={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,s))}else{const i=o;return await Promise.resolve(i.createTask(s))}}if(t.inputSchema){const s=o;return await Promise.resolve(s(r,n))}else{const s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),a=t.handler,s={...n,taskStore:n.taskStore},i=o?await Promise.resolve(a.createTask(o,s)):await Promise.resolve(a.createTask(s)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const d=await n.taskStore.getTask(l);if(!d)throw new McpError(ErrorCode.InternalError,`Task ${l} not found during polling`);c=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async t=>{switch(t.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(t),this.handleResourceCompletion(t,t.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new McpError(ErrorCode.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return EMPTY_COMPLETION_RESULT;const a=getObjectShape(n.argsSchema)?.[t.params.argument.name];if(!isCompletable(a))return EMPTY_COMPLETION_RESULT;const s=getCompleter(a);if(!s)return EMPTY_COMPLETION_RESULT;const i=await s(t.params.argument.value,t.params.context);return createCompletionResult(i)}async handleResourceCompletion(t,r){const n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return EMPTY_COMPLETION_RESULT;const a=await o(t.params.argument.value,t.params.context);return createCompletionResult(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(t,r)=>{const n=Object.entries(this._registeredResources).filter(([a,s])=>s.enabled).map(([a,s])=>({uri:a,name:s.name,...s.metadata})),o=[];for(const a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;const s=await a.resourceTemplate.listCallback(r);for(const i of s.resources)o.push({...a.metadata,...i})}return{resources:[...n,...o]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const a of Object.values(this._registeredResourceTemplates)){const s=a.resourceTemplate.uriTemplate.match(n.toString());if(s)return a.readCallback(n,s,r)}throw new McpError(ErrorCode.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?promptArgumentsFromSchema(r.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=normalizeObjectSchema(n.argsSchema),a=await safeParseAsync(o,t.params.arguments);if(!a.success){const l="error"in a?a.error:"Unknown error",c=getParseErrorMessage(l);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const s=a.data,i=n.callback;return await Promise.resolve(i(s,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const a=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,void 0,r,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,void 0,r,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(t,r,n,o,a){const s={name:t,title:r,metadata:o,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=s)),typeof i.name<"u"&&(s.name=i.name),typeof i.title<"u"&&(s.title=i.title),typeof i.metadata<"u"&&(s.metadata=i.metadata),typeof i.callback<"u"&&(s.readCallback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,a){const s={resourceTemplate:n,title:r,metadata:o,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=s)),typeof c.title<"u"&&(s.title=c.title),typeof c.template<"u"&&(s.resourceTemplate=c.template),typeof c.metadata<"u"&&(s.metadata=c.metadata),typeof c.callback<"u"&&(s.readCallback=c.callback),typeof c.enabled<"u"&&(s.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,a){const s={title:r,description:n,argsSchema:o===void 0?void 0:objectFromShape(o),callback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==t&&(delete this._registeredPrompts[t],i.name&&(this._registeredPrompts[i.name]=s)),typeof i.title<"u"&&(s.title=i.title),typeof i.description<"u"&&(s.description=i.description),typeof i.argsSchema<"u"&&(s.argsSchema=objectFromShape(i.argsSchema)),typeof i.callback<"u"&&(s.callback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(l=>{const c=l instanceof ZodOptional$1?l._def?.innerType:l;return isCompletable(c)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,a,s,i,l,c){validateAndWarnToolName(t);const u={title:r,description:n,inputSchema:getZodSchemaObject(o),outputSchema:getZodSchemaObject(a),annotations:s,execution:i,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&validateAndWarnToolName(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=objectFromShape(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=objectFromShape(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,a,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];isZodRawShapeCompat(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!isZodRawShapeCompat(r[0])&&(s=r.shift())):typeof l=="object"&&l!==null&&(s=r.shift())}const i=r[0];return this._createRegisteredTool(t,void 0,n,o,a,s,{taskSupport:"forbidden"},void 0,i)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);const{title:o,description:a,inputSchema:s,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,a,s,i,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());const a=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);const{title:o,description:a,argsSchema:s}=r,i=this._createRegisteredPrompt(t,o,a,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class ResourceTemplate{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new UriTemplate(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function isZodSchemaInstance(e){return"_def"in e||"_zod"in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!="object"||e===null||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e)return isZodRawShapeCompat(e)?objectFromShape(e):e}function promptArgumentsFromSchema(e){const t=getObjectShape(e);return t?Object.entries(t).map(([r,n])=>{const o=getSchemaDescription(n),a=isSchemaOptional(n);return{name:r,description:o,required:!a}}):[]}function getMethodValue(e){const r=getObjectShape(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=getLiteralValue(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};function getDisplayName(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class InMemoryTransport{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new InMemoryTransport,r=new InMemoryTransport;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}})}}class WebMcpServer{constructor(t,r){const n={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new McpServer(t||n,r||{capabilities:o}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=a=>{this.onerror?.(a)},this.server.server.setRequestHandler(SetLevelRequestSchema,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new MessageChannelServerTransport(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,r,n){return this.server.registerTool(t,r,n)}registerPrompt(t,r,n){return this.server.registerPrompt(t,r,n)}registerResource(t,r,n,o){return typeof r=="string"?this.server.registerResource(t,r,n,o):this.server.registerResource(t,r,n,o)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(t,r){return await this.server.server.createMessage(t,r)}async elicitInput(t,r){return await this.server.server.elicitInput(t,r)}async listRoots(t,r){return await this.server.server.listRoots(t,r)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,r,n){return this.server.server.request(t,r,n)}async notification(t,r){return await this.server.server.notification(t,r)}setRequestHandler(t,r){this.server.server.setRequestHandler(t,r)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,r){this.server.server.setNotificationHandler(t,r)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(SubscribeRequestSchema,t)}onUnsubscribe(t){this.server.server.setRequestHandler(UnsubscribeRequestSchema,t)}onSetLogLevel(t){this.server.server.setRequestHandler(SetLevelRequestSchema,t)}onListResources(t){this.server.server.setRequestHandler(ListResourcesRequestSchema,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(RootsListChangedNotificationSchema,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const createMessageChannelServerTransport=(e,t)=>new MessageChannelServerTransport(e,t),createMessageChannelPairTransport=()=>createTransportPair(),isMessageChannelServerTransport=e=>e instanceof MessageChannelServerTransport,isMcpServer=e=>e instanceof McpServer,setupBuiltinProxy=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 i=(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:i}})}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:s,arguments:i}=r.params,l=await a.executeTool(s,JSON.stringify(i||{})),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 s=new Error("executeTool not implemented in Browser built-in WebMCP");throw s.code=-32601,s}}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 WebMcpClient{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Client(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:s,builtin:i,onError:l}=t;if(s){const d={client:this.client,url:r,token:n,sessionId:o},p=a==="sse"?await createSseProxy(d):a==="socket"?await createSocketProxy(d):await createStreamProxy(d);return p.transport.onerror=async f=>{l?.(f)},i&&setupBuiltinProxy(p.transport),p}const c=new URL(r);let u;if(a==="channel"&&(u=new MessageChannelClientTransport(r),await this.client.connect(u)),a==="sse"){const d=sseOptions(n,o);u=new SSEClientTransport(c,d),await this.client.connect(u)}if(a==="socket"&&(u=new WebSocketClientTransport(new URL(`${r}?sessionId=${o}&token=${n}`)),u.sessionId=o,await this.client.connect(u)),a==="stream"||typeof u>"u"){const d=streamOptions(n,o);u=new StreamableHTTPClientTransport(c,d),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,CallToolResultSchema$1,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(ElicitRequestSchema,t)}onCreateMessage(t){this.client.setRequestHandler(CreateMessageRequestSchema,t)}onListRoots(t){this.client.setRequestHandler(ListRootsRequestSchema,t)}onToolListChanged(t){this.client.setNotificationHandler(ToolListChangedNotificationSchema,t)}onPromptListChanged(t){this.client.setNotificationHandler(PromptListChangedNotificationSchema,t)}onResourceListChanged(t){this.client.setNotificationHandler(ResourceListChangedNotificationSchema,t)}onResourceUpdated(t){this.client.setNotificationHandler(ResourceUpdatedNotificationSchema,t)}onLoggingMessage(t){this.client.setNotificationHandler(LoggingMessageNotificationSchema,t)}async onPagehide(t){t.persisted||(isStreamableHTTPClientTransport(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const createSSEClientTransport=(e,t)=>new SSEClientTransport(e,t),createStreamableHTTPClientTransport=(e,t)=>new StreamableHTTPClientTransport(e,t),createMessageChannelClientTransport=(e,t)=>new MessageChannelClientTransport(e,t),isSSEClientTransport=e=>e instanceof SSEClientTransport,isStreamableHTTPClientTransport=e=>e instanceof StreamableHTTPClientTransport,isMessageChannelClientTransport=e=>e instanceof MessageChannelClientTransport,isMcpClient=e=>e instanceof Client,sendWindowMessage=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},onWindowMessage=(e,t,r)=>{const n=async function(o){o.source===window&&o.data.type===e&&o.data.direction===r&&await t(o.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},sendRuntimeMessage=(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})},onRuntimeMessage=(e,t,r,n)=>{const o=(a,s,i)=>{if(a.type===e&&a.direction===r&&(!n||n&&a.tabId===n)){const{data:l}=a;t(l,s,i),i(s)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class ExtensionClientTransport{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=onRuntimeMessage("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=JSONRPCMessageSchema$1.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}`),sendRuntimeMessage("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】 关闭时发生错误")}}}const randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});class ExtensionPageServerTransport{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||randomUUID(),this._messageListener2=onWindowMessage("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=JSONRPCMessageSchema$1.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&sendWindowMessage("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),sendWindowMessage("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&sendWindowMessage("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{sendWindowMessage("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}class ContentScriptServerTransport{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||randomUUID(),this.tabId=r}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");onRuntimeMessage("mcp-client-to-server",t=>{if(!(t.sessionId!==this.sessionId||t.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",t.mcpMessage);const r=JSONRPCMessageSchema$1.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&sendWindowMessage("update-page-app-message",{status:"run",message:t.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"bg->content",this.tabId),this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",t),sendRuntimeMessage("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->bg"),"result"in t&&t.result?.content&&sendWindowMessage("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(t){this._isStarted&&(this._lastRegistration=t,sendRuntimeMessage("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"content->bg"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(t))}}}var browser={},canPromise,hasRequiredCanPromise;function requireCanPromise(){return hasRequiredCanPromise||(hasRequiredCanPromise=1,canPromise=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),canPromise}var qrcode={},utils$1={},hasRequiredUtils$1;function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;hasRequiredUtils$1=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 utils$1.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},utils$1.getSymbolTotalCodewords=function(n){return t[n]},utils$1.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},utils$1.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},utils$1.isKanjiModeEnabled=function(){return typeof e<"u"},utils$1.toSJIS=function(n){return e(n)},utils$1}var errorCorrectionLevel={},hasRequiredErrorCorrectionLevel;function requireErrorCorrectionLevel(){return hasRequiredErrorCorrectionLevel||(hasRequiredErrorCorrectionLevel=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}}})(errorCorrectionLevel)),errorCorrectionLevel}var bitBuffer,hasRequiredBitBuffer;function requireBitBuffer(){if(hasRequiredBitBuffer)return bitBuffer;hasRequiredBitBuffer=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++}},bitBuffer=e,bitBuffer}var bitMatrix,hasRequiredBitMatrix;function requireBitMatrix(){if(hasRequiredBitMatrix)return bitMatrix;hasRequiredBitMatrix=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]},bitMatrix=e,bitMatrix}var alignmentPattern={},hasRequiredAlignmentPattern;function requireAlignmentPattern(){return hasRequiredAlignmentPattern||(hasRequiredAlignmentPattern=1,(function(e){const t=requireUtils$1().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,a=t(n),s=a===145?26:Math.ceil((a-13)/(2*o-2))*2,i=[a-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-s;return i.push(6),i.reverse()},e.getPositions=function(n){const o=[],a=e.getRowColCoords(n),s=a.length;for(let i=0;i<s;i++)for(let l=0;l<s;l++)i===0&&l===0||i===0&&l===s-1||i===s-1&&l===0||o.push([a[i],a[l]]);return o}})(alignmentPattern)),alignmentPattern}var finderPattern={},hasRequiredFinderPattern;function requireFinderPattern(){if(hasRequiredFinderPattern)return finderPattern;hasRequiredFinderPattern=1;const e=requireUtils$1().getSymbolSize,t=7;return finderPattern.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},finderPattern}var maskPattern={},hasRequiredMaskPattern;function requireMaskPattern(){return hasRequiredMaskPattern||(hasRequiredMaskPattern=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 s=0,i=0,l=0,c=null,u=null;for(let d=0;d<a;d++){i=l=0,c=u=null;for(let p=0;p<a;p++){let f=o.get(d,p);f===c?i++:(i>=5&&(s+=t.N1+(i-5)),c=f,i=1),f=o.get(p,d),f===u?l++:(l>=5&&(s+=t.N1+(l-5)),u=f,l=1)}i>=5&&(s+=t.N1+(i-5)),l>=5&&(s+=t.N1+(l-5))}return s},e.getPenaltyN2=function(o){const a=o.size;let s=0;for(let i=0;i<a-1;i++)for(let l=0;l<a-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&s++}return s*t.N2},e.getPenaltyN3=function(o){const a=o.size;let s=0,i=0,l=0;for(let c=0;c<a;c++){i=l=0;for(let u=0;u<a;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&s++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&s++}return s*t.N3},e.getPenaltyN4=function(o){let a=0;const s=o.data.length;for(let l=0;l<s;l++)a+=o.data[l];return Math.abs(Math.ceil(a*100/s/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 s=a.size;for(let i=0;i<s;i++)for(let l=0;l<s;l++)a.isReserved(l,i)||a.xor(l,i,r(o,l,i))},e.getBestMask=function(o,a){const s=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<s;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,i=c)}return i}})(maskPattern)),maskPattern}var errorCorrectionCode={},hasRequiredErrorCorrectionCode;function requireErrorCorrectionCode(){if(hasRequiredErrorCorrectionCode)return errorCorrectionCode;hasRequiredErrorCorrectionCode=1;const e=requireErrorCorrectionLevel(),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 errorCorrectionCode.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}},errorCorrectionCode.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}},errorCorrectionCode}var polynomial={},galoisField={},hasRequiredGaloisField;function requireGaloisField(){if(hasRequiredGaloisField)return galoisField;hasRequiredGaloisField=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]})(),galoisField.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},galoisField.exp=function(n){return e[n]},galoisField.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},galoisField}var hasRequiredPolynomial;function requirePolynomial(){return hasRequiredPolynomial||(hasRequiredPolynomial=1,(function(e){const t=requireGaloisField();e.mul=function(n,o){const a=new Uint8Array(n.length+o.length-1);for(let s=0;s<n.length;s++)for(let i=0;i<o.length;i++)a[s+i]^=t.mul(n[s],o[i]);return a},e.mod=function(n,o){let a=new Uint8Array(n);for(;a.length-o.length>=0;){const s=a[0];for(let l=0;l<o.length;l++)a[l]^=t.mul(o[l],s);let i=0;for(;i<a.length&&a[i]===0;)i++;a=a.slice(i)}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}})(polynomial)),polynomial}var reedSolomonEncoder,hasRequiredReedSolomonEncoder;function requireReedSolomonEncoder(){if(hasRequiredReedSolomonEncoder)return reedSolomonEncoder;hasRequiredReedSolomonEncoder=1;const e=requirePolynomial();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),s=this.degree-a.length;if(s>0){const i=new Uint8Array(this.degree);return i.set(a,s),i}return a},reedSolomonEncoder=t,reedSolomonEncoder}var version={},mode={},versionCheck={},hasRequiredVersionCheck;function requireVersionCheck(){return hasRequiredVersionCheck||(hasRequiredVersionCheck=1,versionCheck.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),versionCheck}var regex$1={},hasRequiredRegex;function requireRegex(){if(hasRequiredRegex)return regex$1;hasRequiredRegex=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
|
|
49
|
-
]))+`;regex$1.KANJI=new RegExp(r,"g"),regex$1.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),regex$1.BYTE=new RegExp(n,"g"),regex$1.NUMERIC=new RegExp(e,"g"),regex$1.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),a=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return regex$1.testKanji=function(l){return o.test(l)},regex$1.testNumeric=function(l){return a.test(l)},regex$1.testAlphanumeric=function(l){return s.test(l)},regex$1}var hasRequiredMode;function requireMode(){return hasRequiredMode||(hasRequiredMode=1,(function(e){const t=requireVersionCheck(),r=requireRegex();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,s){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?a.ccBits[0]:s<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,s){if(e.isValid(a))return a;try{return n(a)}catch{return s}}})(mode)),mode}var hasRequiredVersion;function requireVersion(){return hasRequiredVersion||(hasRequiredVersion=1,(function(e){const t=requireUtils$1(),r=requireErrorCorrectionCode(),n=requireErrorCorrectionLevel(),o=requireMode(),a=requireVersionCheck(),s=7973,i=t.getBCHDigit(s);function l(p,f,h){for(let b=1;b<=40;b++)if(f<=e.getCapacity(b,h,p))return b}function c(p,f){return o.getCharCountIndicator(p,f)+4}function u(p,f){let h=0;return p.forEach(function(b){const y=c(b.mode,f);h+=y+b.getBitsLength()}),h}function d(p,f){for(let h=1;h<=40;h++)if(u(p,h)<=e.getCapacity(h,f,o.MIXED))return h}e.from=function(f,h){return a.isValid(f)?parseInt(f,10):h},e.getCapacity=function(f,h,b){if(!a.isValid(f))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=o.BYTE);const y=t.getSymbolTotalCodewords(f),w=r.getTotalCodewordsCount(f,h),g=(y-w)*8;if(b===o.MIXED)return g;const m=g-c(b,f);switch(b){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},e.getBestVersionForData=function(f,h){let b;const y=n.from(h,n.M);if(Array.isArray(f)){if(f.length>1)return d(f,y);if(f.length===0)return 1;b=f[0]}else b=f;return l(b.mode,b.getLength(),y)},e.getEncodedBits=function(f){if(!a.isValid(f)||f<7)throw new Error("Invalid QR Code version");let h=f<<12;for(;t.getBCHDigit(h)-i>=0;)h^=s<<t.getBCHDigit(h)-i;return f<<12|h}})(version)),version}var formatInfo={},hasRequiredFormatInfo;function requireFormatInfo(){if(hasRequiredFormatInfo)return formatInfo;hasRequiredFormatInfo=1;const e=requireUtils$1(),t=1335,r=21522,n=e.getBCHDigit(t);return formatInfo.getEncodedBits=function(a,s){const i=a.bit<<3|s;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},formatInfo}var segments={},numericData,hasRequiredNumericData;function requireNumericData(){if(hasRequiredNumericData)return numericData;hasRequiredNumericData=1;const e=requireMode();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,s;for(o=0;o+3<=this.data.length;o+=3)a=this.data.substr(o,3),s=parseInt(a,10),n.put(s,10);const i=this.data.length-o;i>0&&(a=this.data.substr(o),s=parseInt(a,10),n.put(s,i*3+1))},numericData=t,numericData}var alphanumericData,hasRequiredAlphanumericData;function requireAlphanumericData(){if(hasRequiredAlphanumericData)return alphanumericData;hasRequiredAlphanumericData=1;const e=requireMode(),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 s=t.indexOf(this.data[a])*45;s+=t.indexOf(this.data[a+1]),o.put(s,11)}this.data.length%2&&o.put(t.indexOf(this.data[a]),6)},alphanumericData=r,alphanumericData}var byteData,hasRequiredByteData;function requireByteData(){if(hasRequiredByteData)return byteData;hasRequiredByteData=1;const e=requireMode();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)},byteData=t,byteData}var kanjiData,hasRequiredKanjiData;function requireKanjiData(){if(hasRequiredKanjiData)return kanjiData;hasRequiredKanjiData=1;const e=requireMode(),t=requireUtils$1();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]+`
|
|
50
|
-
Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),n.put(a,13)}},kanjiData=r,kanjiData}var dijkstra={exports:{}},hasRequiredDijkstra;function requireDijkstra(){return hasRequiredDijkstra||(hasRequiredDijkstra=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var a={},s={};s[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,d,p,f,h,b,y;!i.empty();){l=i.pop(),c=l.value,d=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],h=d+f,b=s[u],y=typeof s[u]>"u",(y||b>h)&&(s[u]=h,i.push(u,h),a[u]=c))}if(typeof o<"u"&&typeof s[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}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})(dijkstra)),dijkstra.exports}var hasRequiredSegments;function requireSegments(){return hasRequiredSegments||(hasRequiredSegments=1,(function(e){const t=requireMode(),r=requireNumericData(),n=requireAlphanumericData(),o=requireByteData(),a=requireKanjiData(),s=requireRegex(),i=requireUtils$1(),l=requireDijkstra();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,g,m){const S=[];let v;for(;(v=w.exec(m))!==null;)S.push({data:v[0],index:v.index,mode:g,length:v[0].length});return S}function d(w){const g=u(s.NUMERIC,t.NUMERIC,w),m=u(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let S,v;return i.isKanjiModeEnabled()?(S=u(s.BYTE,t.BYTE,w),v=u(s.KANJI,t.KANJI,w)):(S=u(s.BYTE_KANJI,t.BYTE,w),v=[]),g.concat(m,S,v).sort(function($,T){return $.index-T.index}).map(function($){return{data:$.data,mode:$.mode,length:$.length}})}function p(w,g){switch(g){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return a.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function f(w){return w.reduce(function(g,m){const S=g.length-1>=0?g[g.length-1]:null;return S&&S.mode===m.mode?(g[g.length-1].data+=m.data,g):(g.push(m),g)},[])}function h(w){const g=[];for(let m=0;m<w.length;m++){const S=w[m];switch(S.mode){case t.NUMERIC:g.push([S,{data:S.data,mode:t.ALPHANUMERIC,length:S.length},{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.ALPHANUMERIC:g.push([S,{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.KANJI:g.push([S,{data:S.data,mode:t.BYTE,length:c(S.data)}]);break;case t.BYTE:g.push([{data:S.data,mode:t.BYTE,length:c(S.data)}])}}return g}function b(w,g){const m={},S={start:{}};let v=["start"];for(let _=0;_<w.length;_++){const $=w[_],T=[];for(let R=0;R<$.length;R++){const x=$[R],E=""+_+R;T.push(E),m[E]={node:x,lastCount:0},S[E]={};for(let A=0;A<v.length;A++){const D=v[A];m[D]&&m[D].node.mode===x.mode?(S[D][E]=p(m[D].lastCount+x.length,x.mode)-p(m[D].lastCount,x.mode),m[D].lastCount+=x.length):(m[D]&&(m[D].lastCount=x.length),S[D][E]=p(x.length,x.mode)+4+t.getCharCountIndicator(x.mode,g))}}v=T}for(let _=0;_<v.length;_++)S[v[_]].end=0;return{map:S,table:m}}function y(w,g){let m;const S=t.getBestModeForData(w);if(m=t.from(g,S),m!==t.BYTE&&m.bit<S.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
|
|
51
|
-
Suggested mode is: `+t.toString(S));switch(m===t.KANJI&&!i.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new a(w);case t.BYTE:return new o(w)}}e.fromArray=function(g){return g.reduce(function(m,S){return typeof S=="string"?m.push(y(S,null)):S.data&&m.push(y(S.data,S.mode)),m},[])},e.fromString=function(g,m){const S=d(g,i.isKanjiModeEnabled()),v=h(S),_=b(v,m),$=l.find_path(_.map,"start","end"),T=[];for(let R=1;R<$.length-1;R++)T.push(_.table[$[R]].node);return e.fromArray(f(T))},e.rawSplit=function(g){return e.fromArray(d(g,i.isKanjiModeEnabled()))}})(segments)),segments}var hasRequiredQrcode;function requireQrcode(){if(hasRequiredQrcode)return qrcode;hasRequiredQrcode=1;const e=requireUtils$1(),t=requireErrorCorrectionLevel(),r=requireBitBuffer(),n=requireBitMatrix(),o=requireAlignmentPattern(),a=requireFinderPattern(),s=requireMaskPattern(),i=requireErrorCorrectionCode(),l=requireReedSolomonEncoder(),c=requireVersion(),u=requireFormatInfo(),d=requireMode(),p=requireSegments();function f(_,$){const T=_.size,R=a.getPositions($);for(let x=0;x<R.length;x++){const E=R[x][0],A=R[x][1];for(let D=-1;D<=7;D++)if(!(E+D<=-1||T<=E+D))for(let U=-1;U<=7;U++)A+U<=-1||T<=A+U||(D>=0&&D<=6&&(U===0||U===6)||U>=0&&U<=6&&(D===0||D===6)||D>=2&&D<=4&&U>=2&&U<=4?_.set(E+D,A+U,!0,!0):_.set(E+D,A+U,!1,!0))}}function h(_){const $=_.size;for(let T=8;T<$-8;T++){const R=T%2===0;_.set(T,6,R,!0),_.set(6,T,R,!0)}}function b(_,$){const T=o.getPositions($);for(let R=0;R<T.length;R++){const x=T[R][0],E=T[R][1];for(let A=-2;A<=2;A++)for(let D=-2;D<=2;D++)A===-2||A===2||D===-2||D===2||A===0&&D===0?_.set(x+A,E+D,!0,!0):_.set(x+A,E+D,!1,!0)}}function y(_,$){const T=_.size,R=c.getEncodedBits($);let x,E,A;for(let D=0;D<18;D++)x=Math.floor(D/3),E=D%3+T-8-3,A=(R>>D&1)===1,_.set(x,E,A,!0),_.set(E,x,A,!0)}function w(_,$,T){const R=_.size,x=u.getEncodedBits($,T);let E,A;for(E=0;E<15;E++)A=(x>>E&1)===1,E<6?_.set(E,8,A,!0):E<8?_.set(E+1,8,A,!0):_.set(R-15+E,8,A,!0),E<8?_.set(8,R-E-1,A,!0):E<9?_.set(8,15-E-1+1,A,!0):_.set(8,15-E-1,A,!0);_.set(R-8,8,1,!0)}function g(_,$){const T=_.size;let R=-1,x=T-1,E=7,A=0;for(let D=T-1;D>0;D-=2)for(D===6&&D--;;){for(let U=0;U<2;U++)if(!_.isReserved(x,D-U)){let K=!1;A<$.length&&(K=($[A]>>>E&1)===1),_.set(x,D-U,K),E--,E===-1&&(A++,E=7)}if(x+=R,x<0||T<=x){x-=R,R=-R;break}}}function m(_,$,T){const R=new r;T.forEach(function(U){R.put(U.mode.bit,4),R.put(U.getLength(),d.getCharCountIndicator(U.mode,_)),U.write(R)});const x=e.getSymbolTotalCodewords(_),E=i.getTotalCodewordsCount(_,$),A=(x-E)*8;for(R.getLengthInBits()+4<=A&&R.put(0,4);R.getLengthInBits()%8!==0;)R.putBit(0);const D=(A-R.getLengthInBits())/8;for(let U=0;U<D;U++)R.put(U%2?17:236,8);return S(R,_,$)}function S(_,$,T){const R=e.getSymbolTotalCodewords($),x=i.getTotalCodewordsCount($,T),E=R-x,A=i.getBlocksCount($,T),D=R%A,U=A-D,K=Math.floor(R/A),G=Math.floor(E/A),te=G+1,X=K-G,ue=new l(X);let V=0;const C=new Array(A),N=new Array(A);let L=0;const I=new Uint8Array(_.buffer);for(let F=0;F<A;F++){const j=F<U?G:te;C[F]=I.slice(V,V+j),N[F]=ue.encode(C[F]),V+=j,L=Math.max(L,j)}const k=new Uint8Array(R);let O=0,q,B;for(q=0;q<L;q++)for(B=0;B<A;B++)q<C[B].length&&(k[O++]=C[B][q]);for(q=0;q<X;q++)for(B=0;B<A;B++)k[O++]=N[B][q];return k}function v(_,$,T,R){let x;if(Array.isArray(_))x=p.fromArray(_);else if(typeof _=="string"){let K=$;if(!K){const G=p.rawSplit(_);K=c.getBestVersionForData(G,T)}x=p.fromString(_,K||40)}else throw new Error("Invalid data");const E=c.getBestVersionForData(x,T);if(!E)throw new Error("The amount of data is too big to be stored in a QR Code");if(!$)$=E;else if($<E)throw new Error(`
|
|
52
|
-
The chosen QR Code version cannot contain this amount of data.
|
|
53
|
-
Minimum version required to store current data is: `+E+`.
|
|
54
|
-
`);const A=m($,T,x),D=e.getSymbolSize($),U=new n(D);return f(U,$),h(U),b(U,$),w(U,T,0),$>=7&&y(U,$),g(U,A),isNaN(R)&&(R=s.getBestMask(U,w.bind(null,U,T))),s.applyMask(R,U),w(U,T,R),{modules:U,version:$,errorCorrectionLevel:T,maskPattern:R,segments:x}}return qrcode.create=function($,T){if(typeof $>"u"||$==="")throw new Error("No input text");let R=t.M,x,E;return typeof T<"u"&&(R=t.from(T.errorCorrectionLevel,t.M),x=c.from(T.version),E=s.from(T.maskPattern),T.toSJISFunc&&e.setToSJISFunction(T.toSJISFunc)),v($,x,R,E)},qrcode}var canvas={},utils={},hasRequiredUtils;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=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,s=n.scale||4;return{width:a,scale:a?4:s,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 s=o.modules.size,i=o.modules.data,l=e.getScale(s,a),c=Math.floor((s+a.margin*2)*l),u=a.margin*l,d=[a.color.light,a.color.dark];for(let p=0;p<c;p++)for(let f=0;f<c;f++){let h=(p*c+f)*4,b=a.color.light;if(p>=u&&f>=u&&p<c-u&&f<c-u){const y=Math.floor((p-u)/l),w=Math.floor((f-u)/l);b=d[i[y*s+w]?1:0]}n[h++]=b.r,n[h++]=b.g,n[h++]=b.b,n[h]=b.a}}})(utils)),utils}var hasRequiredCanvas;function requireCanvas(){return hasRequiredCanvas||(hasRequiredCanvas=1,(function(e){const t=requireUtils();function r(o,a,s){o.clearRect(0,0,a.width,a.height),a.style||(a.style={}),a.height=s,a.width=s,a.style.height=s+"px",a.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(a,s,i){let l=i,c=s;typeof l>"u"&&(!s||!s.getContext)&&(l=s,s=void 0),s||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(a.modules.size,l),d=c.getContext("2d"),p=d.createImageData(u,u);return t.qrToImageData(p.data,a,l),r(d,c,u),d.putImageData(p,0,0),c},e.renderToDataURL=function(a,s,i){let l=i;typeof l>"u"&&(!s||!s.getContext)&&(l=s,s=void 0),l||(l={});const c=e.render(a,s,l),u=l.type||"image/png",d=l.rendererOpts||{};return c.toDataURL(u,d.quality)}})(canvas)),canvas}var svgTag={},hasRequiredSvgTag;function requireSvgTag(){if(hasRequiredSvgTag)return svgTag;hasRequiredSvgTag=1;const e=requireUtils();function t(o,a){const s=o.a/255,i=a+'="'+o.hex+'"';return s<1?i+" "+a+'-opacity="'+s.toFixed(2).slice(1)+'"':i}function r(o,a,s){let i=o+a;return typeof s<"u"&&(i+=" "+s),i}function n(o,a,s){let i="",l=0,c=!1,u=0;for(let d=0;d<o.length;d++){const p=Math.floor(d%a),f=Math.floor(d/a);!p&&!c&&(c=!0),o[d]?(u++,d>0&&p>0&&o[d-1]||(i+=c?r("M",p+s,.5+f+s):r("m",l,0),l=0,c=!1),p+1<a&&o[d+1]||(i+=r("h",u),u=0)):l++}return i}return svgTag.render=function(a,s,i){const l=e.getOptions(s),c=a.modules.size,u=a.modules.data,d=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+d+"v"+d+'H0z"/>':"",f="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',h='viewBox="0 0 '+d+" "+d+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+h+' shape-rendering="crispEdges">'+p+f+`</svg>
|
|
55
|
-
`;return typeof i=="function"&&i(null,y),y},svgTag}var hasRequiredBrowser;function requireBrowser(){if(hasRequiredBrowser)return browser;hasRequiredBrowser=1;const e=requireCanPromise(),t=requireQrcode(),r=requireCanvas(),n=requireSvgTag();function o(a,s,i,l,c){const u=[].slice.call(arguments,1),d=u.length,p=typeof u[d-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(d<2)throw new Error("Too few arguments provided");d===2?(c=i,i=s,s=l=void 0):d===3&&(s.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=s,s=void 0))}else{if(d<1)throw new Error("Too few arguments provided");return d===1?(i=s,s=l=void 0):d===2&&!s.getContext&&(l=i,i=s,s=void 0),new Promise(function(f,h){try{const b=t.create(i,l);f(a(b,s,l))}catch(b){h(b)}})}try{const f=t.create(i,l);c(null,a(f,s,l))}catch(f){c(f)}}return browser.create=t.create,browser.toCanvas=o.bind(null,r.render),browser.toDataURL=o.bind(null,r.renderToDataURL),browser.toString=o.bind(null,function(a,s,i){return n.render(a,i)}),browser}var browserExports=requireBrowser();const QRCodePck=getDefaultExportFromCjs(browserExports);class QrCode{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 QRCodePck.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return QRCodePck.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const DEFAULTS={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class Tooltip{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={...DEFAULTS,...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=`
|
|
56
|
-
<div class="${this.opts.className}__arrow"></div>
|
|
57
|
-
<div class="${this.opts.className}__inner">${t}</div>
|
|
58
|
-
`}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,s=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-s:i==="bottom"?c=r.bottom+o+s:i==="left"?u=r.left+a-n.width-s:i==="right"&&(u=r.right+a+s),(i==="top"||i==="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),(i==="left"||i==="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,s=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+s.width<=o-5&&t+s.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 STYLE_ID="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(STYLE_ID))return;const e=document.createElement("style");e.id=STYLE_ID,e.textContent=`
|
|
59
|
-
.tiny-remoter-native-tooltip {
|
|
60
|
-
position: absolute;
|
|
61
|
-
z-index: 9999;
|
|
62
|
-
max-width: 200px;
|
|
63
|
-
padding: 6px 10px;
|
|
64
|
-
font-size: 12px;
|
|
65
|
-
line-height: 1.4;
|
|
66
|
-
color: #fff;
|
|
67
|
-
background: #191919;
|
|
68
|
-
border-radius: 4px;
|
|
69
|
-
pointer-events: none;
|
|
70
|
-
box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
|
|
71
|
-
}
|
|
72
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
73
|
-
position: absolute;
|
|
74
|
-
width: 0; height: 0;
|
|
75
|
-
border: 6px solid transparent;
|
|
76
|
-
}
|
|
77
|
-
.tiny-remoter-native-tooltip--top
|
|
78
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
79
|
-
bottom: -12px;
|
|
80
|
-
left: 50%; transform:
|
|
81
|
-
translateX(-50%);
|
|
82
|
-
border-top-color: rgba(0,0,0,.75);
|
|
83
|
-
}
|
|
84
|
-
.tiny-remoter-native-tooltip--bottom
|
|
85
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
86
|
-
top: -12px;
|
|
87
|
-
left: 50%; transform:
|
|
88
|
-
translateX(-50%);
|
|
89
|
-
border-bottom-color: rgba(0,0,0,.75);
|
|
90
|
-
}
|
|
91
|
-
.tiny-remoter-native-tooltip--left
|
|
92
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
93
|
-
right: -12px;
|
|
94
|
-
top: 50%;
|
|
95
|
-
transform: translateY(-50%);
|
|
96
|
-
border-left-color: rgba(0,0,0,.75);
|
|
97
|
-
}
|
|
98
|
-
.tiny-remoter-native-tooltip--right
|
|
99
|
-
.tiny-remoter-native-tooltip__arrow {
|
|
100
|
-
left: -12px;
|
|
101
|
-
top: 50%;
|
|
102
|
-
transform: translateY(-50%);
|
|
103
|
-
border-right-color: rgba(0,0,0,.75);
|
|
104
|
-
}
|
|
105
|
-
`,document.head.appendChild(e)})();const chat="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",scan="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",link="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",qrCode="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",iconCopy="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",logo="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",DEFAULT_REMOTE_URL="https://chat.opentiny.design",DEFAULT_QR_CODE_URL="https://ai.opentiny.design/next-remoter",DEFAULT_LOGO_URL=logo,getDefaultMenuItems=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:qrCode},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:chat},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:link},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:scan}]};class FloatingBlock{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 Tooltip(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||DEFAULT_QR_CODE_URL,remoteUrl:t.remoteUrl||DEFAULT_REMOTE_URL,logoUrl:t.logoUrl||DEFAULT_LOGO_URL},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":qrCode,"ai-chat":chat,"remote-url":link,"remote-control":scan};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?getDefaultMenuItems(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=`
|
|
106
|
-
<div class="tiny-remoter-floating-block__icon">
|
|
107
|
-
<img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
|
|
108
|
-
</div>
|
|
109
|
-
`,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=>`
|
|
110
|
-
<div class="tiny-remoter-dropdown-item" data-action="${r.action}">
|
|
111
|
-
<div id="tiny-remoter-icon-item-${r.action}" class="tiny-remoter-dropdown-item__icon">
|
|
112
|
-
</div>
|
|
113
|
-
<div class="tiny-remoter-dropdown-item__content">
|
|
114
|
-
<div title="${r.tip}">${r.text}</div>
|
|
115
|
-
<div class="tiny-remoter-dropdown-item__desc-wrapper">
|
|
116
|
-
<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>
|
|
117
|
-
<div>
|
|
118
|
-
${r.showCopyIcon?`
|
|
119
|
-
<div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
|
|
120
|
-
<img src="${iconCopy}"/>
|
|
121
|
-
</div>
|
|
122
|
-
`:""}
|
|
123
|
-
</div>
|
|
124
|
-
</div>
|
|
125
|
-
</div>
|
|
126
|
-
</div>
|
|
127
|
-
`).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 s=n.dataset.action;s&&this.handleAction(s);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 QrCode((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
|
|
128
|
-
<div style="text-align: center; padding: 32px;">
|
|
129
|
-
<!-- 二维码容器 - 添加渐变背景和阴影效果 -->
|
|
130
|
-
<div style="
|
|
131
|
-
width: 240px;
|
|
132
|
-
height: 240px;
|
|
133
|
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
|
134
|
-
margin: 0 auto 24px;
|
|
135
|
-
display: flex;
|
|
136
|
-
align-items: center;
|
|
137
|
-
justify-content: center;
|
|
138
|
-
border-radius: 20px;
|
|
139
|
-
box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
|
|
140
|
-
position: relative;
|
|
141
|
-
overflow: hidden;
|
|
142
|
-
">
|
|
143
|
-
<!-- 装饰性背景元素 -->
|
|
144
|
-
<div style="
|
|
145
|
-
position: absolute;
|
|
146
|
-
top: -50%;
|
|
147
|
-
left: -50%;
|
|
148
|
-
width: 200%;
|
|
149
|
-
height: 200%;
|
|
150
|
-
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
|
|
151
|
-
animation: rotate 20s linear infinite;
|
|
152
|
-
"></div>
|
|
153
|
-
|
|
154
|
-
<!-- 二维码图片容器 -->
|
|
155
|
-
<div style="
|
|
156
|
-
width: 200px;
|
|
157
|
-
height: 200px;
|
|
158
|
-
background: white;
|
|
159
|
-
border-radius: 16px;
|
|
160
|
-
padding: 16px;
|
|
161
|
-
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
|
|
162
|
-
position: relative;
|
|
163
|
-
z-index: 1;
|
|
164
|
-
">
|
|
165
|
-
<img src="${r}" alt="二维码" style="
|
|
166
|
-
width: 100%;
|
|
167
|
-
height: 100%;
|
|
168
|
-
object-fit: contain;
|
|
169
|
-
border-radius: 8px;
|
|
170
|
-
">
|
|
171
|
-
</div>
|
|
172
|
-
</div>
|
|
173
|
-
|
|
174
|
-
<!-- 标题文字 -->
|
|
175
|
-
<h3 style="
|
|
176
|
-
color: #333;
|
|
177
|
-
margin: 0 0 12px 0;
|
|
178
|
-
font-size: 20px;
|
|
179
|
-
font-weight: 600;
|
|
180
|
-
letter-spacing: 0.5px;
|
|
181
|
-
">扫描二维码</h3>
|
|
182
|
-
|
|
183
|
-
<!-- 描述文字 -->
|
|
184
|
-
<p style="
|
|
185
|
-
color: #666;
|
|
186
|
-
margin: 0 auto;
|
|
187
|
-
margin-bottom: 20px;
|
|
188
|
-
font-size: 14px;
|
|
189
|
-
line-height: 1.6;
|
|
190
|
-
max-width: 280px;
|
|
191
|
-
">请使用手机微信或者浏览器扫描二维码跳转到智能遥控器</p>
|
|
192
|
-
|
|
193
|
-
<!-- 提示图标和文字 -->
|
|
194
|
-
<div style="
|
|
195
|
-
display: flex;
|
|
196
|
-
align-items: center;
|
|
197
|
-
justify-content: center;
|
|
198
|
-
gap: 8px;
|
|
199
|
-
color: #999;
|
|
200
|
-
font-size: 12px;
|
|
201
|
-
">
|
|
202
|
-
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="opacity: 0.7;">
|
|
203
|
-
<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"/>
|
|
204
|
-
</svg>
|
|
205
|
-
<span>支持微信、浏览器等多种方式</span>
|
|
206
|
-
</div>
|
|
207
|
-
</div>
|
|
208
|
-
`);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(t,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
|
|
209
|
-
<div class="tiny-remoter-modal-overlay"></div>
|
|
210
|
-
<div class="tiny-remoter-modal-content">
|
|
211
|
-
<div class="tiny-remoter-modal-header">
|
|
212
|
-
<h3>${t}</h3>
|
|
213
|
-
<button class="tiny-remoter-modal-close">×</button>
|
|
214
|
-
</div>
|
|
215
|
-
<div class="tiny-remoter-modal-body">
|
|
216
|
-
${r}
|
|
217
|
-
</div>
|
|
218
|
-
</div>
|
|
219
|
-
`;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=`
|
|
220
|
-
/* 浮动块样式 */
|
|
221
|
-
.tiny-remoter-floating-block {
|
|
222
|
-
position: fixed;
|
|
223
|
-
bottom: 30px;
|
|
224
|
-
right: 30px;
|
|
225
|
-
width: 60px;
|
|
226
|
-
height: 60px;
|
|
227
|
-
cursor: pointer;
|
|
228
|
-
display: flex;
|
|
229
|
-
align-items: center;
|
|
230
|
-
justify-content: center;
|
|
231
|
-
color: white;
|
|
232
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
233
|
-
z-index: 99;
|
|
234
|
-
overflow: hidden;
|
|
235
|
-
border-radius: 50%;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
.tiny-remoter-floating-block__icon {
|
|
239
|
-
transform: scale(0.8);
|
|
240
|
-
transition: transform 0.3s ease;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
.tiny-remoter-floating-block__icon:hover {
|
|
244
|
-
transform: scale(1.1);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
.tiny-remoter-floating-block.expanded .tiny-remoter-floating-block__icon {
|
|
248
|
-
transform: scale(1.1);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/* 下拉菜单样式 */
|
|
252
|
-
.tiny-remoter-floating-dropdown {
|
|
253
|
-
position: fixed;
|
|
254
|
-
bottom: 100px;
|
|
255
|
-
right: 30px;
|
|
256
|
-
background: white;
|
|
257
|
-
border-radius: 18px;
|
|
258
|
-
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
|
|
259
|
-
padding: 24px 24px 0px 24px;
|
|
260
|
-
opacity: 0;
|
|
261
|
-
visibility: hidden;
|
|
262
|
-
transform: translateY(20px) scale(0.95);
|
|
263
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
264
|
-
z-index: 999;
|
|
265
|
-
min-width: 200px;
|
|
266
|
-
width: 223px;
|
|
267
|
-
height: auto;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
.tiny-remoter-floating-dropdown.show {
|
|
271
|
-
opacity: 1;
|
|
272
|
-
visibility: visible;
|
|
273
|
-
transform: translateY(0) scale(1);
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
.tiny-remoter-dropdown-item {
|
|
277
|
-
display: flex;
|
|
278
|
-
align-items: center;
|
|
279
|
-
border-radius: 12px;
|
|
280
|
-
cursor: pointer;
|
|
281
|
-
transition: all 0.2s ease;
|
|
282
|
-
color: #333;
|
|
283
|
-
margin-bottom: 24px;
|
|
284
|
-
height: 40px;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
.tiny-remoter-dropdown-item:last-child {
|
|
288
|
-
margin-bottom: 32px;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
.tiny-remoter-dropdown-item > span {
|
|
292
|
-
flex: 1;
|
|
293
|
-
overflow: hidden;
|
|
294
|
-
max-width: 120px;
|
|
295
|
-
text-overflow: ellipsis;
|
|
296
|
-
white-space: nowrap;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
.tiny-remoter-dropdown-item__icon {
|
|
300
|
-
display: flex;
|
|
301
|
-
align-items: center;
|
|
302
|
-
justify-content: center;
|
|
303
|
-
width: 40px;
|
|
304
|
-
height: 40px;
|
|
305
|
-
background: #f8f9fa;
|
|
306
|
-
border-radius: 8px;
|
|
307
|
-
color: #667eea;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
.tiny-remoter-dropdown-item__content {
|
|
311
|
-
flex: 1;
|
|
312
|
-
display: flex;
|
|
313
|
-
flex-direction: column;
|
|
314
|
-
gap: 4px;
|
|
315
|
-
overflow: hidden;
|
|
316
|
-
font-size: 12px;
|
|
317
|
-
margin-left: 16px;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
.tiny-remoter-dropdown-item__desc-wrapper {
|
|
321
|
-
display: flex;
|
|
322
|
-
align-items: center;
|
|
323
|
-
gap: 4px;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
.tiny-remoter-dropdown-item__desc {
|
|
327
|
-
color: #808080;
|
|
328
|
-
overflow: hidden;
|
|
329
|
-
white-space: nowrap;
|
|
330
|
-
text-overflow: ellipsis;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
.tiny-remoter-dropdown-item__desc--active {
|
|
334
|
-
color: #1476ff;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
.tiny-remoter-dropdown-item__desc--know {
|
|
338
|
-
color: #191919;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
/* 复制图标样式 */
|
|
342
|
-
.tiny-remoter-copy-icon {
|
|
343
|
-
display: flex;
|
|
344
|
-
align-items: center;
|
|
345
|
-
justify-content: center;
|
|
346
|
-
width: 24px;
|
|
347
|
-
height: 24px;
|
|
348
|
-
background: #f0f0f0;
|
|
349
|
-
border-radius: 6px;
|
|
350
|
-
color: #666;
|
|
351
|
-
cursor: pointer;
|
|
352
|
-
transition: all 0.2s ease;
|
|
353
|
-
opacity: 0.7;
|
|
354
|
-
margin-left: auto;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
.tiny-remoter-copy-icon:hover {
|
|
358
|
-
background: #e0e0e0;
|
|
359
|
-
color: #333;
|
|
360
|
-
opacity: 1;
|
|
361
|
-
transform: scale(1.1);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
.tiny-remoter-copy-icon:active {
|
|
365
|
-
transform: scale(0.95);
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
/* 弹窗样式 */
|
|
369
|
-
.tiny-remoter-floating-modal {
|
|
370
|
-
position: fixed;
|
|
371
|
-
top: 0;
|
|
372
|
-
left: 0;
|
|
373
|
-
width: 100%;
|
|
374
|
-
height: 100%;
|
|
375
|
-
z-index: 2000;
|
|
376
|
-
display: flex;
|
|
377
|
-
align-items: center;
|
|
378
|
-
justify-content: center;
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
.tiny-remoter-modal-overlay {
|
|
382
|
-
position: absolute;
|
|
383
|
-
top: 0;
|
|
384
|
-
left: 0;
|
|
385
|
-
width: 100%;
|
|
386
|
-
height: 100%;
|
|
387
|
-
background: rgba(0, 0, 0, 0.5);
|
|
388
|
-
backdrop-filter: blur(4px);
|
|
389
|
-
opacity: 0;
|
|
390
|
-
transition: opacity 0.3s ease;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
.tiny-remoter-modal-content {
|
|
394
|
-
background: white;
|
|
395
|
-
border-radius: 16px;
|
|
396
|
-
box-shadow: 0 25px 80px rgba(0, 0, 0, 0.2);
|
|
397
|
-
max-width: 500px;
|
|
398
|
-
width: 90%;
|
|
399
|
-
max-height: 80vh;
|
|
400
|
-
overflow: hidden;
|
|
401
|
-
transform: scale(0.9) translateY(20px);
|
|
402
|
-
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
.tiny-remoter-floating-modal.show .tiny-remoter-modal-overlay {
|
|
406
|
-
opacity: 1;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
.tiny-remoter-floating-modal.show .tiny-remoter-modal-content {
|
|
410
|
-
transform: scale(1) translateY(0);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
.tiny-remoter-modal-header {
|
|
414
|
-
display: flex;
|
|
415
|
-
align-items: center;
|
|
416
|
-
justify-content: space-between;
|
|
417
|
-
padding: 20px 24px;
|
|
418
|
-
border-bottom: 1px solid #f0f0f0;
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
.tiny-remoter-modal-header h3 {
|
|
422
|
-
margin: 0;
|
|
423
|
-
font-size: 18px;
|
|
424
|
-
font-weight: 600;
|
|
425
|
-
color: #333;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
.tiny-remoter-modal-close {
|
|
429
|
-
background: none;
|
|
430
|
-
border: none;
|
|
431
|
-
font-size: 24px;
|
|
432
|
-
cursor: pointer;
|
|
433
|
-
color: #999;
|
|
434
|
-
padding: 0;
|
|
435
|
-
width: 32px;
|
|
436
|
-
height: 32px;
|
|
437
|
-
border-radius: 50%;
|
|
438
|
-
display: flex;
|
|
439
|
-
align-items: center;
|
|
440
|
-
justify-content: center;
|
|
441
|
-
transition: all 0.2s ease;
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
.tiny-remoter-modal-close:hover {
|
|
445
|
-
background: #f5f5f5;
|
|
446
|
-
color: #666;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
.tiny-remoter-modal-body {
|
|
450
|
-
padding: 24px;
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
/* 二维码弹窗动画 */
|
|
454
|
-
@keyframes rotate {
|
|
455
|
-
from {
|
|
456
|
-
transform: rotate(0deg);
|
|
457
|
-
}
|
|
458
|
-
to {
|
|
459
|
-
transform: rotate(360deg);
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
/* 响应式设计 */
|
|
464
|
-
@media (max-width: 768px) {
|
|
465
|
-
.tiny-remoter-floating-block {
|
|
466
|
-
bottom: 20px;
|
|
467
|
-
right: 20px;
|
|
468
|
-
width: 56px;
|
|
469
|
-
height: 56px;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
.tiny-remoter-floating-dropdown {
|
|
473
|
-
bottom: 90px;
|
|
474
|
-
right: 20px;
|
|
475
|
-
min-width: 180px;
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
.tiny-remoter-modal-content {
|
|
479
|
-
width: 95%;
|
|
480
|
-
margin: 20px;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/* 复制反馈提示样式 */
|
|
485
|
-
.tiny-remoter-copy-feedback {
|
|
486
|
-
position: fixed;
|
|
487
|
-
top: 50%;
|
|
488
|
-
left: 50%;
|
|
489
|
-
transform: translate(-50%, -50%);
|
|
490
|
-
background: rgba(0, 0, 0, 0.8);
|
|
491
|
-
color: white;
|
|
492
|
-
padding: 12px 24px;
|
|
493
|
-
border-radius: 8px;
|
|
494
|
-
font-size: 14px;
|
|
495
|
-
font-weight: 500;
|
|
496
|
-
z-index: 10000;
|
|
497
|
-
opacity: 0;
|
|
498
|
-
visibility: hidden;
|
|
499
|
-
transition: all 0.3s ease;
|
|
500
|
-
backdrop-filter: blur(4px);
|
|
501
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
.tiny-remoter-copy-feedback.show {
|
|
505
|
-
opacity: 1;
|
|
506
|
-
visibility: visible;
|
|
507
|
-
transform: translate(-50%, -50%) scale(1);
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
.tiny-remoter-copy-feedback.success {
|
|
511
|
-
background: rgba(34, 197, 94, 0.9);
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
.tiny-remoter-copy-feedback.error {
|
|
515
|
-
background: rgba(239, 68, 68, 0.9);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
/* 深色主题支持 */
|
|
519
|
-
@media (prefers-color-scheme: dark) {
|
|
520
|
-
.tiny-remoter-floating-dropdown {
|
|
521
|
-
background: #1a1a1a;
|
|
522
|
-
color: white;
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
.tiny-remoter-dropdown-item {
|
|
526
|
-
color: white;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
.tiny-remoter-copy-icon {
|
|
531
|
-
background: #2a2a2a;
|
|
532
|
-
color: #ccc;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
.tiny-remoter-copy-icon:hover {
|
|
536
|
-
background: #3a3a3a;
|
|
537
|
-
color: white;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
.tiny-remoter-modal-content {
|
|
541
|
-
background: #1a1a1a;
|
|
542
|
-
color: white;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
.tiny-remoter-modal-header {
|
|
546
|
-
border-bottom-color: #333;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
.tiny-remoter-modal-header h3 {
|
|
550
|
-
color: white;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
`,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 createRemoter=(e={})=>new FloatingBlock(e);var marker$5="vercel.ai.error",symbol$5=Symbol.for(marker$5),_a$5,_b$3,AISDKError$1=class Ft extends(_b$3=Error,_a$5=symbol$5,_b$3){constructor({name:t,message:r,cause:n}){super(r),this[_a$5]=!0,this.name=t,this.cause=n}static isInstance(t){return Ft.hasMarker(t,marker$5)}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}},name$5="AI_APICallError",marker2$3=`vercel.ai.error.${name$5}`,symbol2$3=Symbol.for(marker2$3),_a2$3,_b2$2,APICallError$1=class extends(_b2$2=AISDKError$1,_a2$3=symbol2$3,_b2$2){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:a,responseBody:s,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:name$5,message:t,cause:i}),this[_a2$3]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=a,this.responseBody=s,this.isRetryable=l,this.data=c}static isInstance(t){return AISDKError$1.hasMarker(t,marker2$3)}},name2$3="AI_EmptyResponseBodyError",marker3$3=`vercel.ai.error.${name2$3}`,symbol3$3=Symbol.for(marker3$3),_a3$3,_b3$1,EmptyResponseBodyError$1=class extends(_b3$1=AISDKError$1,_a3$3=symbol3$3,_b3$1){constructor({message:t="Empty response body"}={}){super({name:name2$3,message:t}),this[_a3$3]=!0}static isInstance(t){return AISDKError$1.hasMarker(t,marker3$3)}};function getErrorMessage$2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var name3$3="AI_InvalidArgumentError",marker4$3=`vercel.ai.error.${name3$3}`,symbol4$3=Symbol.for(marker4$3),_a4$3,_b4$1,InvalidArgumentError$2=class extends(_b4$1=AISDKError$1,_a4$3=symbol4$3,_b4$1){constructor({message:t,cause:r,argument:n}){super({name:name3$3,message:t,cause:r}),this[_a4$3]=!0,this.argument=n}static isInstance(t){return AISDKError$1.hasMarker(t,marker4$3)}},name4$2="AI_InvalidPromptError",marker5$2=`vercel.ai.error.${name4$2}`,symbol5$2=Symbol.for(marker5$2),_a5$2,_b5$1,InvalidPromptError=class extends(_b5$1=AISDKError$1,_a5$2=symbol5$2,_b5$1){constructor({prompt:e,message:t,cause:r}){super({name:name4$2,message:`Invalid prompt: ${t}`,cause:r}),this[_a5$2]=!0,this.prompt=e}static isInstance(e){return AISDKError$1.hasMarker(e,marker5$2)}},name5$3="AI_InvalidResponseDataError",marker6$3=`vercel.ai.error.${name5$3}`,symbol6$3=Symbol.for(marker6$3),_a6$3,_b6$1,InvalidResponseDataError$1=class extends(_b6$1=AISDKError$1,_a6$3=symbol6$3,_b6$1){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:name5$3,message:r}),this[_a6$3]=!0,this.data=t}static isInstance(t){return AISDKError$1.hasMarker(t,marker6$3)}},name6$3="AI_JSONParseError",marker7$3=`vercel.ai.error.${name6$3}`,symbol7$3=Symbol.for(marker7$3),_a7$3,_b7$1,JSONParseError$1=class extends(_b7$1=AISDKError$1,_a7$3=symbol7$3,_b7$1){constructor({text:t,cause:r}){super({name:name6$3,message:`JSON parsing failed: Text: ${t}.
|
|
554
|
-
Error message: ${getErrorMessage$2(r)}`,cause:r}),this[_a7$3]=!0,this.text=t}static isInstance(t){return AISDKError$1.hasMarker(t,marker7$3)}},name7$3="AI_LoadAPIKeyError",marker8$2=`vercel.ai.error.${name7$3}`,symbol8$2=Symbol.for(marker8$2),_a8$2,_b8$1,LoadAPIKeyError$1=class extends(_b8$1=AISDKError$1,_a8$2=symbol8$2,_b8$1){constructor({message:t}){super({name:name7$3,message:t}),this[_a8$2]=!0}static isInstance(t){return AISDKError$1.hasMarker(t,marker8$2)}},name11="AI_TooManyEmbeddingValuesForCallError",marker12=`vercel.ai.error.${name11}`,symbol12=Symbol.for(marker12),_a12,_b12,TooManyEmbeddingValuesForCallError=class extends(_b12=AISDKError$1,_a12=symbol12,_b12){constructor(e){super({name:name11,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[_a12]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return AISDKError$1.hasMarker(e,marker12)}},name12$1="AI_TypeValidationError",marker13$1=`vercel.ai.error.${name12$1}`,symbol13$1=Symbol.for(marker13$1),_a13$1,_b13,TypeValidationError$1=class Lt extends(_b13=AISDKError$1,_a13$1=symbol13$1,_b13){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:name12$1,message:`${o}: Value: ${JSON.stringify(t)}.
|
|
555
|
-
Error message: ${getErrorMessage$2(r)}`,cause:r}),this[_a13$1]=!0,this.value=t,this.context=n}static isInstance(t){return AISDKError$1.hasMarker(t,marker13$1)}static wrap({value:t,cause:r,context:n}){var o,a,s;return Lt.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&&((s=r.context)==null?void 0:s.entityId)===n?.entityId?r:new Lt({value:t,cause:r,context:n})}},name13$1="AI_UnsupportedFunctionalityError",marker14$2=`vercel.ai.error.${name13$1}`,symbol14$2=Symbol.for(marker14$2),_a14$2,_b14,UnsupportedFunctionalityError$1=class extends(_b14=AISDKError$1,_a14$2=symbol14$2,_b14){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:name13$1,message:r}),this[_a14$2]=!0,this.functionality=t}static isInstance(t){return AISDKError$1.hasMarker(t,marker14$2)}};function combineHeaders$1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function createToolNameMapping({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},a={};for(const s of e)if(s.type==="provider"){const i=(n=r?.(s))!=null?n:s.id in t?t[s.id]:void 0;if(i==null)continue;o[s.name]=i,a[i]=s.name}return{toProviderToolName:s=>{var i;return(i=o[s])!=null?i:s},toCustomToolName:s=>{var i;return(i=a[s])!=null?i:s}}}async function delay(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(createAbortError());return}const a=setTimeout(()=>{s(),n()},e),s=()=>{clearTimeout(a),r?.removeEventListener("abort",i)},i=()=>{s(),o(createAbortError())};r?.addEventListener("abort",i)})}function createAbortError(){return new DOMException("Delay was aborted","AbortError")}var DelayedPromise=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 extractResponseHeaders$1(e){return Object.fromEntries([...e.headers])}var{btoa:btoa$2,atob:atob$1}=globalThis;function convertBase64ToUint8Array(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob$1(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function convertUint8ArrayToBase64$1(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return btoa$2(t)}function convertToBase64$1(e){return e instanceof Uint8Array?convertUint8ArrayToBase64$1(e):e}function convertToFormData(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 s=r?`${o}[]`:o;for(const i of a)n.append(s,i);continue}n.append(o,a)}return n}async function cancelResponseBody(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch{}}var name$4="AI_DownloadError",marker$4=`vercel.ai.error.${name$4}`,symbol$4=Symbol.for(marker$4),_a$4,_b$2,DownloadError=class extends(_b$2=AISDKError$1,_a$4=symbol$4,_b$2){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:name$4,message:o,cause:n}),this[_a$4]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return AISDKError$1.hasMarker(e,marker$4)}};function isBrowserRuntime(e=globalThis){return e.window!=null}function validateDownloadUrl(e){let t;try{t=new URL(e)}catch{throw new DownloadError({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new DownloadError({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname.toLowerCase().replace(/\.+$/,"");if(!r)throw new DownloadError({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new DownloadError({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(isPrivateIPv6(n))throw new DownloadError({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(isIPv4(r)){if(isPrivateIPv4(r))throw new DownloadError({url:e,message:`URL with IP address ${r} is not allowed`});return}}function isIPv4(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 isPrivateIPv4(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 parseIPv6(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=s=>{if(s==="")return[];const i=[],l=s.split(":");for(let c=0;c<l.length;c++){const u=l[c];if(u.includes(".")){if(c!==l.length-1||!isIPv4(u))return null;const[d,p,f,h]=u.split(".").map(Number);i.push(d<<8|p,f<<8|h);continue}if(!/^[0-9a-f]{1,4}$/.test(u))return null;i.push(parseInt(u,16))}return i},a=o(n[0]);if(a===null)return null;if(n.length===2){const s=o(n[1]);if(s===null)return null;const i=8-a.length-s.length;return i<0?null:[...a,...new Array(i).fill(0),...s]}return a.length===8?a:null}function isPrivateIPv6(e){const t=parseIPv6(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,s=t[7]>>8&255,i=t[7]&255;return isPrivateIPv4(`${o}.${a}.${s}.${i}`)}return!1}var MAX_DOWNLOAD_REDIRECTS=10;async function fetchWithValidatedRedirects({url:e,headers:t,abortSignal:r,maxRedirects:n=MAX_DOWNLOAD_REDIRECTS}){const o={signal:r};t!==void 0&&(o.headers=t);let a=e;for(let s=0;s<=n;s++){validateDownloadUrl(a);const i=await fetch(a,{...o,redirect:"manual"});if(i.type==="opaqueredirect"){if(!isBrowserRuntime())throw new DownloadError({url:e,message:`Redirect from ${a} could not be validated and was blocked`});return await fetch(a,{...o,redirect:"follow"})}const l=i.headers.get("location");if(i.status>=300&&i.status<400&&l){await cancelResponseBody(i),a=new URL(l,a).toString();continue}return i}throw new DownloadError({url:e,message:`Too many redirects (max ${n})`})}var DEFAULT_MAX_DOWNLOAD_SIZE=2*1024*1024*1024;async function readResponseWithSizeLimit({response:e,url:t,maxBytes:r=DEFAULT_MAX_DOWNLOAD_SIZE}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw await cancelResponseBody(e),new DownloadError({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(),s=[];let i=0;try{for(;;){const{done:u,value:d}=await a.read();if(u)break;if(i+=d.length,i>r)throw new DownloadError({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});s.push(d)}}finally{try{await a.cancel()}finally{a.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of s)l.set(u,c),c+=u.length;return l}async function downloadBlob(e,t){var r,n;try{const o=await fetchWithValidatedRedirects({url:e,abortSignal:t?.abortSignal});if(!o.ok)throw await cancelResponseBody(o),new DownloadError({url:e,statusCode:o.status,statusText:o.statusText});const a=await readResponseWithSizeLimit({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:DEFAULT_MAX_DOWNLOAD_SIZE}),s=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([a],s?{type:s}:void 0)}catch(o){throw DownloadError.isInstance(o)?o:new DownloadError({url:e,cause:o})}}var createIdGenerator$1=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,s=new Array(t);for(let i=0;i<t;i++)s[i]=r[Math.random()*a|0];return s.join("")};if(e==null)return o;if(r.includes(n))throw new InvalidArgumentError$2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},generateId$1=createIdGenerator$1();function getErrorMessage$1(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function isAbortError$1(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var FETCH_FAILED_ERROR_MESSAGES$1=["fetch failed","failed to fetch"],BUN_ERROR_CODES=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function isBunNetworkError(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&BUN_ERROR_CODES.includes(t))}function handleFetchError$1({error:e,url:t,requestBodyValues:r}){if(isAbortError$1(e))return e;if(e instanceof TypeError&&FETCH_FAILED_ERROR_MESSAGES$1.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new APICallError$1({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return isBunNetworkError(e)?new APICallError$1({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function getRuntimeEnvironmentUserAgent$1(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 normalizeHeaders$1(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 withUserAgentSuffix$1(e,...t){const r=new Headers(normalizeHeaders$1(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var VERSION$7="4.0.33",getOriginalFetch=()=>globalThis.fetch,getFromApi=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:a=getOriginalFetch()})=>{try{const s=await a(e,{method:"GET",headers:withUserAgentSuffix$1(t,`ai-sdk/provider-utils/${VERSION$7}`,getRuntimeEnvironmentUserAgent$1()),signal:o}),i=extractResponseHeaders$1(s);if(!s.ok){let l;try{l=await n({response:s,url:e,requestBodyValues:{}})}catch(c){throw isAbortError$1(c)||APICallError$1.isInstance(c)?c:new APICallError$1({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:s,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(isAbortError$1(l)||APICallError$1.isInstance(l))?l:new APICallError$1({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(s){throw handleFetchError$1({error:s,url:e,requestBodyValues:{}})}};function isNonNullable(e){return e!=null}function isUrlSupported({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 loadApiKey$1({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new LoadAPIKeyError$1({message:`${n} API key must be a string.`});if(typeof process>"u")throw new LoadAPIKeyError$1({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 LoadAPIKeyError$1({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new LoadAPIKeyError$1({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function loadOptionalSetting({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 mediaTypeToExtension(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 suspectProtoRx$1=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,suspectConstructorRx$1=/"(?: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 _parse$1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||suspectProtoRx$1.test(e)===!1&&suspectConstructorRx$1.test(e)===!1?t:filter$1(t)}function filter$1(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 secureJsonParse$1(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return _parse$1(e)}try{return _parse$1(e)}finally{Error.stackTraceLimit=t}}function addAdditionalPropertiesToJsonSchema(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]=visit(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(visit):visit(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(visit)),e.allOf!=null&&(e.allOf=e.allOf.map(visit)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(visit));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=visit(t[r]);return e}function visit(e){return typeof e=="boolean"?e:addAdditionalPropertiesToJsonSchema(e)}var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={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"},getDefaultOptions=e=>typeof e=="string"?{...defaultOptions,name:e}:{...defaultOptions,...e};function parseAnyDef(){return{}}function parseArrayDef(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)!==ZodFirstPartyTypeKind.ZodAny&&(a.items=parseDef(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 parseBigintDef(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 parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}var parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>parseDateDef(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 integerDateParser(e)}}var integerDateParser=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 parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy==="input"?parseDef(e.schema._def,t):parseAnyDef()}function parseEnumDef(e){return{type:"string",enum:Array.from(e.values)}}var isJsonSchema7AllOfType=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function parseIntersectionDef(e,t){const r=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(isJsonSchema7AllOfType(o))n.push(...o.allOf);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:s,...i}=o;a=i}n.push(a)}}),n.length?{allOf:n}:void 0}function parseLiteralDef(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 emojiRegex=void 0,zodPatterns={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:()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),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 parseStringDef(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":addFormat(r,"email",n.message,t);break;case"format:idn-email":addFormat(r,"idn-email",n.message,t);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,t);break}break;case"url":addFormat(r,"uri",n.message,t);break;case"uuid":addFormat(r,"uuid",n.message,t);break;case"regex":addPattern(r,n.regex,n.message,t);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,t);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,t);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,t)}`),n.message,t);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,t)}$`),n.message,t);break;case"datetime":addFormat(r,"date-time",n.message,t);break;case"date":addFormat(r,"date",n.message,t);break;case"time":addFormat(r,"time",n.message,t);break;case"duration":addFormat(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":{addPattern(r,RegExp(escapeLiteralCheckValue(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&addFormat(r,"ipv4",n.message,t),n.version!=="v4"&&addFormat(r,"ipv6",n.message,t);break}case"base64url":addPattern(r,zodPatterns.base64url,n.message,t);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&addPattern(r,zodPatterns.ipv4Cidr,n.message,t),n.version!=="v4"&&addPattern(r,zodPatterns.ipv6Cidr,n.message,t);break}case"emoji":addPattern(r,zodPatterns.emoji(),n.message,t);break;case"ulid":{addPattern(r,zodPatterns.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{addFormat(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{addPattern(r,zodPatterns.base64,n.message,t);break}}break}case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,t)}return r}function escapeLiteralCheckValue(e,t){return t.patternStrategy==="escape"?escapeNonAlphaNumeric(e):e}var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(e){let t="";for(let r=0;r<e.length;r++)ALPHA_NUMERIC.has(e[r])||(t+="\\"),t+=e[r];return t}function addFormat(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 addPattern(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:stringifyRegExpWithFlags(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=stringifyRegExpWithFlags(t,n)}function stringifyRegExpWithFlags(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="",s=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(s){a+=o[c],s=!1;continue}if(n.i){if(i){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
|
|
556
|
-
]))`;continue}else if(o[c]==="$"){a+=`($|(?=[\r
|
|
557
|
-
]))`;continue}}if(n.s&&o[c]==="."){a+=i?`${o[c]}\r
|
|
558
|
-
`:`[${o[c]}\r
|
|
559
|
-
]`;continue}a+=o[c],o[c]==="\\"?s=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!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 parseRecordDef(e,t){var r,n,o,a,s,i;const l={type:"object",additionalProperties:(r=parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===ZodFirstPartyTypeKind.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=parseStringDef(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===ZodFirstPartyTypeKind.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((s=e.keyType)==null?void 0:s._def.typeName)===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=parseBrandedDef(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function parseMapDef(e,t){if(t.mapStrategy==="record")return parseRecordDef(e,t);const r=parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||parseAnyDef(),n=parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||parseAnyDef();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef(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 parseNeverDef(){return{not:parseAnyDef()}}function parseNullDef(){return{type:"null"}}var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in primitiveMappings&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,a)=>{const s=primitiveMappings[a._def.typeName];return s&&!o.includes(s)?[...o,s]: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 s=typeof a._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];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,s,i)=>i.indexOf(a)===s);return{type:o.length>1?o:o[0],enum:r.reduce((a,s)=>a.includes(s._def.value)?a:[...a,s._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 asAnyOf(e,t)}var asAnyOf=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>parseDef(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 parseNullableDef(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[primitiveMappings[e.innerType._def.typeName],"null"]};const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(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 parseObjectDef(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let i=o[s];if(i===void 0||i._def===void 0)continue;const l=safeIsOptional(i),c=parseDef(i._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});c!==void 0&&(r.properties[s]=c,l||n.push(s))}n.length&&(r.required=n);const a=decideAdditionalProperties(e,t);return a!==void 0&&(r.additionalProperties=a),r}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!=="ZodNever")return parseDef(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 safeIsOptional(e){try{return e.isOptional()}catch{return!0}}var parseOptionalDef=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return parseDef(e.innerType._def,t);const n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:parseAnyDef()},n]}:parseAnyDef()},parsePipelineDef=(e,t)=>{if(t.pipeStrategy==="input")return parseDef(e.in._def,t);if(t.pipeStrategy==="output")return parseDef(e.out._def,t);const r=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=parseDef(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){const n={type:"array",uniqueItems:!0,items:parseDef(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 parseTupleDef(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>parseDef(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>parseDef(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef(){return{not:parseAnyDef()}}function parseUnknownDef(){return parseAnyDef()}var parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,r)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef();case ZodFirstPartyTypeKind.ZodNull:return parseNullDef();case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef();case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef();case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef();case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}},getRelativePath=(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 parseDef(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!==ignoreOverride)return l}if(o&&!r){const l=get$ref(o,t);if(l!==void 0)return l}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const s=selectParser(e,e.typeName,t),i=typeof s=="function"?parseDef(s(),t):s;if(i&&addMeta(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return a.jsonSchema=i,l}return a.jsonSchema=i,i}var get$ref=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath(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`),parseAnyDef()):t.$refStrategy==="seen"?parseAnyDef():void 0}},addMeta=(e,t,r)=>(e.description&&(r.description=e.description),r),getRefs=e=>{const t=getDefaultOptions(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}]))}},zod3ToJsonSchema=(e,t)=>{var r;const n=getRefs(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>{var p;return{...c,[u]:(p=parseDef(d._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:parseAnyDef()}},{}):void 0;const a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=(r=parseDef(e._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1))!=null?r:parseAnyDef(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(s.title=i);const l=a===void 0?o?{...s,[n.definitionPath]:o}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...o,[a]:s}};return l.$schema="http://json-schema.org/draft-07/schema#",l},schemaSymbol=Symbol.for("vercel.ai.schema");function lazySchema(e){let t;return()=>(t==null&&(t=e()),t)}function jsonSchema(e,{validate:t}={}){return{[schemaSymbol]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function isSchema(e){return typeof e=="object"&&e!==null&&schemaSymbol in e&&e[schemaSymbol]===!0&&"jsonSchema"in e&&"validate"in e}function asSchema(e){return e==null?jsonSchema({properties:{},additionalProperties:!1}):isSchema(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?zodSchema(e):standardSchema(e):e()}function standardSchema(e){return jsonSchema(()=>addAdditionalPropertiesToJsonSchema(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 TypeValidationError$1({value:t,cause:r.issues})}}})}function zod3Schema(e,t){var r;const n=(r=void 0)!=null?r:!1;return jsonSchema(()=>zod3ToJsonSchema(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 zod4Schema(e,t){var r;const n=(r=void 0)!=null?r:!1;return jsonSchema(()=>addAdditionalPropertiesToJsonSchema(toJSONSchema(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const a=await safeParseAsync$1(e,o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function isZod4Schema(e){return"_zod"in e}function zodSchema(e,t){return isZod4Schema(e)?zod4Schema(e):zod3Schema(e)}async function validateTypes$1({value:e,schema:t,context:r}){const n=await safeValidateTypes$1({value:e,schema:t,context:r});if(!n.success)throw TypeValidationError$1.wrap({value:e,cause:n.error,context:r});return n.value}async function safeValidateTypes$1({value:e,schema:t,context:r}){const n=asSchema(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:TypeValidationError$1.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:TypeValidationError$1.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function parseJSON$1({text:e,schema:t}){try{const r=secureJsonParse$1(e);return t==null?r:validateTypes$1({value:r,schema:t})}catch(r){throw JSONParseError$1.isInstance(r)||TypeValidationError$1.isInstance(r)?r:new JSONParseError$1({text:e,cause:r})}}async function safeParseJSON$1({text:e,schema:t}){try{const r=secureJsonParse$1(e);return t==null?{success:!0,value:r,rawValue:r}:await safeValidateTypes$1({value:r,schema:t})}catch(r){return{success:!1,error:JSONParseError$1.isInstance(r)?r:new JSONParseError$1({text:e,cause:r}),rawValue:void 0}}}function isParsableJson$1(e){try{return secureJsonParse$1(e),!0}catch{return!1}}function parseJsonEventStream$1({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await safeParseJSON$1({text:r,schema:t}))}}))}async function parseProviderOptions$1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await safeValidateTypes$1({value:t[e],schema:r});if(!n.success)throw new InvalidArgumentError$2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var getOriginalFetch2$1=()=>globalThis.fetch,postJsonToApi$1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s})=>postToApi$1({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s}),postFormDataToApi=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s})=>postToApi$1({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s}),postToApi$1=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:s=getOriginalFetch2$1()})=>{try{const i=await s(e,{method:"POST",headers:withUserAgentSuffix$1(t,`ai-sdk/provider-utils/${VERSION$7}`,getRuntimeEnvironmentUserAgent$1()),body:r.content,signal:a}),l=extractResponseHeaders$1(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw isAbortError$1(u)||APICallError$1.isInstance(u)?u:new APICallError$1({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(isAbortError$1(c)||APICallError$1.isInstance(c))?c:new APICallError$1({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw handleFetchError$1({error:i,url:e,requestBodyValues:r.values})}};function tool(e){return e}function dynamicTool(e){return{...e,type:"dynamic"}}function createProviderToolFactory({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:a,onInputStart:s,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:a,onInputStart:s,onInputDelta:i,onInputAvailable:l})}function createProviderToolFactoryWithOutputSchema({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:a,toModelOutput:s,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:a,toModelOutput:s,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function resolve(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var textDecoder=new TextDecoder;async function readResponseBodyAsText({response:e,url:t}){return textDecoder.decode(await readResponseWithSizeLimit({response:e,url:t}))}var createJsonErrorResponseHandler$1=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const s=await readResponseBodyAsText({response:n,url:o}),i=extractResponseHeaders$1(n);if(s.trim()==="")return{responseHeaders:i,value:new APICallError$1({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r?.(n)})};try{const l=await parseJSON$1({text:s,schema:e});return{responseHeaders:i,value:new APICallError$1({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new APICallError$1({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r?.(n)})}}},createEventSourceResponseHandler$1=e=>async({response:t})=>{const r=extractResponseHeaders$1(t);if(t.body==null)throw new EmptyResponseBodyError$1({});return{responseHeaders:r,value:parseJsonEventStream$1({stream:t.body,schema:e})}},createJsonResponseHandler$1=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await readResponseBodyAsText({response:t,url:r}),a=await safeParseJSON$1({text:o,schema:e}),s=extractResponseHeaders$1(t);if(!a.success)throw new APICallError$1({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:s,value:a.value,rawValue:a.rawValue}},createBinaryResponseHandler=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=extractResponseHeaders$1(e);if(!e.body)throw new APICallError$1({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 APICallError$1({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function withoutTrailingSlash$1(e){return e?.replace(/\/$/,"")}function isAsyncIterable(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*executeTool({execute:e,input:t,options:r}){const n=e(t,r);if(isAsyncIterable(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}}var getContext_1,hasRequiredGetContext;function requireGetContext(){if(hasRequiredGetContext)return getContext_1;hasRequiredGetContext=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,d)=>{for(var p in d)e(u,p,{get:d[p],enumerable:!0})},a=(u,d,p,f)=>{if(d&&typeof d=="object"||typeof d=="function")for(let h of r(d))!n.call(u,h)&&h!==p&&e(u,h,{get:()=>d[h],enumerable:!(f=t(d,h))||f.enumerable});return u},s=u=>a(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),getContext_1=s(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return getContext_1}var authErrors,hasRequiredAuthErrors;function requireAuthErrors(){if(hasRequiredAuthErrors)return authErrors;hasRequiredAuthErrors=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,d)=>{for(var p in d)e(u,p,{get:d[p],enumerable:!0})},a=(u,d,p,f)=>{if(d&&typeof d=="object"||typeof d=="function")for(let h of r(d))!n.call(u,h)&&h!==p&&e(u,h,{get:()=>d[h],enumerable:!(f=t(d,h))||f.enumerable});return u},s=u=>a(e({},"__esModule",{value:!0}),u),i={};o(i,{AccessTokenMissingError:()=>l,RefreshAccessTokenFailedError:()=>c}),authErrors=s(i);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(d){super("Failed to refresh authentication token.",{cause:d}),this.name="RefreshAccessTokenFailedError"}}return authErrors}var indexBrowser,hasRequiredIndexBrowser;function requireIndexBrowser(){if(hasRequiredIndexBrowser)return indexBrowser;hasRequiredIndexBrowser=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(f,h)=>{for(var b in h)e(f,b,{get:h[b],enumerable:!0})},a=(f,h,b,y)=>{if(h&&typeof h=="object"||typeof h=="function")for(let w of r(h))!n.call(f,w)&&w!==b&&e(f,w,{get:()=>h[w],enumerable:!(y=t(h,w))||y.enumerable});return f},s=f=>a(e({},"__esModule",{value:!0}),f),i={};o(i,{AccessTokenMissingError:()=>c.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>c.RefreshAccessTokenFailedError,getContext:()=>l.getContext,getVercelOidcToken:()=>u,getVercelOidcTokenSync:()=>d,getVercelToken:()=>p}),indexBrowser=s(i);var l=requireGetContext(),c=requireAuthErrors();async function u(){return""}function d(){return""}async function p(){throw new Error("getVercelToken is not supported in browser environments")}return indexBrowser}var indexBrowserExports=requireIndexBrowser(),marker$3="vercel.ai.gateway.error",symbol$3=Symbol.for(marker$3),_a$3,_b$1,GatewayError=class Vt extends(_b$1=Error,_a$3=symbol$3,_b$1){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[_a$3]=!0,this.statusCode=r,this.cause=n,this.generationId=o,this.isRetryable=a}static isInstance(t){return Vt.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&symbol$3 in t&&t[symbol$3]===!0}},name$3="GatewayAuthenticationError",marker2$2=`vercel.ai.gateway.error.${name$3}`,symbol2$2=Symbol.for(marker2$2),_a2$2,_b2$1,GatewayAuthenticationError=class Ht extends(_b2$1=GatewayError,_a2$2=symbol2$2,_b2$1){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[_a2$2]=!0,this.name=name$3,this.type="authentication_error"}static isInstance(t){return GatewayError.hasMarker(t)&&symbol2$2 in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a,generationId:s}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
|
|
560
|
-
|
|
561
|
-
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
562
|
-
|
|
563
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?i=`AI Gateway authentication failed: Invalid OIDC token.
|
|
564
|
-
|
|
565
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
566
|
-
|
|
567
|
-
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:i=`AI Gateway authentication failed: No authentication provided.
|
|
568
|
-
|
|
569
|
-
Option 1 - API key:
|
|
570
|
-
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
571
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
572
|
-
|
|
573
|
-
Option 2 - OIDC token:
|
|
574
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Ht({message:i,statusCode:o,cause:a,generationId:s})}},name2$2="GatewayInvalidRequestError",marker3$2=`vercel.ai.gateway.error.${name2$2}`,symbol3$2=Symbol.for(marker3$2),_a3$2,_b3,GatewayInvalidRequestError=class extends(_b3=GatewayError,_a3$2=symbol3$2,_b3){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[_a3$2]=!0,this.name=name2$2,this.type="invalid_request_error"}static isInstance(e){return GatewayError.hasMarker(e)&&symbol3$2 in e}},name3$2="GatewayRateLimitError",marker4$2=`vercel.ai.gateway.error.${name3$2}`,symbol4$2=Symbol.for(marker4$2),_a4$2,_b4,GatewayRateLimitError=class extends(_b4=GatewayError,_a4$2=symbol4$2,_b4){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[_a4$2]=!0,this.name=name3$2,this.type="rate_limit_exceeded"}static isInstance(e){return GatewayError.hasMarker(e)&&symbol4$2 in e}},name4$1="GatewayModelNotFoundError",marker5$1=`vercel.ai.gateway.error.${name4$1}`,symbol5$1=Symbol.for(marker5$1),modelNotFoundParamSchema=lazySchema(()=>zodSchema(object$2({modelId:string()}))),_a5$1,_b5,GatewayModelNotFoundError=class extends(_b5=GatewayError,_a5$1=symbol5$1,_b5){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[_a5$1]=!0,this.name=name4$1,this.type="model_not_found",this.modelId=r}static isInstance(e){return GatewayError.hasMarker(e)&&symbol5$1 in e}},name5$2="GatewayInternalServerError",marker6$2=`vercel.ai.gateway.error.${name5$2}`,symbol6$2=Symbol.for(marker6$2),_a6$2,_b6,GatewayInternalServerError=class extends(_b6=GatewayError,_a6$2=symbol6$2,_b6){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[_a6$2]=!0,this.name=name5$2,this.type="internal_server_error"}static isInstance(e){return GatewayError.hasMarker(e)&&symbol6$2 in e}},name6$2="GatewayFailedDependencyError",marker7$2=`vercel.ai.gateway.error.${name6$2}`,symbol7$2=Symbol.for(marker7$2),_a7$2,_b7,GatewayFailedDependencyError=class extends(_b7=GatewayError,_a7$2=symbol7$2,_b7){constructor({message:e="Failed dependency",statusCode:t=424,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[_a7$2]=!0,this.name=name6$2,this.type="failed_dependency"}static isInstance(e){return GatewayError.hasMarker(e)&&symbol7$2 in e}},name7$2="GatewayForbiddenError",marker8$1=`vercel.ai.gateway.error.${name7$2}`,symbol8$1=Symbol.for(marker8$1),_a8$1,_b8,GatewayForbiddenError=class extends(_b8=GatewayError,_a8$1=symbol8$1,_b8){constructor({message:e="Forbidden",statusCode:t=403,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[_a8$1]=!0,this.name=name7$2,this.type="forbidden"}static isInstance(e){return GatewayError.hasMarker(e)&&symbol8$1 in e}},name8="GatewayResponseError",marker9$1=`vercel.ai.gateway.error.${name8}`,symbol9$1=Symbol.for(marker9$1),_a9$1,_b9,GatewayResponseError=class extends(_b9=GatewayError,_a9$1=symbol9$1,_b9){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[_a9$1]=!0,this.name=name8,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return GatewayError.hasMarker(e)&&symbol9$1 in e}};async function createGatewayErrorFromResponse({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var a;const s=await safeValidateTypes$1({value:e,schema:gatewayErrorResponseSchema});if(!s.success){const d=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new GatewayResponseError({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:s.error,cause:n,generationId:d})}const i=s.value,l=i.error.type,c=i.error.message,u=(a=i.generationId)!=null?a:void 0;switch(l){case"authentication_error":return GatewayAuthenticationError.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new GatewayInvalidRequestError({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new GatewayRateLimitError({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const d=await safeValidateTypes$1({value:i.error.param,schema:modelNotFoundParamSchema});return new GatewayModelNotFoundError({message:c,statusCode:t,modelId:d.success?d.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new GatewayInternalServerError({message:c,statusCode:t,cause:n,generationId:u});case"failed_dependency":return new GatewayFailedDependencyError({message:c,statusCode:t,cause:n,generationId:u});case"forbidden":return new GatewayForbiddenError({message:c,statusCode:t,cause:n,generationId:u});default:return new GatewayInternalServerError({message:c,statusCode:t,cause:n,generationId:u})}}var gatewayErrorResponseSchema=lazySchema(()=>zodSchema(object$2({error:object$2({message:string(),type:string().nullish(),param:unknown().nullish(),code:union([string(),number$1()]).nullish()}),generationId:string().nullish()})));function extractApiCallResponse(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 name9$1="GatewayTimeoutError",marker10$1=`vercel.ai.gateway.error.${name9$1}`,symbol10$1=Symbol.for(marker10$1),_a10$1,_b10,GatewayTimeoutError=class Bt extends(_b10=GatewayError,_a10$1=symbol10$1,_b10){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[_a10$1]=!0,this.name=name9$1,this.type="timeout_error"}static isInstance(t){return GatewayError.hasMarker(t)&&symbol10$1 in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const a=`Gateway request timed out: ${t}
|
|
575
|
-
|
|
576
|
-
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 Bt({message:a,statusCode:r,cause:n,generationId:o})}};function isTimeoutError(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 asGatewayError(e,t){var r;return GatewayError.isInstance(e)?e:isTimeoutError(e)?GatewayTimeoutError.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):APICallError$1.isInstance(e)?e.cause&&isTimeoutError(e.cause)?GatewayTimeoutError.createTimeoutError({originalMessage:e.message,cause:e}):await createGatewayErrorFromResponse({response:extractApiCallResponse(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await createGatewayErrorFromResponse({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var GATEWAY_AUTH_METHOD_HEADER="ai-gateway-auth-method";async function parseAuthMethod(e){const t=await safeValidateTypes$1({value:e[GATEWAY_AUTH_METHOD_HEADER],schema:gatewayAuthMethodSchema});return t.success?t.value:void 0}var gatewayAuthMethodSchema=lazySchema(()=>zodSchema(union([literal("api-key"),literal("oidc")]))),KNOWN_MODEL_TYPES=["embedding","image","language","reranking","speech","transcription","video"],GatewayFetchMetadata=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await getFromApi({url:`${this.config.baseURL}/config`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler$1(gatewayAvailableModelsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await asGatewayError(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await getFromApi({url:`${e.origin}/v1/credits`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler$1(gatewayCreditsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await asGatewayError(e)}}},gatewayAvailableModelsResponseSchema=lazySchema(()=>zodSchema(object$2({models:array$1(object$2({id:string(),name:string(),description:string().nullish(),pricing:object$2({input:string(),output:string(),input_cache_read:string().nullish(),input_cache_write:string().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:object$2({specificationVersion:literal("v3"),provider:string(),modelId:string()}),modelType:string().nullish()})).transform(e=>e.filter(t=>t.modelType==null||KNOWN_MODEL_TYPES.includes(t.modelType)))}))),gatewayCreditsResponseSchema=lazySchema(()=>zodSchema(object$2({balance:string(),total_used:string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),GatewaySpendReport=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 getFromApi({url:`${t.origin}/v1/report?${r.toString()}`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler$1(gatewaySpendReportResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await asGatewayError(t)}}},gatewaySpendReportResponseSchema=lazySchema(()=>zodSchema(object$2({results:array$1(object$2({day:string().optional(),hour:string().optional(),user:string().optional(),model:string().optional(),tag:string().optional(),provider:string().optional(),credential_type:_enum(["byok","system"]).optional(),total_cost:number$1(),market_cost:number$1().optional(),input_tokens:number$1().optional(),output_tokens:number$1().optional(),cached_input_tokens:number$1().optional(),cache_creation_input_tokens:number$1().optional(),reasoning_tokens:number$1().optional(),request_count:number$1().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:s,reasoning_tokens:i,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}:{},...s!==void 0?{cacheCreationInputTokens:s}:{},...i!==void 0?{reasoningTokens:i}:{},...l!==void 0?{requestCount:l}:{}})))}))),GatewayGenerationInfoFetcher=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await getFromApi({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler$1(gatewayGenerationInfoResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await asGatewayError(t)}}},gatewayGenerationInfoResponseSchema=lazySchema(()=>zodSchema(object$2({data:object$2({id:string(),total_cost:number$1(),upstream_inference_cost:number$1(),usage:number$1(),created_at:string(),model:string(),is_byok:boolean(),provider_name:string(),streamed:boolean(),finish_reason:string(),latency:number$1(),generation_time:number$1(),native_tokens_prompt:number$1(),native_tokens_completion:number$1(),native_tokens_reasoning:number$1(),native_tokens_cached:number$1(),native_tokens_cache_creation:number$1(),billable_web_search_calls:number$1()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:a,generation_time:s,native_tokens_prompt:i,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:d,billable_web_search_calls:p,...f})=>({...f,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:a,generationTime:s,promptTokens:i,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:d,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),GatewayLanguageModel=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 resolve(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:i}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await resolve(this.config.o11yHeaders)),body:t,successfulResponseHandler:createJsonResponseHandler$1(any()),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...s,request:{body:t},response:{headers:a,body:i},warnings:r}}catch(a){throw await asGatewayError(a,await parseAuthMethod(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await resolve(this.config.headers());try{const{value:a,responseHeaders:s}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await resolve(this.config.o11yHeaders)),body:t,successfulResponseHandler:createEventSourceResponseHandler$1(any()),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.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(i.error)}})),request:{body:t},response:{headers:s}}}catch(a){throw await asGatewayError(a,await parseAuthMethod(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)}}},GatewayEmbeddingModel=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 s=await resolve(this.config.headers());try{const{responseHeaders:i,value:l,rawValue:c}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(s,t??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:createJsonResponseHandler$1(gatewayEmbeddingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),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:i,body:c},warnings:(a=l.warnings)!=null?a:[]}}catch(i){throw await asGatewayError(i,await parseAuthMethod(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},gatewayEmbeddingWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewayEmbeddingResponseSchema=lazySchema(()=>zodSchema(object$2({embeddings:array$1(array$1(number$1())),usage:object$2({tokens:number$1()}).nullish(),warnings:array$1(gatewayEmbeddingWarningSchema).optional(),providerMetadata:record(string(),record(string(),unknown())).optional()}))),GatewayImageModel=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:s,providerOptions:i,headers:l,abortSignal:c}){var u,d,p,f;const h=await resolve(this.config.headers());try{const{responseHeaders:b,value:y,rawValue:w}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(h,l??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...a&&{files:a.map(g=>maybeEncodeImageFile(g))},...s&&{mask:maybeEncodeImageFile(s)}},successfulResponseHandler:createJsonResponseHandler$1(gatewayImageResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:g=>g}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(u=y.warnings)!=null?u:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:b},...y.usage!=null&&{usage:{inputTokens:(d=y.usage.inputTokens)!=null?d:void 0,outputTokens:(p=y.usage.outputTokens)!=null?p:void 0,totalTokens:(f=y.usage.totalTokens)!=null?f:void 0}}}}catch(b){throw await asGatewayError(b,await parseAuthMethod(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function maybeEncodeImageFile(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:convertUint8ArrayToBase64$1(e.data)}:e}var providerMetadataEntrySchema=object$2({images:array$1(unknown()).optional()}).catchall(unknown()),gatewayImageWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewayImageUsageSchema=object$2({inputTokens:number$1().nullish(),outputTokens:number$1().nullish(),totalTokens:number$1().nullish()}),gatewayImageResponseSchema=object$2({images:array$1(string()),warnings:array$1(gatewayImageWarningSchema).optional(),providerMetadata:record(string(),providerMetadataEntrySchema).optional(),usage:gatewayImageUsageSchema.optional()}),GatewayVideoModel=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:s,generateAudio:i,image:l,providerOptions:c,headers:u,abortSignal:d}){var p;const f=await resolve(this.config.headers());try{const{responseHeaders:h,value:b}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(f,u??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...a&&{fps:a},...s&&{seed:s},...i!==void 0&&{generateAudio:i},...c&&{providerOptions:c},...l&&{image:maybeEncodeVideoFile(l)}},successfulResponseHandler:async({response:y,url:w,requestBodyValues:g})=>{if(y.body==null)throw new APICallError$1({message:"SSE response body is empty",url:w,requestBodyValues:g,statusCode:y.status});const S=parseJsonEventStream$1({stream:y.body,schema:gatewayVideoEventSchema}).getReader(),{done:v,value:_}=await S.read();if(S.releaseLock(),v||!_)throw new APICallError$1({message:"SSE stream ended without a data event",url:w,requestBodyValues:g,statusCode:y.status});if(!_.success)throw new APICallError$1({message:"Failed to parse video SSE event",cause:_.error,url:w,requestBodyValues:g,statusCode:y.status});const $=_.value;if($.type==="error")throw new APICallError$1({message:$.message,statusCode:$.statusCode,url:w,requestBodyValues:g,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify($),data:{error:{message:$.message,type:$.errorType,param:$.param}}});return{value:{videos:$.videos,warnings:$.warnings,providerMetadata:$.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:y=>y}),...d&&{abortSignal:d},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:h}}}catch(h){throw await asGatewayError(h,await parseAuthMethod(f))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function maybeEncodeVideoFile(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:convertUint8ArrayToBase64$1(e.data)}:e}var providerMetadataEntrySchema2=object$2({videos:array$1(unknown()).optional()}).catchall(unknown()),gatewayVideoDataSchema=union([object$2({type:literal("url"),url:string(),mediaType:string()}),object$2({type:literal("base64"),data:string(),mediaType:string()})]),gatewayVideoWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewayVideoEventSchema=discriminatedUnion("type",[object$2({type:literal("result"),videos:array$1(gatewayVideoDataSchema),warnings:array$1(gatewayVideoWarningSchema).optional(),providerMetadata:record(string(),providerMetadataEntrySchema2).optional()}),object$2({type:literal("error"),message:string(),errorType:string(),statusCode:number$1(),param:unknown().nullable()})]),GatewayRerankingModel=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 s;const i=await resolve(this.config.headers());try{const{responseHeaders:l,value:c,rawValue:u}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(i,n??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{documents:e,query:t,...r!=null?{topN:r}:{},...a?{providerOptions:a}:{}},successfulResponseHandler:createJsonResponseHandler$1(gatewayRerankingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:d=>d}),...o&&{abortSignal:o},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:l,body:u},warnings:(s=c.warnings)!=null?s:[]}}catch(l){throw await asGatewayError(l,await parseAuthMethod(i))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},gatewayRerankingWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewayRerankingResponseSchema=lazySchema(()=>zodSchema(object$2({ranking:array$1(object$2({index:number$1(),relevanceScore:number$1()})),warnings:array$1(gatewayRerankingWarningSchema).optional(),providerMetadata:record(string(),record(string(),unknown())).optional()}))),GatewaySpeechModel=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:s,headers:i,abortSignal:l}){var c;const u=await resolve(this.config.headers());try{const{responseHeaders:d,value:p,rawValue:f}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(u,i??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{text:e,...t&&{voice:t},...r&&{outputFormat:r},...n&&{instructions:n},...o!=null&&{speed:o},...a&&{language:a},...s&&{providerOptions:s}},successfulResponseHandler:createJsonResponseHandler$1(gatewaySpeechResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:h=>h}),...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:d,body:f}}}catch(d){throw await asGatewayError(d,await parseAuthMethod(u??{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"3","ai-model-id":this.modelId}}},providerMetadataEntrySchema3=object$2({}).catchall(unknown()),gatewaySpeechWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewaySpeechResponseSchema=object$2({audio:string(),warnings:array$1(gatewaySpeechWarningSchema).optional(),providerMetadata:record(string(),providerMetadataEntrySchema3).optional()}),GatewayTranscriptionModel=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,s,i,l;const c=await resolve(this.config.headers());try{const{responseHeaders:u,value:d,rawValue:p}=await postJsonToApi$1({url:this.getUrl(),headers:combineHeaders$1(c,n??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{audio:e instanceof Uint8Array?convertUint8ArrayToBase64$1(e):e,mediaType:t,...r&&{providerOptions:r}},successfulResponseHandler:createJsonResponseHandler$1(gatewayTranscriptionResponseSchema),failedResponseHandler:createJsonErrorResponseHandler$1({errorSchema:any(),errorToMessage:f=>f}),...o&&{abortSignal:o},fetch:this.config.fetch});return{text:d.text,segments:(a=d.segments)!=null?a:[],language:(s=d.language)!=null?s:void 0,durationInSeconds:(i=d.durationInSeconds)!=null?i:void 0,warnings:(l=d.warnings)!=null?l:[],providerMetadata:d.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u,body:p}}}catch(u){throw await asGatewayError(u,await parseAuthMethod(c??{}))}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"3","ai-model-id":this.modelId}}},providerMetadataEntrySchema4=object$2({}).catchall(unknown()),gatewayTranscriptionWarningSchema=discriminatedUnion("type",[object$2({type:literal("unsupported"),feature:string(),details:string().optional()}),object$2({type:literal("compatibility"),feature:string(),details:string().optional()}),object$2({type:literal("other"),message:string()})]),gatewayTranscriptionResponseSchema=object$2({text:string(),segments:array$1(object$2({text:string(),startSecond:number$1(),endSecond:number$1()})).optional(),language:string().nullish(),durationInSeconds:number$1().nullish(),warnings:array$1(gatewayTranscriptionWarningSchema).optional(),providerMetadata:record(string(),providerMetadataEntrySchema4).optional()}),exaSearchInputSchema=lazySchema(()=>zodSchema(objectType({query:stringType().describe("Natural-language web search query. This is required."),type:enumType(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:numberType().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:enumType(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:stringType().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:arrayType(stringType()).optional().describe("Only return results from these domains."),exclude_domains:arrayType(stringType()).optional().describe("Exclude results from these domains."),start_published_date:stringType().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:stringType().optional().describe("Only return links published before this ISO 8601 date."),contents:objectType({text:unionType([booleanType(),objectType({max_characters:numberType().optional(),include_html_tags:booleanType().optional(),verbosity:enumType(["compact","standard","full"]).optional(),include_sections:arrayType(enumType(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:arrayType(enumType(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:unionType([booleanType(),objectType({query:stringType().optional(),max_characters:numberType().optional()})]).optional(),max_age_hours:numberType().optional(),livecrawl_timeout:numberType().optional(),subpages:numberType().optional(),subpage_target:unionType([stringType(),arrayType(stringType())]).optional(),extras:objectType({links:numberType().optional(),image_links:numberType().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}))),exaSearchOutputSchema=lazySchema(()=>zodSchema(unionType([objectType({requestId:stringType(),searchType:stringType().optional(),resolvedSearchType:stringType().optional(),results:arrayType(objectType({title:stringType(),url:stringType(),id:stringType(),publishedDate:stringType().nullable().optional(),author:stringType().nullable().optional(),image:stringType().nullable().optional(),favicon:stringType().nullable().optional(),text:stringType().optional(),highlights:arrayType(stringType()).optional(),highlightScores:arrayType(numberType()).optional(),summary:stringType().optional(),subpages:arrayType(anyType()).optional(),extras:objectType({links:arrayType(stringType()).optional(),imageLinks:arrayType(stringType()).optional()}).optional()})),costDollars:objectType({total:numberType().optional(),search:recordType(numberType()).optional()}).optional()}),objectType({error:enumType(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:numberType().optional(),message:stringType()})]))),exaSearchToolFactory=createProviderToolFactoryWithOutputSchema({id:"gateway.exa_search",inputSchema:exaSearchInputSchema,outputSchema:exaSearchOutputSchema}),exaSearch=(e={})=>exaSearchToolFactory(e),parallelSearchInputSchema=lazySchema(()=>zodSchema(objectType({objective:stringType().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:arrayType(stringType()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:enumType(["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:numberType().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:objectType({include_domains:arrayType(stringType()).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:arrayType(stringType()).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:stringType().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:objectType({max_chars_per_result:numberType().optional().describe("Maximum characters per result."),max_chars_total:numberType().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:objectType({max_age_seconds:numberType().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.")}))),parallelSearchOutputSchema=lazySchema(()=>zodSchema(unionType([objectType({searchId:stringType(),results:arrayType(objectType({url:stringType(),title:stringType(),excerpt:stringType(),publishDate:stringType().nullable().optional(),relevanceScore:numberType().optional()}))}),objectType({error:enumType(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:numberType().optional(),message:stringType()})]))),parallelSearchToolFactory=createProviderToolFactoryWithOutputSchema({id:"gateway.parallel_search",inputSchema:parallelSearchInputSchema,outputSchema:parallelSearchOutputSchema}),parallelSearch=(e={})=>parallelSearchToolFactory(e),perplexitySearchInputSchema=lazySchema(()=>zodSchema(objectType({query:unionType([stringType(),arrayType(stringType())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:numberType().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:numberType().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:numberType().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:stringType().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:arrayType(stringType()).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:arrayType(stringType()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:stringType().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:stringType().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:stringType().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:stringType().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:enumType(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),perplexitySearchOutputSchema=lazySchema(()=>zodSchema(unionType([objectType({results:arrayType(objectType({title:stringType(),url:stringType(),snippet:stringType(),date:stringType().optional(),lastUpdated:stringType().optional()})),id:stringType()}),objectType({error:enumType(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:numberType().optional(),message:stringType()})]))),perplexitySearchToolFactory=createProviderToolFactoryWithOutputSchema({id:"gateway.perplexity_search",inputSchema:perplexitySearchInputSchema,outputSchema:perplexitySearchOutputSchema}),perplexitySearch=(e={})=>perplexitySearchToolFactory(e),gatewayTools={exaSearch,parallelSearch,perplexitySearch};async function getVercelRequestId(){var e;return(e=indexBrowserExports.getContext().headers)==null?void 0:e["x-vercel-id"]}var VERSION$6="3.0.140",AI_GATEWAY_PROTOCOL_VERSION="0.0.1";function createGatewayProvider(e={}){var t,r;let n=null,o=null;const a=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let s=0;const i=(r=withoutTrailingSlash$1(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const S=await getGatewayAuthToken(e);return withUserAgentSuffix$1({Authorization:`Bearer ${S.token}`,"ai-gateway-protocol-version":AI_GATEWAY_PROTOCOL_VERSION,[GATEWAY_AUTH_METHOD_HEADER]:S.authMethod,...e.headers},`ai-sdk/gateway/${VERSION$6}`)}catch(S){throw GatewayAuthenticationError.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:S})}},c=()=>{const S=loadOptionalSetting({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=loadOptionalSetting({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=loadOptionalSetting({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),$=loadOptionalSetting({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const T=await getVercelRequestId();return{...S&&{"ai-o11y-deployment-id":S},...v&&{"ai-o11y-environment":v},..._&&{"ai-o11y-region":_},...T&&{"ai-o11y-request-id":T},...$&&{"ai-o11y-project-id":$}}}},u=S=>new GatewayLanguageModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),d=async()=>{var S,v,_;const $=(_=(v=(S=e._internal)==null?void 0:S.currentDate)==null?void 0:v.call(S).getTime())!=null?_:Date.now();return(!n||$-s>a)&&(s=$,n=new GatewayFetchMetadata({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(T=>(o=T,T)).catch(async T=>{throw await asGatewayError(T,await parseAuthMethod(await l()))})),o?Promise.resolve(o):n},p=async()=>new GatewayFetchMetadata({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async S=>{throw await asGatewayError(S,await parseAuthMethod(await l()))}),f=async S=>new GatewaySpendReport({baseURL:i,headers:l,fetch:e.fetch}).getSpendReport(S).catch(async v=>{throw await asGatewayError(v,await parseAuthMethod(await l()))}),h=async S=>new GatewayGenerationInfoFetcher({baseURL:i,headers:l,fetch:e.fetch}).getGenerationInfo(S).catch(async v=>{throw await asGatewayError(v,await parseAuthMethod(await l()))}),b=function(S){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(S)};b.specificationVersion="v3",b.getAvailableModels=d,b.getCredits=p,b.getSpendReport=f,b.getGenerationInfo=h,b.imageModel=S=>new GatewayImageModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),b.languageModel=u;const y=S=>new GatewayEmbeddingModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});b.embeddingModel=y,b.textEmbeddingModel=y,b.videoModel=S=>new GatewayVideoModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});const w=S=>new GatewayRerankingModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});b.rerankingModel=w,b.reranking=w;const g=S=>new GatewaySpeechModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});b.speechModel=g,b.speech=g;const m=S=>new GatewayTranscriptionModel(S,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return b.transcriptionModel=m,b.transcription=m,b.chat=b.languageModel,b.embedding=b.embeddingModel,b.image=b.imageModel,b.video=b.videoModel,b.tools=gatewayTools,b}var gateway=createGatewayProvider();async function getGatewayAuthToken(e){const t=loadOptionalSetting({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await indexBrowserExports.getVercelOidcToken(),authMethod:"oidc"}}const VERSION$5="1.9.1",re=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){const t=new Set([e]),r=new Set,n=e.match(re);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(i){return r.add(i),!1}function s(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;const c=l.match(re);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?s(l):a(l):o.minor<=u.minor?s(l):a(l)}}const isCompatible=_makeCompatibilityCheck(VERSION$5),major=VERSION$5.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for(`opentelemetry.js.api.${major}`),_global=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function registerGlobal(e,t,r,n=!1){var o;const a=_global[GLOBAL_OPENTELEMETRY_API_KEY]=(o=_global[GLOBAL_OPENTELEMETRY_API_KEY])!==null&&o!==void 0?o:{version:VERSION$5};if(!n&&a[e]){const s=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(s.stack||s.message),!1}if(a.version!==VERSION$5){const s=new Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${VERSION$5}`);return r.error(s.stack||s.message),!1}return a[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${VERSION$5}.`),!0}function getGlobal(e){var t,r;const n=(t=_global[GLOBAL_OPENTELEMETRY_API_KEY])===null||t===void 0?void 0:t.version;if(!(!n||!isCompatible(n)))return(r=_global[GLOBAL_OPENTELEMETRY_API_KEY])===null||r===void 0?void 0:r[e]}function unregisterGlobal(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${VERSION$5}.`);const r=_global[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}class DiagComponentLogger{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return logProxy("debug",this._namespace,t)}error(...t){return logProxy("error",this._namespace,t)}info(...t){return logProxy("info",this._namespace,t)}warn(...t){return logProxy("warn",this._namespace,t)}verbose(...t){return logProxy("verbose",this._namespace,t)}}function logProxy(e,t,r){const n=getGlobal("diag");if(n)return n[e](t,...r)}var DiagLogLevel;(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"})(DiagLogLevel||(DiagLogLevel={}));function createLogLevelDiagLogger(e,t){e<DiagLogLevel.NONE?e=DiagLogLevel.NONE:e>DiagLogLevel.ALL&&(e=DiagLogLevel.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",DiagLogLevel.ERROR),warn:r("warn",DiagLogLevel.WARN),info:r("info",DiagLogLevel.INFO),debug:r("debug",DiagLogLevel.DEBUG),verbose:r("verbose",DiagLogLevel.VERBOSE)}}const API_NAME$4="diag";class DiagAPI{static instance(){return this._instance||(this._instance=new DiagAPI),this._instance}constructor(){function t(o){return function(...a){const s=getGlobal("diag");if(s)return s[o](...a)}}const r=this,n=(o,a={logLevel:DiagLogLevel.INFO})=>{var s,i,l;if(o===r){const d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((s=d.stack)!==null&&s!==void 0?s:d.message),!1}typeof a=="number"&&(a={logLevel:a});const c=getGlobal("diag"),u=createLogLevelDiagLogger((i=a.logLevel)!==null&&i!==void 0?i:DiagLogLevel.INFO,o);if(c&&!a.suppressOverrideMessage){const d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return registerGlobal("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{unregisterGlobal(API_NAME$4,r)},r.createComponentLogger=o=>new DiagComponentLogger(o),r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}}class BaggageImpl{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 BaggageImpl(this._entries);return n._entries.set(t,r),n}removeEntry(t){const r=new BaggageImpl(this._entries);return r._entries.delete(t),r}removeEntries(...t){const r=new BaggageImpl(this._entries);for(const n of t)r._entries.delete(n);return r}clear(){return new BaggageImpl}}DiagAPI.instance();function createBaggage(e={}){return new BaggageImpl(new Map(Object.entries(e)))}function createContextKey(e){return Symbol.for(e)}class BaseContext{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 BaseContext(r._currentContext);return a._currentContext.set(n,o),a},r.deleteValue=n=>{const o=new BaseContext(r._currentContext);return o._currentContext.delete(n),o}}}const ROOT_CONTEXT=new BaseContext;class NoopMeter{constructor(){}createGauge(t,r){return NOOP_GAUGE_METRIC}createHistogram(t,r){return NOOP_HISTOGRAM_METRIC}createCounter(t,r){return NOOP_COUNTER_METRIC}createUpDownCounter(t,r){return NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(t,r){return NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(t,r){return NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(t,r){return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(t,r){}removeBatchObservableCallback(t){}}class NoopMetric{}class NoopCounterMetric extends NoopMetric{add(t,r){}}class NoopUpDownCounterMetric extends NoopMetric{add(t,r){}}class NoopGaugeMetric extends NoopMetric{record(t,r){}}class NoopHistogramMetric extends NoopMetric{record(t,r){}}class NoopObservableMetric{addCallback(t){}removeCallback(t){}}class NoopObservableCounterMetric extends NoopObservableMetric{}class NoopObservableGaugeMetric extends NoopObservableMetric{}class NoopObservableUpDownCounterMetric extends NoopObservableMetric{}const NOOP_METER=new NoopMeter,NOOP_COUNTER_METRIC=new NoopCounterMetric,NOOP_GAUGE_METRIC=new NoopGaugeMetric,NOOP_HISTOGRAM_METRIC=new NoopHistogramMetric,NOOP_UP_DOWN_COUNTER_METRIC=new NoopUpDownCounterMetric,NOOP_OBSERVABLE_COUNTER_METRIC=new NoopObservableCounterMetric,NOOP_OBSERVABLE_GAUGE_METRIC=new NoopObservableGaugeMetric,NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new NoopObservableUpDownCounterMetric,defaultTextMapGetter={get(e,t){if(e!=null)return e[t]},keys(e){return e==null?[]:Object.keys(e)}},defaultTextMapSetter={set(e,t,r){e!=null&&(e[t]=r)}};class NoopContextManager{active(){return ROOT_CONTEXT}with(t,r,n,...o){return r.call(n,...o)}bind(t,r){return r}enable(){return this}disable(){return this}}const API_NAME$3="context",NOOP_CONTEXT_MANAGER=new NoopContextManager;class ContextAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new ContextAPI),this._instance}setGlobalContextManager(t){return registerGlobal(API_NAME$3,t,DiagAPI.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 getGlobal(API_NAME$3)||NOOP_CONTEXT_MANAGER}disable(){this._getContextManager().disable(),unregisterGlobal(API_NAME$3,DiagAPI.instance())}}var TraceFlags;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(TraceFlags||(TraceFlags={}));const INVALID_SPANID="0000000000000000",INVALID_TRACEID="00000000000000000000000000000000",INVALID_SPAN_CONTEXT={traceId:INVALID_TRACEID,spanId:INVALID_SPANID,traceFlags:TraceFlags.NONE};class NonRecordingSpan{constructor(t=INVALID_SPAN_CONTEXT){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 SPAN_KEY=createContextKey("OpenTelemetry Context Key SPAN");function getSpan(e){return e.getValue(SPAN_KEY)||void 0}function getActiveSpan(){return getSpan(ContextAPI.getInstance().active())}function setSpan(e,t){return e.setValue(SPAN_KEY,t)}function deleteSpan(e){return e.deleteValue(SPAN_KEY)}function setSpanContext(e,t){return setSpan(e,new NonRecordingSpan(t))}function getSpanContext(e){var t;return(t=getSpan(e))===null||t===void 0?void 0:t.spanContext()}const isHex=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 isValidHex(e,t){if(typeof e!="string"||e.length!==t)return!1;let r=0;for(let n=0;n<e.length;n+=4)r+=(isHex[e.charCodeAt(n)]|0)+(isHex[e.charCodeAt(n+1)]|0)+(isHex[e.charCodeAt(n+2)]|0)+(isHex[e.charCodeAt(n+3)]|0);return r===t}function isValidTraceId(e){return isValidHex(e,32)&&e!==INVALID_TRACEID}function isValidSpanId(e){return isValidHex(e,16)&&e!==INVALID_SPANID}function isSpanContextValid(e){return isValidTraceId(e.traceId)&&isValidSpanId(e.spanId)}function wrapSpanContext(e){return new NonRecordingSpan(e)}const contextApi=ContextAPI.getInstance();class NoopTracer{startSpan(t,r,n=contextApi.active()){if(!!r?.root)return new NonRecordingSpan;const a=n&&getSpanContext(n);return isSpanContext(a)&&isSpanContextValid(a)?new NonRecordingSpan(a):new NonRecordingSpan}startActiveSpan(t,r,n,o){let a,s,i;if(arguments.length<2)return;arguments.length===2?i=r:arguments.length===3?(a=r,i=n):(a=r,s=n,i=o);const l=s??contextApi.active(),c=this.startSpan(t,a,l),u=setSpan(l,c);return contextApi.with(u,i,void 0,c)}}function isSpanContext(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 NOOP_TRACER=new NoopTracer;class ProxyTracer{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):NOOP_TRACER}}class NoopTracerProvider{getTracer(t,r,n){return new NoopTracer}}const NOOP_TRACER_PROVIDER=new NoopTracerProvider;class ProxyTracerProvider{getTracer(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new ProxyTracer(this,t,r,n)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:NOOP_TRACER_PROVIDER}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 SpanStatusCode;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(SpanStatusCode||(SpanStatusCode={}));const context=ContextAPI.getInstance();DiagAPI.instance();class NoopMeterProvider{getMeter(t,r,n){return NOOP_METER}}const NOOP_METER_PROVIDER=new NoopMeterProvider,API_NAME$2="metrics";class MetricsAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new MetricsAPI),this._instance}setGlobalMeterProvider(t){return registerGlobal(API_NAME$2,t,DiagAPI.instance())}getMeterProvider(){return getGlobal(API_NAME$2)||NOOP_METER_PROVIDER}getMeter(t,r,n){return this.getMeterProvider().getMeter(t,r,n)}disable(){unregisterGlobal(API_NAME$2,DiagAPI.instance())}}MetricsAPI.getInstance();class NoopTextMapPropagator{inject(t,r){}extract(t,r){return t}fields(){return[]}}const BAGGAGE_KEY=createContextKey("OpenTelemetry Baggage Key");function getBaggage(e){return e.getValue(BAGGAGE_KEY)||void 0}function getActiveBaggage(){return getBaggage(ContextAPI.getInstance().active())}function setBaggage(e,t){return e.setValue(BAGGAGE_KEY,t)}function deleteBaggage(e){return e.deleteValue(BAGGAGE_KEY)}const API_NAME$1="propagation",NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator;class PropagationAPI{constructor(){this.createBaggage=createBaggage,this.getBaggage=getBaggage,this.getActiveBaggage=getActiveBaggage,this.setBaggage=setBaggage,this.deleteBaggage=deleteBaggage}static getInstance(){return this._instance||(this._instance=new PropagationAPI),this._instance}setGlobalPropagator(t){return registerGlobal(API_NAME$1,t,DiagAPI.instance())}inject(t,r,n=defaultTextMapSetter){return this._getGlobalPropagator().inject(t,r,n)}extract(t,r,n=defaultTextMapGetter){return this._getGlobalPropagator().extract(t,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){unregisterGlobal(API_NAME$1,DiagAPI.instance())}_getGlobalPropagator(){return getGlobal(API_NAME$1)||NOOP_TEXT_MAP_PROPAGATOR}}PropagationAPI.getInstance();const API_NAME="trace";class TraceAPI{constructor(){this._proxyTracerProvider=new ProxyTracerProvider,this.wrapSpanContext=wrapSpanContext,this.isSpanContextValid=isSpanContextValid,this.deleteSpan=deleteSpan,this.getSpan=getSpan,this.getActiveSpan=getActiveSpan,this.getSpanContext=getSpanContext,this.setSpan=setSpan,this.setSpanContext=setSpanContext}static getInstance(){return this._instance||(this._instance=new TraceAPI),this._instance}setGlobalTracerProvider(t){const r=registerGlobal(API_NAME,this._proxyTracerProvider,DiagAPI.instance());return r&&this._proxyTracerProvider.setDelegate(t),r}getTracerProvider(){return getGlobal(API_NAME)||this._proxyTracerProvider}getTracer(t,r){return this.getTracerProvider().getTracer(t,r)}disable(){unregisterGlobal(API_NAME,DiagAPI.instance()),this._proxyTracerProvider=new ProxyTracerProvider}}const trace=TraceAPI.getInstance();var __defProp=Object.defineProperty,__export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},name$2="AI_InvalidArgumentError",marker$2=`vercel.ai.error.${name$2}`,symbol$2=Symbol.for(marker$2),_a$2,InvalidArgumentError$1=class extends AISDKError$1{constructor({parameter:t,value:r,message:n}){super({name:name$2,message:`Invalid argument for parameter ${t}: ${n}`}),this[_a$2]=!0,this.parameter=t,this.value=r}static isInstance(t){return AISDKError$1.hasMarker(t,marker$2)}};_a$2=symbol$2;var name3$1="AI_InvalidToolApprovalError",marker3$1=`vercel.ai.error.${name3$1}`,symbol3$1=Symbol.for(marker3$1),_a3$1,InvalidToolApprovalError=class extends AISDKError$1{constructor({approvalId:e}){super({name:name3$1,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[_a3$1]=!0,this.approvalId=e}static isInstance(e){return AISDKError$1.hasMarker(e,marker3$1)}};_a3$1=symbol3$1;var name4="AI_InvalidToolApprovalSignatureError",marker4$1=`vercel.ai.error.${name4}`,symbol4$1=Symbol.for(marker4$1),_a4$1,InvalidToolApprovalSignatureError=class extends AISDKError$1{constructor({approvalId:e,toolCallId:t,reason:r}){super({name:name4,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${r}`}),this[_a4$1]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker4$1)}};_a4$1=symbol4$1;var name5$1="AI_InvalidToolInputError",marker5=`vercel.ai.error.${name5$1}`,symbol5=Symbol.for(marker5),_a5,InvalidToolInputError=class extends AISDKError$1{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${getErrorMessage$2(r)}`}){super({name:name5$1,message:n,cause:r}),this[_a5]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker5)}};_a5=symbol5;var name6$1="AI_ToolCallNotFoundForApprovalError",marker6$1=`vercel.ai.error.${name6$1}`,symbol6$1=Symbol.for(marker6$1),_a6$1,ToolCallNotFoundForApprovalError=class extends AISDKError$1{constructor({toolCallId:e,approvalId:t}){super({name:name6$1,message:`Tool call "${e}" not found for approval request "${t}".`}),this[_a6$1]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker6$1)}};_a6$1=symbol6$1;var name7$1="AI_MissingToolResultsError",marker7$1=`vercel.ai.error.${name7$1}`,symbol7$1=Symbol.for(marker7$1),_a7$1,MissingToolResultsError=class extends AISDKError$1{constructor({toolCallIds:e}){super({name:name7$1,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[_a7$1]=!0,this.toolCallIds=e}static isInstance(e){return AISDKError$1.hasMarker(e,marker7$1)}};_a7$1=symbol7$1;var name9="AI_NoObjectGeneratedError",marker9=`vercel.ai.error.${name9}`,symbol9=Symbol.for(marker9),_a9,NoObjectGeneratedError=class extends AISDKError$1{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:a}){super({name:name9,message:e,cause:t}),this[_a9]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=a}static isInstance(e){return AISDKError$1.hasMarker(e,marker9)}};_a9=symbol9;var name10$1="AI_NoOutputGeneratedError",marker10=`vercel.ai.error.${name10$1}`,symbol10=Symbol.for(marker10),_a10,NoOutputGeneratedError=class extends AISDKError$1{constructor({message:e="No output generated.",cause:t}={}){super({name:name10$1,message:e,cause:t}),this[_a10]=!0}static isInstance(e){return AISDKError$1.hasMarker(e,marker10)}};_a10=symbol10;var name14="AI_NoSuchToolError",marker14$1=`vercel.ai.error.${name14}`,symbol14$1=Symbol.for(marker14$1),_a14$1,NoSuchToolError=class extends AISDKError$1{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:name14,message:r}),this[_a14$1]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker14$1)}};_a14$1=symbol14$1;var name15="AI_ToolCallRepairError",marker15=`vercel.ai.error.${name15}`,symbol15=Symbol.for(marker15),_a15,ToolCallRepairError=class extends AISDKError$1{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${getErrorMessage$2(e)}`}){super({name:name15,message:r,cause:e}),this[_a15]=!0,this.originalError=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker15)}};_a15=symbol15;var UnsupportedModelVersionError=class extends AISDKError$1{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}},name16="AI_UIMessageStreamError",marker16=`vercel.ai.error.${name16}`,symbol16=Symbol.for(marker16),_a16,UIMessageStreamError=class extends AISDKError$1{constructor({chunkType:e,chunkId:t,message:r}){super({name:name16,message:r}),this[_a16]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return AISDKError$1.hasMarker(e,marker16)}};_a16=symbol16;var name18="AI_InvalidMessageRoleError",marker18=`vercel.ai.error.${name18}`,symbol18=Symbol.for(marker18),_a18,InvalidMessageRoleError=class extends AISDKError$1{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:name18,message:t}),this[_a18]=!0,this.role=e}static isInstance(e){return AISDKError$1.hasMarker(e,marker18)}};_a18=symbol18;var name20="AI_RetryError",marker20=`vercel.ai.error.${name20}`,symbol20=Symbol.for(marker20),_a20,RetryError=class extends AISDKError$1{constructor({message:e,reason:t,errors:r}){super({name:name20,message:e}),this[_a20]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return AISDKError$1.hasMarker(e,marker20)}};_a20=symbol20;function asArray(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function notify(e){for(const t of asArray(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function formatWarning({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 FIRST_WARNING_INFO_MESSAGE="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",hasLoggedBefore=!1,logWarnings=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}hasLoggedBefore||(hasLoggedBefore=!0,console.info(FIRST_WARNING_INFO_MESSAGE));for(const r of e.warnings)console.warn(formatWarning({warning:r,provider:e.provider,model:e.model}))}};function logV2CompatibilityWarning({provider:e,modelId:t}){logWarnings({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function asLanguageModelV3(e){return e.specificationVersion==="v3"?e:(logV2CompatibilityWarning({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:convertV2FinishReasonToV3(o.finishReason),usage:convertV2UsageToV3(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:convertV2StreamToV3(o.stream)}};default:return t[r]}}}))}function convertV2StreamToV3(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:convertV2FinishReasonToV3(t.finishReason),usage:convertV2UsageToV3(t.usage)});break;default:r.enqueue(t);break}}}))}function convertV2FinishReasonToV3(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function convertV2UsageToV3(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 resolveLanguageModel(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new UnsupportedModelVersionError({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return asLanguageModelV3(e)}return getGlobalProvider().languageModel(e)}function getGlobalProvider(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:gateway}function getTotalTimeoutMs(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function getStepTimeoutMs(e){if(!(e==null||typeof e=="number"))return e.stepMs}function getChunkTimeoutMs(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var imageMediaTypeSignatures=[{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]}],stripID3=e=>{const t=typeof e=="string"?convertBase64ToUint8Array(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function stripID3TagsIfPresent(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?stripID3(e):e}function detectMediaType({data:e,signatures:t}){const r=stripID3TagsIfPresent(e),n=typeof r=="string"?convertBase64ToUint8Array(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((a,s)=>a===null||n[s]===a))return o.mediaType}var VERSION$4="6.0.216",download=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const a=withUserAgentSuffix$1({},`ai-sdk/${VERSION$4}`,getRuntimeEnvironmentUserAgent$1()),s=await fetchWithValidatedRedirects({url:o,headers:a,abortSignal:r});if(!s.ok)throw await cancelResponseBody(s),new DownloadError({url:o,statusCode:s.status,statusText:s.statusText});return{data:await readResponseWithSizeLimit({response:s,url:o,maxBytes:t??DEFAULT_MAX_DOWNLOAD_SIZE}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(a){throw DownloadError.isInstance(a)?a:new DownloadError({url:o,cause:a})}},createDefaultDownloadFunction=(e=download)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function splitDataUrl(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 dataContentSchema=union([string(),_instanceof(Uint8Array),_instanceof(ArrayBuffer),custom(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function convertToLanguageModelV3DataContent(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}=splitDataUrl(e.toString());if(t==null||r==null)throw new AISDKError$1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function convertDataContentToBase64String(e){return typeof e=="string"?e:e instanceof ArrayBuffer?convertUint8ArrayToBase64$1(new Uint8Array(e)):convertUint8ArrayToBase64$1(e)}async function convertToLanguageModelPrompt({prompt:e,supportedUrls:t,download:r=createDefaultDownloadFunction()}){const n=await downloadAssets(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 d=o.get(u.approvalId);d&&a.add(d)}}const s=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:asArray(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>convertToLanguageModelMessage({message:c,downloadedAssets:n}))],i=[];for(const c of s){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)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 MissingToolResultsError({toolCallIds:Array.from(l)});break}for(const c of a)l.delete(c);if(l.size>0)throw new MissingToolResultsError({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function convertToLanguageModelMessage({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=>convertPartToLanguageModelPart(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:s}=convertToLanguageModelV3DataContent(n.data);return{type:"file",data:a,filename:n.filename,mediaType:s??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:mapToolResultOutput({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:mapToolResultOutput({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 InvalidMessageRoleError({role:n})}}}async function downloadAssets(e,t,r){var n;const o=[];for(const i of e){if(i.role==="user"&&Array.isArray(i.content))for(const l of i.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(i.role==="tool"||i.role==="assistant"){if(!Array.isArray(i.content))continue;for(const l of i.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(i=>{const l=i.mediaType,{data:c}=convertToLanguageModelV3DataContent(i.data);return{mediaType:l,data:c}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&isUrlSupported({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:r})})),s=await t(a);return Object.fromEntries(s.map((i,l)=>i==null?null:[a[l].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}function convertPartToLanguageModelPart(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:s}=convertToLanguageModelV3DataContent(n);let i=s??e.mediaType,l=a;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=detectMediaType({data:l,signatures:imageMediaTypeSignatures}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function mapToolResultOutput({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:convertDataContentToBase64String(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:convertDataContentToBase64String(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 createToolModelOutput({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:getErrorMessage$2(r)}:o==="json"?{type:"error-json",value:toJSONValue(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:toJSONValue(r)}}function toJSONValue(e){return e===void 0?null:e}function prepareCallSettings({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,seed:s,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new InvalidArgumentError$1({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new InvalidArgumentError$1({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new InvalidArgumentError$1({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new InvalidArgumentError$1({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new InvalidArgumentError$1({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new InvalidArgumentError$1({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new InvalidArgumentError$1({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(s!=null&&!Number.isInteger(s))throw new InvalidArgumentError$1({parameter:"seed",value:s,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,stopSequences:i,seed:s}}function isNonEmptyObject(e){return e!=null&&Object.keys(e).length>0}async function prepareToolsAndToolChoice({tools:e,toolChoice:t,activeTools:r}){if(!isNonEmptyObject(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,s]of n){const i=s.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:a,description:s.description,inputSchema:await asSchema(s.inputSchema).jsonSchema,...s.inputExamples!=null?{inputExamples:s.inputExamples}:{},providerOptions:s.providerOptions,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":o.push({type:"provider",name:a,id:s.id,args:s.args});break;default:{const l=i;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 jsonValueSchema$1=lazy(()=>union([_null(),string(),number$1(),boolean(),record(string(),jsonValueSchema$1.optional()),array$1(jsonValueSchema$1)])),providerMetadataSchema=record(string(),record(string(),jsonValueSchema$1.optional())),textPartSchema=object$2({type:literal("text"),text:string(),providerOptions:providerMetadataSchema.optional()}),imagePartSchema=object$2({type:literal("image"),image:union([dataContentSchema,_instanceof(URL)]),mediaType:string().optional(),providerOptions:providerMetadataSchema.optional()}),filePartSchema=object$2({type:literal("file"),data:union([dataContentSchema,_instanceof(URL)]),filename:string().optional(),mediaType:string(),providerOptions:providerMetadataSchema.optional()}),reasoningPartSchema=object$2({type:literal("reasoning"),text:string(),providerOptions:providerMetadataSchema.optional()}),toolCallPartSchema=object$2({type:literal("tool-call"),toolCallId:string(),toolName:string(),input:unknown(),providerOptions:providerMetadataSchema.optional(),providerExecuted:boolean().optional()}),outputSchema=discriminatedUnion("type",[object$2({type:literal("text"),value:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("json"),value:jsonValueSchema$1,providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("execution-denied"),reason:string().optional(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("error-text"),value:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("error-json"),value:jsonValueSchema$1,providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("content"),value:array$1(union([object$2({type:literal("text"),text:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("media"),data:string(),mediaType:string()}),object$2({type:literal("file-data"),data:string(),mediaType:string(),filename:string().optional(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("file-url"),url:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("file-id"),fileId:union([string(),record(string(),string())]),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("image-data"),data:string(),mediaType:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("image-url"),url:string(),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("image-file-id"),fileId:union([string(),record(string(),string())]),providerOptions:providerMetadataSchema.optional()}),object$2({type:literal("custom"),providerOptions:providerMetadataSchema.optional()})]))})]),toolResultPartSchema=object$2({type:literal("tool-result"),toolCallId:string(),toolName:string(),output:outputSchema,providerOptions:providerMetadataSchema.optional()}),toolApprovalRequestSchema=object$2({type:literal("tool-approval-request"),approvalId:string(),toolCallId:string()}),toolApprovalResponseSchema=object$2({type:literal("tool-approval-response"),approvalId:string(),approved:boolean(),reason:string().optional()}),systemModelMessageSchema=object$2({role:literal("system"),content:string(),providerOptions:providerMetadataSchema.optional()}),userModelMessageSchema=object$2({role:literal("user"),content:union([string(),array$1(union([textPartSchema,imagePartSchema,filePartSchema]))]),providerOptions:providerMetadataSchema.optional()}),assistantModelMessageSchema=object$2({role:literal("assistant"),content:union([string(),array$1(union([textPartSchema,filePartSchema,reasoningPartSchema,toolCallPartSchema,toolResultPartSchema,toolApprovalRequestSchema]))]),providerOptions:providerMetadataSchema.optional()}),toolModelMessageSchema=object$2({role:literal("tool"),content:array$1(union([toolResultPartSchema,toolApprovalResponseSchema])),providerOptions:providerMetadataSchema.optional()}),modelMessageSchema=union([systemModelMessageSchema,userModelMessageSchema,assistantModelMessageSchema,toolModelMessageSchema]);async function standardizePrompt({allowSystemInMessages:e,system:t,prompt:r,messages:n}){if(r==null&&n==null)throw new InvalidPromptError({prompt:r,message:"prompt or messages must be defined"});if(r!=null&&n!=null)throw new InvalidPromptError({prompt:r,message:"prompt and messages cannot be defined at the same time"});if(typeof t!="string"&&!asArray(t).every(a=>a.role==="system"))throw new InvalidPromptError({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 InvalidPromptError({prompt:r,message:"prompt or messages must be defined"});if(n.length===0)throw new InvalidPromptError({prompt:r,message:"messages must not be empty"});if(n.some(a=>a.role==="system")){if(e===!1)throw new InvalidPromptError({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 safeValidateTypes$1({value:n,schema:array$1(modelMessageSchema)});if(!o.success)throw new InvalidPromptError({prompt:r,message:"The messages do not match the ModelMessage[] schema.",cause:o.error});return{messages:n,system:t}}function wrapGatewayError(e){if(!GatewayAuthenticationError.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 AISDKError$1({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
|
|
577
|
-
|
|
578
|
-
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
579
|
-
|
|
580
|
-
Alternatively, you can use a provider module instead of the AI Gateway.
|
|
581
|
-
|
|
582
|
-
Learn more: \x1B[34m${r}\x1B[0m
|
|
583
|
-
|
|
584
|
-
`),{name:"GatewayAuthenticationError"})}function assembleOperationName({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 getBaseTelemetryAttributes({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,[s,i])=>{if(s==="timeout"){const l=getTotalTimeoutMs(i);l!=null&&(a[`ai.settings.${s}`]=l)}else a[`ai.settings.${s}`]=i;return a},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((a,[s,i])=>(a[`ai.telemetry.metadata.${s}`]=i,a),{}),...Object.entries(n??{}).reduce((a,[s,i])=>(i!==void 0&&(a[`ai.request.headers.${s}`]=i),a),{})}}var noopTracer={startSpan(){return noopSpan},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(noopSpan);if(typeof r=="function")return r(noopSpan);if(typeof n=="function")return n(noopSpan)}},noopSpan={spanContext(){return noopSpanContext},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}},noopSpanContext={traceId:"",spanId:"",traceFlags:0};function getTracer({isEnabled:e=!1,tracer:t}={}){return e?t||trace.getTracer("ai"):noopTracer}async function recordSpan({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async a=>{const s=context.active();try{const i=await context.with(s,()=>n(a));return o&&a.end(),i}catch(i){try{recordErrorOnSpan(a,i)}finally{a.end()}throw i}})}function recordErrorOnSpan(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:SpanStatusCode.ERROR})}function isPrimitiveAttributeValue(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function sanitizeAttributeValue(e){if(!Array.isArray(e))return e;const t=new Set(e.filter(isPrimitiveAttributeValue).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 selectTelemetryAttributes({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 s=await o.input();if(s!=null){const i=sanitizeAttributeValue(s);i!=null&&(r[n]=i)}continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();if(s!=null){const i=sanitizeAttributeValue(s);i!=null&&(r[n]=i)}continue}const a=sanitizeAttributeValue(o);a!=null&&(r[n]=a)}return r}function stringifyForTelemetry(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?convertDataContentToBase64String(r.data):r.data}:r)})))}function getGlobalTelemetryIntegrations(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function getGlobalTelemetryIntegration(){const e=getGlobalTelemetryIntegrations();return t=>{const r=asArray(t),n=[...e,...r];function o(a){const s=n.map(a).filter(Boolean);return async i=>{for(const l of s)try{await l(i)}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 asLanguageModelUsage(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:addTokenCounts(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function createNullLanguageModelUsage(){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 addLanguageModelUsage(e,t){var r,n,o,a,s,i,l,c,u,d;return{inputTokens:addTokenCounts(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:addTokenCounts((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:addTokenCounts((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:addTokenCounts((s=e.inputTokenDetails)==null?void 0:s.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:addTokenCounts(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:addTokenCounts((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:addTokenCounts((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(d=t.outputTokenDetails)==null?void 0:d.reasoningTokens)},totalTokens:addTokenCounts(e.totalTokens,t.totalTokens),reasoningTokens:addTokenCounts(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:addTokenCounts(e.cachedInputTokens,t.cachedInputTokens)}}function addTokenCounts(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function mergeObjects(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,s=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);s&&i?r[n]=mergeObjects(a,o):r[n]=o}return r}function getRetryDelayInMs({error:e,exponentialBackoffDelay:t}){const r=APICallError$1.isInstance(e)?e.responseHeaders:APICallError$1.isInstance(e.cause)?e.cause.responseHeaders:void 0;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const s=parseFloat(o);Number.isNaN(s)||(n=s)}const a=r["retry-after"];if(a&&n===void 0){const s=parseFloat(a);Number.isNaN(s)?n=Date.parse(a)-Date.now():n=s*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var retryWithExponentialBackoffRespectingRetryHeaders=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>_retryWithExponentialBackoff(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function _retryWithExponentialBackoff(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},a=[]){try{return await e()}catch(s){if(isAbortError$1(s)||t===0)throw s;const i=getErrorMessage$1(s),l=[...a,s],c=l.length;if(c>t)throw new RetryError({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(s instanceof Error&&(APICallError$1.isInstance(s)&&s.isRetryable===!0||GatewayError.isInstance(s)&&s.isRetryable===!0)&&c<=t)return await delay(getRetryDelayInMs({error:s,exponentialBackoffDelay:r}),{abortSignal:o}),_retryWithExponentialBackoff(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?s:new RetryError({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function prepareRetries({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new InvalidArgumentError$1({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new InvalidArgumentError$1({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:retryWithExponentialBackoffRespectingRetryHeaders({maxRetries:r,abortSignal:t})}}function collectToolApprovals({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=[],s=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new InvalidToolApprovalError({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new ToolCallNotFoundForApprovalError({toolCallId:c.toolCallId,approvalId:c.approvalId});const d={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?a.push(d):s.push(d)}return{approvedToolApprovals:a,deniedToolApprovals:s}}function now(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function executeToolCall({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:s,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:d}){const{toolName:p,toolCallId:f,input:h}=e,b=t?.[p];if(b?.execute==null)return;const y={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:a,functionId:n?.functionId,metadata:n?.metadata,experimental_context:s};return recordSpan({name:"ai.toolCall",attributes:selectTelemetryAttributes({telemetry:n,attributes:{...assembleOperationName({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(h)}}}),tracer:r,fn:async w=>{let g;await notify({event:y,callbacks:u});const m=now();try{const v=executeTool({execute:b.execute.bind(b),input:h,options:{toolCallId:f,messages:o,abortSignal:a,experimental_context:s}});for await(const _ of v)_.type==="preliminary"?c?.({...e,type:"tool-result",output:_.output,preliminary:!0}):g=_.output}catch(v){const _=now()-m;return await notify({event:{...y,success:!1,error:v,durationMs:_},callbacks:d}),recordErrorOnSpan(w,v),{type:"tool-error",toolCallId:f,toolName:p,input:h,error:v,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}const S=now()-m;await notify({event:{...y,success:!0,output:g,durationMs:S},callbacks:d});try{w.setAttributes(await selectTelemetryAttributes({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(g)}}}))}catch{}return{type:"tool-result",toolCallId:f,toolName:p,input:h,output:g,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}})}function extractReasoningContent(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
|
|
585
|
-
`)}function extractTextContent(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var DefaultGeneratedFile=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=convertUint8ArrayToBase64$1(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=convertBase64ToUint8Array(this.base64Data)),this.uint8ArrayData}},DefaultGeneratedFileWithType=class extends DefaultGeneratedFile{constructor(e){super(e),this.type="file"}};async function isApprovalNeeded({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 encoder=new TextEncoder;function canonicalJSON(e){return e==null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(canonicalJSON).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${canonicalJSON(e[n])}`).join(",")}}`}function toBase64url(e){return convertUint8ArrayToBase64$1(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function fromBase64url(e){return convertBase64ToUint8Array(e)}async function importKey(e){const t=typeof e=="string"?encoder.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function hashInput(e){const t=canonicalJSON(e),r=await crypto.subtle.digest("SHA-256",encoder.encode(t));return toBase64url(new Uint8Array(r))}function buildPayload(e,t,r,n){return encoder.encode(`${e}
|
|
586
|
-
${t}
|
|
587
|
-
${r}
|
|
588
|
-
${n}`)}async function signToolApproval({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){const a=await importKey(e),s=await hashInput(o),i=buildPayload(t,r,n,s),l=await crypto.subtle.sign("HMAC",a,i);return toBase64url(new Uint8Array(l))}async function verifyToolApprovalSignature({secret:e,signature:t,approvalId:r,toolCallId:n,toolName:o,input:a}){const s=await importKey(e),i=await hashInput(a),l=buildPayload(r,n,o,i),c=fromBase64url(t);return crypto.subtle.verify("HMAC",s,c,l)}async function maybeSignApproval({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){if(e!=null)return signToolApproval({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o})}async function validateApprovedToolApprovals({approvedToolApprovals:e,tools:t,messages:r,experimental_context:n,toolApprovalSecret:o}){var a;const s=[],i=[];for(const l of e){const{toolCall:c,approvalRequest:u}=l,d=t?.[c.toolName];if(o!=null){if(u.signature==null)throw new InvalidToolApprovalSignatureError({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"missing signature"});if(!await verifyToolApprovalSignature({secret:o,signature:u.signature,approvalId:u.approvalId,toolCallId:c.toolCallId,toolName:c.toolName,input:c.input}))throw new InvalidToolApprovalSignatureError({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"invalid signature"})}if(d!=null&&typeof d.execute=="function"&&d.inputSchema!=null){const f=await safeValidateTypes$1({value:c.input,schema:asSchema(d.inputSchema)});if(!f.success)throw new InvalidToolInputError({toolName:c.toolName,toolInput:JSON.stringify(c.input),cause:f.error})}d!=null&&await isApprovalNeeded({tool:d,toolCall:c,messages:r,experimental_context:n})?s.push(l):i.push({...l,approvalResponse:{...l.approvalResponse,approved:!1,reason:(a=l.approvalResponse.reason)!=null?a:`Tool "${c.toolName}" does not require approval`}})}return{approvedToolApprovals:s,deniedToolApprovals:i}}var output_exports={};__export(output_exports,{array:()=>array,choice:()=>choice,json:()=>json,object:()=>object,text:()=>text});function fixJson(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 s(u,d,p){switch(u){case'"':{r=d,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=d,n=d,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=d,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{r=d,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{r=d,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function i(u,d){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=d,t.pop();break}}}function l(u,d){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=d,t.pop();break}}}for(let u=0;u<e.length;u++){const d=e[u];switch(t[t.length-1]){case"ROOT":s(d,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(d){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(d){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(d){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(d){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(d,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(d,u);break}case"INSIDE_STRING":{switch(d){case'"':{t.pop(),r=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=u}break}case"INSIDE_ARRAY_START":{switch(d){case"]":{r=u,t.pop();break}default:{r=u,s(d,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(d){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":{s(d,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),d==="u"?(o=0,t.push("INSIDE_STRING_UNICODE_ESCAPE")):r=u;break}case"INSIDE_STRING_UNICODE_ESCAPE":{a(d)&&(o++,o===4&&(t.pop(),r=u));break}case"INSIDE_NUMBER":{switch(d){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(d,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(n,u+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(d,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,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 parsePartialJson(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await safeParseJSON$1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await safeParseJSON$1({text:fixJson(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var text=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),object=({schema:e,name:t,description:r})=>{const n=asSchema(e);return{name:"object",responseFormat:resolve(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},a){const s=await safeParseJSON$1({text:o});if(!s.success)throw new NoObjectGeneratedError({message:"No object generated: could not parse the response.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const i=await safeValidateTypes$1({value:s.value,schema:n});if(!i.success)throw new NoObjectGeneratedError({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return i.value},async parsePartialOutput({text:o}){const a=await parsePartialJson(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){}}},array=({element:e,name:t,description:r})=>{const n=asSchema(e);return{name:"array",responseFormat:resolve(n.jsonSchema).then(o=>{const{$schema:a,...s}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:s}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},a){const s=await safeParseJSON$1({text:o});if(!s.success)throw new NoObjectGeneratedError({message:"No object generated: could not parse the response.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const i=s.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new NoObjectGeneratedError({message:"No object generated: response did not match schema.",cause:new TypeValidationError$1({value:i,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 i.elements){const c=await safeValidateTypes$1({value:l,schema:n});if(!c.success)throw new NoObjectGeneratedError({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason})}return i.elements},async parsePartialOutput({text:o}){const a=await parsePartialJson(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=a.value;if(s==null||typeof s!="object"||!("elements"in s)||!Array.isArray(s.elements))return;const i=a.state==="repaired-parse"&&s.elements.length>0?s.elements.slice(0,-1):s.elements,l=[];for(const c of i){const u=await safeValidateTypes$1({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:a},s){if(a!=null)for(;o<a.length;o++)s.enqueue(a[o])}})}}},choice=({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 safeParseJSON$1({text:n});if(!a.success)throw new NoObjectGeneratedError({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const s=a.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string"||!e.includes(s.result))throw new NoObjectGeneratedError({message:"No object generated: response did not match schema.",cause:new TypeValidationError$1({value:s,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return s.result},async parsePartialOutput({text:n}){const o=await parsePartialJson(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 s=e.filter(i=>i.startsWith(a.result));return o.state==="successful-parse"?s.includes(a.result)?{partial:a.result}:void 0:s.length===1?{partial:s[0]}:void 0}}},createElementStreamTransform(){}}),json=({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 safeParseJSON$1({text:r});if(!o.success)throw new NoObjectGeneratedError({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 parsePartialJson(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 parseToolCall({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await parseProviderExecutedDynamicToolCall(e);throw new NoSuchToolError({toolName:e.toolName})}try{return await doParseToolCall({toolCall:e,tools:t})}catch(a){if(r==null||!(NoSuchToolError.isInstance(a)||InvalidToolInputError.isInstance(a)))throw a;let s=null;try{s=await r({toolCall:e,tools:t,inputSchema:async({toolName:i})=>{const{inputSchema:l}=t[i];return await asSchema(l).jsonSchema},system:n,messages:o,error:a})}catch(i){throw new ToolCallRepairError({cause:i,originalError:a})}if(s==null)throw a;return await doParseToolCall({toolCall:s,tools:t})}}catch(a){const s=await safeParseJSON$1({text:e.input}),i=s.success?s.value:e.input,l=t?.[e.toolName];return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:a,title:l?.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...l?.metadata!=null?{toolMetadata:l.metadata}:{}}}}async function parseProviderExecutedDynamicToolCall(e){const t=e.input.trim()===""?{success:!0,value:{}}:await safeParseJSON$1({text:e.input});if(t.success===!1)throw new InvalidToolInputError({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 doParseToolCall({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await parseProviderExecutedDynamicToolCall(e);throw new NoSuchToolError({toolName:e.toolName,availableTools:Object.keys(t)})}const o=asSchema(n.inputSchema),a=e.input.trim()===""?await safeValidateTypes$1({value:{},schema:o}):await safeParseJSON$1({text:e.input,schema:o});if(a.success===!1)throw new InvalidToolInputError({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 DefaultStepResult=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:a,finishReason:s,rawFinishReason:i,usage:l,warnings:c,request:u,response:d,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=a,this.finishReason=s,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=d,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 stepCountIs(e){return({steps:t})=>t.length===e}async function isStopConditionMet({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function toResponseMessages({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 s=await createToolModelOutput({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:s,providerOptions:a.providerMetadata});break}case"tool-error":{const s=await createToolModelOutput({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:s,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 s=await createToolModelOutput({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:s,...a.providerMetadata!=null?{providerOptions:a.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function mergeAbortSignals(...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 originalGenerateId=createIdGenerator$1({prefix:"aitxt",size:24});async function generateText({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:s,maxRetries:i,abortSignal:l,timeout:c,headers:u,stopWhen:d=stepCountIs(1),experimental_output:p,output:f=p,experimental_telemetry:h,providerOptions:b,experimental_activeTools:y,activeTools:w=y,experimental_prepareStep:g,prepareStep:m=g,experimental_repairToolCall:S,experimental_download:v,experimental_context:_,experimental_toolApprovalSecret:$,experimental_include:T,_internal:{generateId:R=originalGenerateId}={},experimental_onStart:x,experimental_onStepStart:E,experimental_onToolCallStart:A,experimental_onToolCallFinish:D,onStepFinish:U,onFinish:K,...G}){const te=resolveLanguageModel(e),X=getGlobalTelemetryIntegration(),ue=asArray(d),V=getTotalTimeoutMs(c),C=getStepTimeoutMs(c),N=C!=null?new AbortController:void 0,L=mergeAbortSignals(l,V!=null?AbortSignal.timeout(V):void 0,N?.signal),{maxRetries:I,retry:k}=prepareRetries({maxRetries:i,abortSignal:L}),O=prepareCallSettings(G),q=withUserAgentSuffix$1(u??{},`ai/${VERSION$4}`),B=getBaseTelemetryAttributes({model:te,telemetry:h,headers:q,settings:{...O,maxRetries:I}}),F={provider:te.provider,modelId:te.modelId},j=await standardizePrompt({system:n,prompt:o,messages:a,allowSystemInMessages:s}),M=X(h?.integrations);await notify({event:{model:F,system:n,prompt:o,messages:a,tools:t,toolChoice:r,activeTools:w,maxOutputTokens:O.maxOutputTokens,temperature:O.temperature,topP:O.topP,topK:O.topK,presencePenalty:O.presencePenalty,frequencyPenalty:O.frequencyPenalty,stopSequences:O.stopSequences,seed:O.seed,maxRetries:I,timeout:c,headers:u,providerOptions:b,stopWhen:d,output:f,abortSignal:l,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:_},callbacks:[x,M.onStart]});const Z=getTracer(h);try{return await recordSpan({name:"ai.generateText",attributes:selectTelemetryAttributes({telemetry:h,attributes:{...assembleOperationName({operationId:"ai.generateText",telemetry:h}),...B,"ai.model.provider":te.provider,"ai.model.id":te.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:a})}}}),tracer:Z,fn:async H=>{var J,oe,se,_e,Te,Se,Q,ve,de,ne,ae,ee,Y,ce,le,P,W,he,Ee,Ye;const Ie=j.messages,xe=[],{approvedToolApprovals:Ne,deniedToolApprovals:Fe}=collectToolApprovals({messages:Ie}),{approvedToolApprovals:He,deniedToolApprovals:Be}=await validateApprovedToolApprovals({approvedToolApprovals:Ne.filter(Le=>!Le.toolCall.providerExecuted),tools:t,messages:Ie,experimental_context:_,toolApprovalSecret:$}),ie=[...Fe,...Be];if(ie.length>0||He.length>0){const Le=await executeTools({toolCalls:He.map(ye=>ye.toolCall),tools:t,tracer:Z,telemetry:h,messages:Ie,abortSignal:L,experimental_context:_,stepNumber:0,model:F,onToolCallStart:[A,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}),qe=[];for(const ye of Le){const ze=await createToolModelOutput({toolCallId:ye.toolCallId,input:ye.input,tool:t?.[ye.toolName],output:ye.type==="tool-result"?ye.output:ye.error,errorMode:ye.type==="tool-error"?"text":"none"});qe.push({type:"tool-result",toolCallId:ye.toolCallId,toolName:ye.toolName,output:ze})}for(const ye of ie)qe.push({type:"tool-result",toolCallId:ye.toolCall.toolCallId,toolName:ye.toolCall.toolName,output:{type:"execution-denied",reason:ye.approvalResponse.reason,...ye.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:ye.approvalResponse.approvalId}}}}});xe.push({role:"tool",content:qe})}const $e=prepareCallSettings(G);let be,ke=[],ge=[];const we=[],Qe=new Map;do{const Le=C!=null?setTimeout(()=>N.abort(),C):void 0;try{const qe=[...Ie,...xe],ye=await m?.({model:te,steps:we,stepNumber:we.length,messages:qe,experimental_context:_}),ze=resolveLanguageModel((J=ye?.model)!=null?J:te),et={provider:ze.provider,modelId:ze.modelId},Xe=await convertToLanguageModelPrompt({prompt:{system:(oe=ye?.system)!=null?oe:j.system,messages:(se=ye?.messages)!=null?se:qe},supportedUrls:await ze.supportedUrls,download:v});_=(_e=ye?.experimental_context)!=null?_e:_;const St=(Te=ye?.activeTools)!=null?Te:w,{toolChoice:tt,tools:st}=await prepareToolsAndToolChoice({tools:t,toolChoice:(Se=ye?.toolChoice)!=null?Se:r,activeTools:St}),rt=(Q=ye?.messages)!=null?Q:qe,Ae=(ve=ye?.system)!=null?ve:j.system,Ge=mergeObjects(b,ye?.providerOptions);await notify({event:{stepNumber:we.length,model:et,system:Ae,messages:rt,tools:t,toolChoice:tt,activeTools:St,steps:[...we],providerOptions:Ge,timeout:c,headers:u,stopWhen:d,output:f,abortSignal:l,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:_},callbacks:[E,M.onStepStart]}),be=await k(()=>{var me;return recordSpan({name:"ai.generateText.doGenerate",attributes:selectTelemetryAttributes({telemetry:h,attributes:{...assembleOperationName({operationId:"ai.generateText.doGenerate",telemetry:h}),...B,"ai.model.provider":ze.provider,"ai.model.id":ze.modelId,"ai.prompt.messages":{input:()=>stringifyForTelemetry(Xe)},"ai.prompt.tools":{input:()=>st?.map(Ue=>JSON.stringify(Ue))},"ai.prompt.toolChoice":{input:()=>tt!=null?JSON.stringify(tt):void 0},"gen_ai.system":ze.provider,"gen_ai.request.model":ze.modelId,"gen_ai.request.frequency_penalty":G.frequencyPenalty,"gen_ai.request.max_tokens":G.maxOutputTokens,"gen_ai.request.presence_penalty":G.presencePenalty,"gen_ai.request.stop_sequences":G.stopSequences,"gen_ai.request.temperature":(me=G.temperature)!=null?me:void 0,"gen_ai.request.top_k":G.topK,"gen_ai.request.top_p":G.topP}}),tracer:Z,fn:async Ue=>{var Je,je,mt,Et,Ct,ot,at,ct;const Ce=await ze.doGenerate({...$e,tools:st,toolChoice:tt,responseFormat:await f?.responseFormat,prompt:Xe,providerOptions:Ge,abortSignal:L,headers:q}),Ve={id:(je=(Je=Ce.response)==null?void 0:Je.id)!=null?je:R(),timestamp:(Et=(mt=Ce.response)==null?void 0:mt.timestamp)!=null?Et:new Date,modelId:(ot=(Ct=Ce.response)==null?void 0:Ct.modelId)!=null?ot:ze.modelId,headers:(at=Ce.response)==null?void 0:at.headers,body:(ct=Ce.response)==null?void 0:ct.body},gt=asLanguageModelUsage(Ce.usage);return Ue.setAttributes(await selectTelemetryAttributes({telemetry:h,attributes:{"ai.response.finishReason":Ce.finishReason.unified,"ai.response.text":{output:()=>extractTextContent(Ce.content)},"ai.response.reasoning":{output:()=>extractReasoningContent(Ce.content)},"ai.response.toolCalls":{output:()=>{const ut=asToolCalls(Ce.content);return ut==null?void 0:JSON.stringify(ut)}},"ai.response.id":Ve.id,"ai.response.model":Ve.modelId,"ai.response.timestamp":Ve.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ce.providerMetadata),"ai.usage.inputTokens":Ce.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Ce.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Ce.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Ce.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Ce.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Ce.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Ce.usage.outputTokens.reasoning,"ai.usage.totalTokens":gt.totalTokens,"ai.usage.reasoningTokens":Ce.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Ce.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Ce.finishReason.unified],"gen_ai.response.id":Ve.id,"gen_ai.response.model":Ve.modelId,"gen_ai.usage.input_tokens":Ce.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ce.usage.outputTokens.total}})),{...Ce,response:Ve}}})});const nt=await Promise.all(be.content.filter(me=>me.type==="tool-call").map(me=>parseToolCall({toolCall:me,tools:t,repairToolCall:S,system:n,messages:qe}))),lt={};for(const me of nt){if(me.invalid)continue;const Ue=t?.[me.toolName];if(Ue!=null&&(Ue?.onInputAvailable!=null&&await Ue.onInputAvailable({input:me.input,toolCallId:me.toolCallId,messages:qe,abortSignal:L,experimental_context:_}),await isApprovalNeeded({tool:Ue,toolCall:me,messages:qe,experimental_context:_}))){const Je=R(),je=await maybeSignApproval({secret:$,approvalId:Je,toolCallId:me.toolCallId,toolName:me.toolName,input:me.input});lt[me.toolCallId]={type:"tool-approval-request",approvalId:Je,toolCall:me,...je!=null?{signature:je}:{}}}}const Tt=nt.filter(me=>me.invalid&&me.dynamic);ge=[];for(const me of Tt)ge.push({type:"tool-error",toolCallId:me.toolCallId,toolName:me.toolName,input:me.input,error:getErrorMessage$1(me.error),dynamic:!0});ke=nt.filter(me=>!me.providerExecuted),t!=null&&ge.push(...await executeTools({toolCalls:ke.filter(me=>!me.invalid&<[me.toolCallId]==null),tools:t,tracer:Z,telemetry:h,messages:qe,abortSignal:L,experimental_context:_,stepNumber:we.length,model:et,onToolCallStart:[A,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}));for(const me of nt){if(!me.providerExecuted)continue;const Ue=t?.[me.toolName];Ue?.type==="provider"&&Ue.supportsDeferredResults&&(be.content.some(je=>je.type==="tool-result"&&je.toolCallId===me.toolCallId)||Qe.set(me.toolCallId,{toolName:me.toolName}))}for(const me of be.content)me.type==="tool-result"&&Qe.delete(me.toolCallId);const it=asContent({content:be.content,toolCalls:nt,toolOutputs:ge,toolApprovalRequests:Object.values(lt),tools:t});xe.push(...await toResponseMessages({content:it,tools:t}));const ht=(de=T?.requestBody)==null||de?(ne=be.request)!=null?ne:{}:{...be.request,body:void 0},Rt={...be.response,messages:structuredClone(xe),body:(ae=T?.responseBody)==null||ae?(ee=be.response)==null?void 0:ee.body:void 0},xt=we.length,ft=new DefaultStepResult({stepNumber:xt,model:et,functionId:h?.functionId,metadata:h?.metadata,experimental_context:_,content:it,finishReason:be.finishReason.unified,rawFinishReason:be.finishReason.raw,usage:asLanguageModelUsage(be.usage),warnings:be.warnings,providerMetadata:be.providerMetadata,request:ht,response:Rt});logWarnings({warnings:(Y=be.warnings)!=null?Y:[],provider:et.provider,model:et.modelId}),we.push(ft),await notify({event:ft,callbacks:[U,M.onStepFinish]})}finally{Le!=null&&clearTimeout(Le)}}while((ke.length>0&&ge.length===ke.length||Qe.size>0)&&!await isStopConditionMet({stopConditions:ue,steps:we}));H.setAttributes(await selectTelemetryAttributes({telemetry:h,attributes:{"ai.response.finishReason":be.finishReason.unified,"ai.response.text":{output:()=>extractTextContent(be.content)},"ai.response.reasoning":{output:()=>extractReasoningContent(be.content)},"ai.response.toolCalls":{output:()=>{const Le=asToolCalls(be.content);return Le==null?void 0:JSON.stringify(Le)}},"ai.response.providerMetadata":JSON.stringify(be.providerMetadata)}}));const fe=we[we.length-1],Re=we.reduce((Le,qe)=>addLanguageModelUsage(Le,qe.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});H.setAttributes(await selectTelemetryAttributes({telemetry:h,attributes:{"ai.usage.inputTokens":Re.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ce=Re.inputTokenDetails)==null?void 0:ce.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(le=Re.inputTokenDetails)==null?void 0:le.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(P=Re.inputTokenDetails)==null?void 0:P.cacheWriteTokens,"ai.usage.outputTokens":Re.outputTokens,"ai.usage.outputTokenDetails.textTokens":(W=Re.outputTokenDetails)==null?void 0:W.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(he=Re.outputTokenDetails)==null?void 0:he.reasoningTokens,"ai.usage.totalTokens":Re.totalTokens,"ai.usage.reasoningTokens":(Ee=Re.outputTokenDetails)==null?void 0:Ee.reasoningTokens,"ai.usage.cachedInputTokens":(Ye=Re.inputTokenDetails)==null?void 0:Ye.cacheReadTokens}})),await notify({event:{stepNumber:fe.stepNumber,model:fe.model,functionId:fe.functionId,metadata:fe.metadata,experimental_context:fe.experimental_context,finishReason:fe.finishReason,rawFinishReason:fe.rawFinishReason,usage:fe.usage,content:fe.content,text:fe.text,reasoningText:fe.reasoningText,reasoning:fe.reasoning,files:fe.files,sources:fe.sources,toolCalls:fe.toolCalls,staticToolCalls:fe.staticToolCalls,dynamicToolCalls:fe.dynamicToolCalls,toolResults:fe.toolResults,staticToolResults:fe.staticToolResults,dynamicToolResults:fe.dynamicToolResults,request:fe.request,response:fe.response,warnings:fe.warnings,providerMetadata:fe.providerMetadata,steps:we,totalUsage:Re},callbacks:[K,M.onFinish]});let Pe;return fe.finishReason==="stop"&&(Pe=await(f??text()).parseCompleteOutput({text:fe.text},{response:fe.response,usage:fe.usage,finishReason:fe.finishReason})),new DefaultGenerateTextResult({steps:we,totalUsage:Re,output:Pe})}})}catch(H){throw wrapGatewayError(H)}}async function executeTools({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:s,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>executeToolCall({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:s,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var DefaultGenerateTextResult=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 NoOutputGeneratedError;return this._output}};function asToolCalls(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 asContent({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const a=[];for(const s of e)switch(s.type){case"text":case"reasoning":case"source":a.push(s);break;case"file":{a.push({type:"file",file:new DefaultGeneratedFile(s),...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{}});break}case"tool-call":{a.push(t.find(i=>i.toolCallId===s.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===s.toolCallId);if(i==null){const l=o?.[s.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${s.toolCallId} not found.`);s.isError?a.push({type:"tool-error",toolCallId:s.toolCallId,toolName:s.toolName,input:void 0,error:s.result,providerExecuted:!0,dynamic:s.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}}):a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,input:void 0,output:s.result,providerExecuted:!0,dynamic:s.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}});break}s.isError?a.push({type:"tool-error",toolCallId:s.toolCallId,toolName:s.toolName,input:i.input,error:s.result,providerExecuted:!0,dynamic:i.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...i.toolMetadata!=null?{toolMetadata:i.toolMetadata}:{}}):a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,input:i.input,output:s.result,providerExecuted:!0,dynamic:i.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...i.toolMetadata!=null?{toolMetadata:i.toolMetadata}:{}});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===s.toolCallId);if(i==null)throw new ToolCallNotFoundForApprovalError({toolCallId:s.toolCallId,approvalId:s.approvalId});a.push({type:"tool-approval-request",approvalId:s.approvalId,toolCall:i});break}}return[...a,...r,...n]}function prepareHeaders(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 createTextStreamResponse({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:prepareHeaders(r,{"content-type":"text/plain; charset=utf-8"})})}function writeToServerResponse({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 s=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await s.read();if(l)break;e.write(c)||await new Promise(d=>{e.once("drain",d)})}}catch(l){throw l}finally{e.end()}})()}function pipeTextStreamToResponse({response:e,status:t,statusText:r,headers:n,textStream:o}){writeToServerResponse({response:e,status:t,statusText:r,headers:Object.fromEntries(prepareHeaders(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var JsonToSseTransformStream=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
589
|
-
|
|
590
|
-
`)},flush(e){e.enqueue(`data: [DONE]
|
|
591
|
-
|
|
592
|
-
`)}})}},UI_MESSAGE_STREAM_HEADERS={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function createUIMessageStreamResponse({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let a=n.pipeThrough(new JsonToSseTransformStream);if(o){const[s,i]=a.tee();a=s,o({stream:i})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:prepareHeaders(r,UI_MESSAGE_STREAM_HEADERS)})}function getResponseUIMessageId({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}record(string(),jsonValueSchema$1.optional());function isDataUIMessageChunk(e){return e.type.startsWith("data-")}function createIdMap(){return Object.create(null)}function isStaticToolUIPart(e){return e.type.startsWith("tool-")}function isDynamicToolUIPart(e){return e.type==="dynamic-tool"}function isToolUIPart(e){return isStaticToolUIPart(e)||isDynamicToolUIPart(e)}function getStaticToolName(e){return e.type.split("-").slice(1).join("-")}function createStreamingUIMessageState({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:createIdMap(),activeReasoningParts:createIdMap(),partialToolCalls:createIdMap()}}function processUIMessageStream({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:a,onData:s}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var d,p,f,h;function b(m){const v=c.message.parts.filter(isToolUIPart).find(_=>_.toolCallId===m);if(v==null)throw new UIMessageStreamError({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return v}function y(m){var S;const v=c.message.parts.find(T=>isStaticToolUIPart(T)&&T.toolCallId===m.toolCallId),_=m,$=v;if(v!=null){v.state=m.state,$.input=_.input,$.output=_.output,$.errorText=_.errorText,$.rawInput=_.rawInput,$.preliminary=_.preliminary,m.title!==void 0&&($.title=m.title),m.toolMetadata!==void 0&&($.toolMetadata=m.toolMetadata),$.providerExecuted=(S=_.providerExecuted)!=null?S:v.providerExecuted;const T=_.providerMetadata;if(T!=null)if(m.state==="output-available"||m.state==="output-error"){const R=v;R.resultProviderMetadata=T}else v.callProviderMetadata=T}else c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,...m.toolMetadata!==void 0?{toolMetadata:m.toolMetadata}:{},input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null&&(m.state==="output-available"||m.state==="output-error")?{resultProviderMetadata:_.providerMetadata}:{},..._.providerMetadata!=null&&!(m.state==="output-available"||m.state==="output-error")?{callProviderMetadata:_.providerMetadata}:{}})}function w(m){var S,v;const _=c.message.parts.find(R=>R.type==="dynamic-tool"&&R.toolCallId===m.toolCallId),$=m,T=_;if(_!=null){_.state=m.state,T.toolName=m.toolName,T.input=$.input,T.output=$.output,T.errorText=$.errorText,T.rawInput=(S=$.rawInput)!=null?S:T.rawInput,T.preliminary=$.preliminary,m.title!==void 0&&(T.title=m.title),m.toolMetadata!==void 0&&(T.toolMetadata=m.toolMetadata),T.providerExecuted=(v=$.providerExecuted)!=null?v:_.providerExecuted;const R=$.providerMetadata;if(R!=null)if(m.state==="output-available"||m.state==="output-error"){const x=_;x.resultProviderMetadata=R}else _.callProviderMetadata=R}else c.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:$.input,output:$.output,errorText:$.errorText,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:m.title,...m.toolMetadata!==void 0?{toolMetadata:m.toolMetadata}:{},...$.providerMetadata!=null&&(m.state==="output-available"||m.state==="output-error")?{resultProviderMetadata:$.providerMetadata}:{},...$.providerMetadata!=null&&!(m.state==="output-available"||m.state==="output-error")?{callProviderMetadata:$.providerMetadata}:{}})}async function g(m){if(m!=null){const S=c.message.metadata!=null?mergeObjects(c.message.metadata,m):m;t!=null&&await validateTypes$1({value:S,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=S}}switch(i.type){case"text-start":{const m={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=m,c.message.parts.push(m),u();break}case"text-delta":{const m=c.activeTextParts[i.id];if(m==null)throw new UIMessageStreamError({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});m.text+=i.delta,m.providerMetadata=(d=i.providerMetadata)!=null?d:m.providerMetadata,u();break}case"text-end":{const m=c.activeTextParts[i.id];if(m==null)throw new UIMessageStreamError({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});m.state="done",m.providerMetadata=(p=i.providerMetadata)!=null?p:m.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const m={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=m,c.message.parts.push(m),u();break}case"reasoning-delta":{const m=c.activeReasoningParts[i.id];if(m==null)throw new UIMessageStreamError({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});m.text+=i.delta,m.providerMetadata=(f=i.providerMetadata)!=null?f:m.providerMetadata,u();break}case"reasoning-end":{const m=c.activeReasoningParts[i.id];if(m==null)throw new UIMessageStreamError({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});m.providerMetadata=(h=i.providerMetadata)!=null?h:m.providerMetadata,m.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const m=c.message.parts.filter(isStaticToolUIPart);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:m.length,dynamic:i.dynamic,title:i.title,toolMetadata:i.toolMetadata},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,toolMetadata:i.toolMetadata,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,toolMetadata:i.toolMetadata,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const m=c.partialToolCalls[i.toolCallId];if(m==null)throw new UIMessageStreamError({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});m.text+=i.inputTextDelta;const{value:S}=await parsePartialJson(m.text);m.dynamic?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:S,title:m.title,toolMetadata:m.toolMetadata}):y({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:S,title:m.title,toolMetadata:m.toolMetadata}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title,toolMetadata:i.toolMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title,toolMetadata:i.toolMetadata}),u(),a&&!i.providerExecuted&&await a({toolCall:i});break}case"tool-input-error":{const m=c.message.parts.filter(isToolUIPart).find(v=>v.toolCallId===i.toolCallId);(m!=null?m.type==="dynamic-tool":!!i.dynamic)?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,toolMetadata:i.toolMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,toolMetadata:i.toolMetadata}),u();break}case"tool-approval-request":{const m=b(i.toolCallId);m.state="approval-requested",m.approval={id:i.approvalId,...i.signature!=null?{signature:i.signature}:{}},u();break}case"tool-output-denied":{const m=b(i.toolCallId);m.state="output-denied",u();break}case"tool-output-available":{const m=b(i.toolCallId);m.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:m.title,toolMetadata:m.toolMetadata}):y({toolCallId:i.toolCallId,toolName:getStaticToolName(m),state:"output-available",input:m.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,providerMetadata:i.providerMetadata,title:m.title,toolMetadata:m.toolMetadata}),u();break}case"tool-output-error":{const m=b(i.toolCallId);m.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:m.title,toolMetadata:m.toolMetadata}):y({toolCallId:i.toolCallId,toolName:getStaticToolName(m),state:"output-error",input:m.input,rawInput:m.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:m.title,toolMetadata:m.toolMetadata}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts=createIdMap(),c.activeReasoningParts=createIdMap();break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await g(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(isDataUIMessageChunk(i)){if(r?.[i.type]!=null){const v=c.message.parts.findIndex($=>"id"in $&&"data"in $&&$.id===i.id&&$.type===i.type),_=v>=0?v:c.message.parts.length;await validateTypes$1({value:i.data,schema:r[i.type],context:{field:`message.parts[${_}].data`,entityName:i.type,entityId:i.id}})}const m=i;if(m.transient){s?.(m);break}const S=m.id!=null?c.message.parts.find(v=>m.type===v.type&&m.id===v.id):void 0;S!=null?S.data=m.data:c.message.parts.push(m),s?.(m),u()}}l.enqueue(i)})}}))}function handleUIMessageStreamFinish({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:a}){let s=t?.[t.length-1];s?.role!=="assistant"?s=void 0:e=s.id;let i=!1;const l=a.pipeThrough(new TransformStream({transform(h,b){if(h.type==="start"){const y=h;y.messageId==null&&e!=null&&(y.messageId=e)}h.type==="abort"&&(i=!0),b.enqueue(h)}}));if(n==null&&r==null)return l;const c=createStreamingUIMessageState({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),u=async h=>{await h({state:c,write:()=>{}})};let d=!1;const p=async()=>{if(d||!n)return;d=!0;const h=c.message.id===s?.id;await n({isAborted:i,isContinuation:h,responseMessage:c.message,messages:[...h?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},f=async()=>{if(!r)return;const h=c.message.id===s?.id;try{await r({isContinuation:h,responseMessage:structuredClone(c.message),messages:[...h?t.slice(0,-1):t,structuredClone(c.message)]})}catch(b){o(b)}};return processUIMessageStream({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(h,b){h.type==="finish-step"&&await f(),b.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function pipeUIMessageStreamToResponse({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:a}){let s=o.pipeThrough(new JsonToSseTransformStream);if(a){const[i,l]=s.tee();s=i,a({stream:l})}writeToServerResponse({response:e,status:t,statusText:r,headers:Object.fromEntries(prepareHeaders(n,UI_MESSAGE_STREAM_HEADERS).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function createAsyncIterableStream(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(a){var s;if(!n){n=!0;try{a&&await((s=r.cancel)==null?void 0:s.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:a,value:s}=await r.read();return a?(await o(!0),{done:!0,value:void 0}):{done:!1,value:s}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(a){throw await o(!0),a}}},t}async function consumeStream({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 createResolvablePromise(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function createStitchableStream(){let e=[],t=null,r=!1,n=createResolvablePromise();const o=()=>{r=!0,n.resolve(),e.forEach(s=>s.cancel()),e=[],t?.close()},a=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=createResolvablePromise(),await n.promise,a();try{const{value:s,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await a()):t?.enqueue(s)}catch(s){t?.error(s),e.shift(),o()}};return{stream:new ReadableStream({start(s){t=s},pull:a,async cancel(){for(const s of e)await s.cancel();e=[],r=!0}}),addStream:s=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(s.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function runToolsTransformation({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:a,abortSignal:s,repairToolCall:i,experimental_context:l,toolApprovalSecret:c,generateId:u,stepNumber:d,model:p,onToolCallStart:f,onToolCallFinish:h}){let b=null;const y=new ReadableStream({start(T){b=T}}),w=new Set,g=new Map,m=new Map;let S=!1,v;function _(){S&&w.size===0&&(v!=null&&b.enqueue(v),b.close())}const $=new TransformStream({async transform(T,R){const x=T.type;switch(x){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":{R.enqueue(T);break}case"file":{R.enqueue({type:"file",file:new DefaultGeneratedFileWithType({data:T.data,mediaType:T.mediaType}),...T.providerMetadata!=null?{providerMetadata:T.providerMetadata}:{}});break}case"finish":{v={type:"finish",finishReason:T.finishReason.unified,rawFinishReason:T.finishReason.raw,usage:asLanguageModelUsage(T.usage),providerMetadata:T.providerMetadata};break}case"tool-approval-request":{const E=m.get(T.toolCallId);if(E==null){b.enqueue({type:"error",error:new ToolCallNotFoundForApprovalError({toolCallId:T.toolCallId,approvalId:T.approvalId})});break}R.enqueue({type:"tool-approval-request",approvalId:T.approvalId,toolCall:E});break}case"tool-call":{try{const E=await parseToolCall({toolCall:T,tools:e,repairToolCall:i,system:o,messages:a});if(m.set(E.toolCallId,E),R.enqueue(E),E.invalid){b.enqueue({type:"tool-error",toolCallId:E.toolCallId,toolName:E.toolName,input:E.input,error:getErrorMessage$1(E.error),dynamic:!0,title:E.title,...E.toolMetadata!=null?{toolMetadata:E.toolMetadata}:{}});break}const A=e?.[E.toolName];if(A==null)break;if(A.onInputAvailable!=null&&await A.onInputAvailable({input:E.input,toolCallId:E.toolCallId,messages:a,abortSignal:s,experimental_context:l}),await isApprovalNeeded({tool:A,toolCall:E,messages:a,experimental_context:l})){const D=u(),U=await maybeSignApproval({secret:c,approvalId:D,toolCallId:E.toolCallId,toolName:E.toolName,input:E.input});b.enqueue({type:"tool-approval-request",approvalId:D,toolCall:E,...U!=null?{signature:U}:{}});break}if(g.set(E.toolCallId,E.input),A.execute!=null&&E.providerExecuted!==!0){const D=u();w.add(D),executeToolCall({toolCall:E,tools:e,tracer:r,telemetry:n,messages:a,abortSignal:s,experimental_context:l,stepNumber:d,model:p,onToolCallStart:f,onToolCallFinish:h,onPreliminaryToolResult:U=>{b.enqueue(U)}}).then(U=>{b.enqueue(U)}).catch(U=>{b.enqueue({type:"error",error:U})}).finally(()=>{w.delete(D),_()})}}catch(E){b.enqueue({type:"error",error:E})}break}case"tool-result":{const E=T.toolName,A=m.get(T.toolCallId);T.isError?b.enqueue({type:"tool-error",toolCallId:T.toolCallId,toolName:E,input:g.get(T.toolCallId),providerExecuted:!0,error:T.result,dynamic:T.dynamic,...T.providerMetadata!=null?{providerMetadata:T.providerMetadata}:{},...A?.toolMetadata!=null?{toolMetadata:A.toolMetadata}:{}}):R.enqueue({type:"tool-result",toolCallId:T.toolCallId,toolName:E,input:g.get(T.toolCallId),output:T.result,providerExecuted:!0,dynamic:T.dynamic,...T.providerMetadata!=null?{providerMetadata:T.providerMetadata}:{},...A?.toolMetadata!=null?{toolMetadata:A.toolMetadata}:{}});break}default:{const E=x;throw new Error(`Unhandled chunk type: ${E}`)}}},flush(){S=!0,_()}});return new ReadableStream({async start(T){return Promise.all([t.pipeThrough($).pipeTo(new WritableStream({write(R){T.enqueue(R)},close(){}})),y.pipeTo(new WritableStream({write(R){T.enqueue(R)},close(){T.close()}}))])}})}var originalGenerateId2=createIdGenerator$1({prefix:"aitxt",size:24}),isOutputChunkType={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 streamText({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:s,maxRetries:i,abortSignal:l,timeout:c,headers:u,stopWhen:d=stepCountIs(1),experimental_output:p,output:f=p,experimental_telemetry:h,prepareStep:b,providerOptions:y,experimental_activeTools:w,activeTools:g=w,experimental_repairToolCall:m,experimental_transform:S,experimental_download:v,includeRawChunks:_=!1,onChunk:$,onError:T=({error:N})=>{console.error(N)},onFinish:R,onAbort:x,onStepFinish:E,experimental_onStart:A,experimental_onStepStart:D,experimental_onToolCallStart:U,experimental_onToolCallFinish:K,experimental_context:G,experimental_toolApprovalSecret:te,experimental_include:X,_internal:{now:ue=now,generateId:V=originalGenerateId2}={},...C}){const N=getTotalTimeoutMs(c),L=getStepTimeoutMs(c),I=getChunkTimeoutMs(c),k=L!=null?new AbortController:void 0,O=I!=null?new AbortController:void 0;return new DefaultStreamTextResult({model:resolveLanguageModel(e),telemetry:h,headers:u,settings:C,maxRetries:i,abortSignal:mergeAbortSignals(l,N!=null?AbortSignal.timeout(N):void 0,k?.signal,O?.signal),stepTimeoutMs:L,stepAbortController:k,chunkTimeoutMs:I,chunkAbortController:O,system:n,prompt:o,messages:a,allowSystemInMessages:s,tools:t,toolChoice:r,transforms:asArray(S),activeTools:g,repairToolCall:m,stopConditions:asArray(d),output:f,providerOptions:y,prepareStep:b,includeRawChunks:_,timeout:c,stopWhen:d,originalAbortSignal:l,onChunk:$,onError:T,onFinish:R,onAbort:x,onStepFinish:E,onStart:A,onStepStart:D,onToolCallStart:U,onToolCallFinish:K,now:ue,generateId:V,experimental_context:G,experimental_toolApprovalSecret:te,download:v,include:X})}function createOutputTransformStream(e){let t,r="",n="",o,a="";function s({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&s({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&s({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const d=typeof u.partial=="string"?u.partial:JSON.stringify(u.partial);d!==a&&(s({controller:l,partialOutput:u.partial}),a=d)}}})}var DefaultStreamTextResult=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:a,stepTimeoutMs:s,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:d,messages:p,allowSystemInMessages:f,tools:h,toolChoice:b,transforms:y,activeTools:w,repairToolCall:g,stopConditions:m,output:S,providerOptions:v,prepareStep:_,includeRawChunks:$,now:T,generateId:R,timeout:x,stopWhen:E,originalAbortSignal:A,onChunk:D,onError:U,onFinish:K,onAbort:G,onStepFinish:te,onStart:X,onStepStart:ue,onToolCallStart:V,onToolCallFinish:C,experimental_context:N,experimental_toolApprovalSecret:L,download:I,include:k}){this._totalUsage=new DelayedPromise,this._finishReason=new DelayedPromise,this._rawFinishReason=new DelayedPromise,this._steps=new DelayedPromise,this.outputSpecification=S,this.includeRawChunks=$,this.tools=h;const q=getGlobalTelemetryIntegration()(t?.integrations);let B,F=[];const j=[];let M,Z,H,J={},oe=[];const se=[];let _e;const Te=new Map;let Se,Q=createIdMap(),ve=createIdMap();const de=new TransformStream({async transform(Ie,xe){var Ne,Fe,He,Be;xe.enqueue(Ie);const{part:ie}=Ie;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 D?.({chunk:ie}),ie.type==="error"){const $e=wrapGatewayError(ie.error);NoOutputGeneratedError.isInstance($e)&&(_e=$e),await U({error:$e})}if(ie.type==="text-start"&&(Q[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},F.push(Q[ie.id])),ie.type==="text-delta"){const $e=Q[ie.id];if($e==null){xe.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}$e.text+=ie.text,$e.providerMetadata=(Ne=ie.providerMetadata)!=null?Ne:$e.providerMetadata}if(ie.type==="text-end"){const $e=Q[ie.id];if($e==null){xe.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}$e.providerMetadata=(Fe=ie.providerMetadata)!=null?Fe:$e.providerMetadata,delete Q[ie.id]}if(ie.type==="reasoning-start"&&(ve[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},F.push(ve[ie.id])),ie.type==="reasoning-delta"){const $e=ve[ie.id];if($e==null){xe.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}$e.text+=ie.text,$e.providerMetadata=(He=ie.providerMetadata)!=null?He:$e.providerMetadata}if(ie.type==="reasoning-end"){const $e=ve[ie.id];if($e==null){xe.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}$e.providerMetadata=(Be=ie.providerMetadata)!=null?Be:$e.providerMetadata,delete ve[ie.id]}if(ie.type==="file"&&F.push({type:"file",file:ie.file,...ie.providerMetadata!=null?{providerMetadata:ie.providerMetadata}:{}}),ie.type==="source"&&F.push(ie),ie.type==="tool-call"&&F.push(ie),ie.type==="tool-result"&&!ie.preliminary&&F.push(ie),ie.type==="tool-approval-request"&&F.push(ie),ie.type==="tool-error"&&F.push(ie),ie.type==="start-step"&&(F=[],ve=createIdMap(),Q=createIdMap(),J=ie.request,oe=ie.warnings),ie.type==="finish-step"){const $e=await toResponseMessages({content:F,tools:h}),be=new DefaultStepResult({stepNumber:se.length,model:Ee,...Ye,experimental_context:N,content:F,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:oe,request:J,response:{...ie.response,messages:[...j,...$e]},providerMetadata:ie.providerMetadata});await notify({event:be,callbacks:[te,q.onStepFinish]}),logWarnings({warnings:oe,provider:Ee.provider,model:Ee.modelId}),se.push(be),j.push(...$e),B.resolve()}ie.type==="finish"&&(H=ie.totalUsage,M=ie.finishReason,Z=ie.rawFinishReason)},async flush(Ie){var xe,Ne,Fe,He,Be,ie,$e;try{if(se.length===0||_e!=null){const we=a?.aborted?a.reason:_e??new NoOutputGeneratedError({message:"No output generated. Check the stream for errors."});he._finishReason.reject(we),he._rawFinishReason.reject(we),he._totalUsage.reject(we),he._steps.reject(we);return}const be=M??"other",ke=H??createNullLanguageModelUsage();he._finishReason.resolve(be),he._rawFinishReason.resolve(Z),he._totalUsage.resolve(ke),he._steps.resolve(se);const ge=se[se.length-1];await notify({event:{stepNumber:ge.stepNumber,model:ge.model,functionId:ge.functionId,metadata:ge.metadata,experimental_context:ge.experimental_context,finishReason:ge.finishReason,rawFinishReason:ge.rawFinishReason,totalUsage:ke,usage:ge.usage,content:ge.content,text:ge.text,reasoningText:ge.reasoningText,reasoning:ge.reasoning,files:ge.files,sources:ge.sources,toolCalls:ge.toolCalls,staticToolCalls:ge.staticToolCalls,dynamicToolCalls:ge.dynamicToolCalls,toolResults:ge.toolResults,staticToolResults:ge.staticToolResults,dynamicToolResults:ge.dynamicToolResults,request:ge.request,response:ge.response,warnings:ge.warnings,providerMetadata:ge.providerMetadata,steps:se},callbacks:[K,q.onFinish]}),Se.setAttributes(await selectTelemetryAttributes({telemetry:t,attributes:{"ai.response.finishReason":be,"ai.response.text":{output:()=>ge.text},"ai.response.reasoning":{output:()=>ge.reasoningText},"ai.response.toolCalls":{output:()=>{var we;return(we=ge.toolCalls)!=null&&we.length?JSON.stringify(ge.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ge.providerMetadata),"ai.usage.inputTokens":ke.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(xe=ke.inputTokenDetails)==null?void 0:xe.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ne=ke.inputTokenDetails)==null?void 0:Ne.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Fe=ke.inputTokenDetails)==null?void 0:Fe.cacheWriteTokens,"ai.usage.outputTokens":ke.outputTokens,"ai.usage.outputTokenDetails.textTokens":(He=ke.outputTokenDetails)==null?void 0:He.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Be=ke.outputTokenDetails)==null?void 0:Be.reasoningTokens,"ai.usage.totalTokens":ke.totalTokens,"ai.usage.reasoningTokens":(ie=ke.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":($e=ke.inputTokenDetails)==null?void 0:$e.cacheReadTokens}}))}catch(be){Ie.error(be)}finally{Se.end()}}}),ne=createStitchableStream();this.addStream=ne.addStream,this.closeStream=ne.close;const ae=ne.stream.getReader();let ee=new ReadableStream({async start(Ie){Ie.enqueue({type:"start"})},async pull(Ie){function xe(){G?.({steps:se}),Ie.enqueue({type:"abort",...a?.reason!==void 0?{reason:getErrorMessage$2(a.reason)}:{}}),Ie.close()}try{const{done:Ne,value:Fe}=await ae.read();if(Ne){Ie.close();return}if(a?.aborted){xe();return}Ie.enqueue(Fe)}catch(Ne){isAbortError$1(Ne)&&a?.aborted?xe():Ie.error(Ne)}},cancel(Ie){return ne.stream.cancel(Ie)}});for(const Ie of y)ee=ee.pipeThrough(Ie({tools:h,stopStream(){ne.terminate()}}));this.baseStream=ee.pipeThrough(createOutputTransformStream(S??text())).pipeThrough(de);const{maxRetries:Y,retry:ce}=prepareRetries({maxRetries:o,abortSignal:a}),le=getTracer(t),P=prepareCallSettings(n),W=getBaseTelemetryAttributes({model:e,telemetry:t,headers:r,settings:{...P,maxRetries:Y}}),he=this,Ee={provider:e.provider,modelId:e.modelId},Ye={functionId:t?.functionId,metadata:t?.metadata};recordSpan({name:"ai.streamText",attributes:selectTelemetryAttributes({telemetry:t,attributes:{...assembleOperationName({operationId:"ai.streamText",telemetry:t}),...W,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:d,messages:p})}}}),tracer:le,endWhenDone:!1,fn:async Ie=>{Se=Ie;const xe=await standardizePrompt({system:u,prompt:d,messages:p,allowSystemInMessages:f});await notify({event:{model:Ee,system:u,prompt:d,messages:p,tools:h,toolChoice:b,activeTools:w,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:Y,timeout:x,headers:r,providerOptions:v,stopWhen:E,output:S,abortSignal:A,include:k,...Ye,experimental_context:N},callbacks:[X,q.onStart]});const Ne=xe.messages,Fe=[],{approvedToolApprovals:He,deniedToolApprovals:Be}=collectToolApprovals({messages:Ne});if(Be.length>0||He.length>0){const{approvedToolApprovals:$e,deniedToolApprovals:be}=await validateApprovedToolApprovals({approvedToolApprovals:He.filter(fe=>!fe.toolCall.providerExecuted),tools:h,messages:Ne,experimental_context:N,toolApprovalSecret:L}),ke=[...Be.filter(fe=>!fe.toolCall.providerExecuted),...be],ge=Be.filter(fe=>fe.toolCall.providerExecuted);let we;const Qe=new ReadableStream({start(fe){we=fe}});he.addStream(Qe);try{for(const Re of[...ke,...ge])we?.enqueue({type:"tool-output-denied",toolCallId:Re.toolCall.toolCallId,toolName:Re.toolCall.toolName});const fe=[];if(await Promise.all($e.map(async Re=>{const Pe=await executeToolCall({toolCall:Re.toolCall,tools:h,tracer:le,telemetry:t,messages:Ne,abortSignal:a,experimental_context:N,stepNumber:se.length,model:Ee,onToolCallStart:[V,q.onToolCallStart],onToolCallFinish:[C,q.onToolCallFinish],onPreliminaryToolResult:Le=>{we?.enqueue(Le)}});Pe!=null&&(we?.enqueue(Pe),fe.push(Pe))})),fe.length>0||ke.length>0){const Re=[];for(const Pe of fe)Re.push({type:"tool-result",toolCallId:Pe.toolCallId,toolName:Pe.toolName,output:await createToolModelOutput({toolCallId:Pe.toolCallId,input:Pe.input,tool:h?.[Pe.toolName],output:Pe.type==="tool-result"?Pe.output:Pe.error,errorMode:Pe.type==="tool-error"?"text":"none"})});for(const Pe of ke)Re.push({type:"tool-result",toolCallId:Pe.toolCall.toolCallId,toolName:Pe.toolCall.toolName,output:{type:"execution-denied",reason:Pe.approvalResponse.reason}});Fe.push({role:"tool",content:Re})}}finally{we?.close()}}j.push(...Fe);async function ie({currentStep:$e,responseMessages:be,usage:ke}){var ge,we,Qe,fe,Re,Pe,Le,qe,ye;const ze=he.includeRawChunks,et=s!=null?setTimeout(()=>i.abort(),s):void 0;let Xe;function St(){l!=null&&(Xe!=null&&clearTimeout(Xe),Xe=setTimeout(()=>c.abort(),l))}function tt(){Xe!=null&&(clearTimeout(Xe),Xe=void 0)}function st(){et!=null&&clearTimeout(et)}try{B=new DelayedPromise;const rt=[...Ne,...be],Ae=await _?.({model:e,steps:se,stepNumber:se.length,messages:rt,experimental_context:N}),Ge=resolveLanguageModel((ge=Ae?.model)!=null?ge:e),nt={provider:Ge.provider,modelId:Ge.modelId},lt=await convertToLanguageModelPrompt({prompt:{system:(we=Ae?.system)!=null?we:xe.system,messages:(Qe=Ae?.messages)!=null?Qe:rt},supportedUrls:await Ge.supportedUrls,download:I}),Tt=(fe=Ae?.activeTools)!=null?fe:w,{toolChoice:it,tools:ht}=await prepareToolsAndToolChoice({tools:h,toolChoice:(Re=Ae?.toolChoice)!=null?Re:b,activeTools:Tt});N=(Pe=Ae?.experimental_context)!=null?Pe:N;const Rt=(Le=Ae?.messages)!=null?Le:rt,xt=(qe=Ae?.system)!=null?qe:xe.system,ft=mergeObjects(v,Ae?.providerOptions);await notify({event:{stepNumber:se.length,model:nt,system:xt,messages:Rt,tools:h,toolChoice:it,activeTools:Tt,steps:[...se],providerOptions:ft,timeout:x,headers:r,stopWhen:E,output:S,abortSignal:A,include:k,...Ye,experimental_context:N},callbacks:[ue,q.onStepStart]});const{result:{stream:me,response:Ue,request:Je},doStreamSpan:je,startTimestampMs:mt}=await ce(()=>recordSpan({name:"ai.streamText.doStream",attributes:selectTelemetryAttributes({telemetry:t,attributes:{...assembleOperationName({operationId:"ai.streamText.doStream",telemetry:t}),...W,"ai.model.provider":Ge.provider,"ai.model.id":Ge.modelId,"ai.prompt.messages":{input:()=>stringifyForTelemetry(lt)},"ai.prompt.tools":{input:()=>ht?.map(pe=>JSON.stringify(pe))},"ai.prompt.toolChoice":{input:()=>it!=null?JSON.stringify(it):void 0},"gen_ai.system":Ge.provider,"gen_ai.request.model":Ge.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:le,endWhenDone:!1,fn:async pe=>({startTimestampMs:T(),doStreamSpan:pe,result:await Ge.doStream({...P,tools:ht,toolChoice:it,responseFormat:await S?.responseFormat,prompt:lt,providerOptions:ft,abortSignal:a,headers:r,includeRawChunks:ze})})})),Et=runToolsTransformation({tools:h,generatorStream:me,tracer:le,telemetry:t,system:u,messages:rt,repairToolCall:g,abortSignal:a,experimental_context:N,toolApprovalSecret:L,generateId:R,stepNumber:se.length,model:nt,onToolCallStart:[V,q.onToolCallStart],onToolCallFinish:[C,q.onToolCallFinish]}),Ct=(ye=k?.requestBody)==null||ye?Je??{}:{...Je,body:void 0},ot=[],at=[];let ct;const Ce={};let Ve="other",gt,ut=!1,Dt=!1,Ze=createNullLanguageModelUsage(),qt,Ut=!0,Ke={id:R(),timestamp:new Date,modelId:Ee.modelId},Wt="";he.addStream(Et.pipeThrough(new TransformStream({async transform(pe,Oe){var yt,vt,_t,bt,wt;if(St(),pe.type==="stream-start"){ct=pe.warnings;return}if(Ut){const Me=T()-mt;Ut=!1,je.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Me}),je.setAttributes({"ai.response.msToFirstChunk":Me}),Oe.enqueue({type:"start-step",request:Ct,warnings:ct??[]})}const dt=pe.type;switch(isOutputChunkType[dt]&&(Dt=!0),dt){case"tool-approval-request":case"text-start":case"text-end":{Oe.enqueue(pe);break}case"text-delta":{pe.delta.length>0&&(Oe.enqueue({type:"text-delta",id:pe.id,text:pe.delta,providerMetadata:pe.providerMetadata}),Wt+=pe.delta);break}case"reasoning-start":case"reasoning-end":{Oe.enqueue(pe);break}case"reasoning-delta":{Oe.enqueue({type:"reasoning-delta",id:pe.id,text:pe.delta,providerMetadata:pe.providerMetadata});break}case"tool-call":{Oe.enqueue(pe),ot.push(pe);break}case"tool-result":{Oe.enqueue(pe),pe.preliminary||at.push(pe);break}case"tool-error":{Oe.enqueue(pe),at.push(pe);break}case"response-metadata":{Ke={id:(yt=pe.id)!=null?yt:Ke.id,timestamp:(vt=pe.timestamp)!=null?vt:Ke.timestamp,modelId:(_t=pe.modelId)!=null?_t:Ke.modelId};break}case"finish":{ut=!0,Ze=pe.usage,Ve=pe.finishReason,gt=pe.rawFinishReason,qt=pe.providerMetadata;const Me=T()-mt;je.addEvent("ai.stream.finish"),je.setAttributes({"ai.response.msToFinish":Me,"ai.response.avgOutputTokensPerSecond":1e3*((bt=Ze.outputTokens)!=null?bt:0)/Me});break}case"file":{Oe.enqueue(pe);break}case"source":{Oe.enqueue(pe);break}case"tool-input-start":{Ce[pe.id]=pe.toolName;const Me=h?.[pe.toolName];Me?.onInputStart!=null&&await Me.onInputStart({toolCallId:pe.id,messages:rt,abortSignal:a,experimental_context:N}),Oe.enqueue({...pe,dynamic:(wt=pe.dynamic)!=null?wt:Me?.type==="dynamic",title:Me?.title});break}case"tool-input-end":{delete Ce[pe.id],Oe.enqueue(pe);break}case"tool-input-delta":{const Me=Ce[pe.id],pt=h?.[Me];pt?.onInputDelta!=null&&await pt.onInputDelta({inputTextDelta:pe.delta,toolCallId:pe.id,messages:rt,abortSignal:a,experimental_context:N}),Oe.enqueue(pe);break}case"error":{ut=!0,Oe.enqueue(pe),Ve="error";break}case"raw":{ze&&Oe.enqueue(pe);break}default:{const Me=dt;throw new Error(`Unknown chunk type: ${Me}`)}}},async flush(pe){var Oe,yt,vt,_t,bt,wt,dt;if(!ut&&!Dt){pe.enqueue({type:"error",error:new NoOutputGeneratedError({message:"No output generated. The model stream ended without a finish chunk."})}),je.end(),st(),tt(),he.closeStream();return}const Me=ot.length>0?JSON.stringify(ot):void 0;try{je.setAttributes(await selectTelemetryAttributes({telemetry:t,attributes:{"ai.response.finishReason":Ve,"ai.response.toolCalls":{output:()=>Me},"ai.response.id":Ke.id,"ai.response.model":Ke.modelId,"ai.response.timestamp":Ke.timestamp.toISOString(),"ai.usage.inputTokens":Ze.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Oe=Ze.inputTokenDetails)==null?void 0:Oe.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(yt=Ze.inputTokenDetails)==null?void 0:yt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(vt=Ze.inputTokenDetails)==null?void 0:vt.cacheWriteTokens,"ai.usage.outputTokens":Ze.outputTokens,"ai.usage.outputTokenDetails.textTokens":(_t=Ze.outputTokenDetails)==null?void 0:_t.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(bt=Ze.outputTokenDetails)==null?void 0:bt.reasoningTokens,"ai.usage.totalTokens":Ze.totalTokens,"ai.usage.reasoningTokens":(wt=Ze.outputTokenDetails)==null?void 0:wt.reasoningTokens,"ai.usage.cachedInputTokens":(dt=Ze.inputTokenDetails)==null?void 0:dt.cacheReadTokens,"gen_ai.response.finish_reasons":[Ve],"gen_ai.response.id":Ke.id,"gen_ai.response.model":Ke.modelId,"gen_ai.usage.input_tokens":Ze.inputTokens,"gen_ai.usage.output_tokens":Ze.outputTokens}}))}catch{}pe.enqueue({type:"finish-step",finishReason:Ve,rawFinishReason:gt,usage:Ze,providerMetadata:qt,response:{...Ke,headers:Ue?.headers}});const pt=addLanguageModelUsage(ke,Ze);await B.promise;const kt=se[se.length-1];try{je.setAttributes(await selectTelemetryAttributes({telemetry:t,attributes:{"ai.response.text":{output:()=>kt.text},"ai.response.reasoning":{output:()=>kt.reasoningText},"ai.response.providerMetadata":JSON.stringify(kt.providerMetadata)}}))}catch{}finally{je.end()}const Zt=ot.filter(De=>De.providerExecuted!==!0),Jt=at.filter(De=>De.providerExecuted!==!0);for(const De of ot){if(De.providerExecuted!==!0)continue;const Pt=h?.[De.toolName];Pt?.type==="provider"&&Pt.supportsDeferredResults&&(at.some(At=>(At.type==="tool-result"||At.type==="tool-error")&&At.toolCallId===De.toolCallId)||Te.set(De.toolCallId,{toolName:De.toolName}))}for(const De of at)(De.type==="tool-result"||De.type==="tool-error")&&Te.delete(De.toolCallId);if(st(),tt(),(Zt.length>0&&Jt.length===Zt.length||Te.size>0)&&!await isStopConditionMet({stopConditions:m,steps:se})){be.push(...await toResponseMessages({content:se[se.length-1].content,tools:h}));try{await ie({currentStep:$e+1,responseMessages:be,usage:pt})}catch(De){pe.enqueue({type:"error",error:De}),he.closeStream()}}else pe.enqueue({type:"finish",finishReason:Ve,rawFinishReason:gt,totalUsage:pt}),he.closeStream()}})))}finally{st(),tt()}}await ie({currentStep:0,responseMessages:Fe,usage:createNullLanguageModelUsage()})}}).catch(Ie=>{he.addStream(new ReadableStream({start(xe){xe.enqueue({type:"error",error:Ie}),xe.close()}})),he.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return createAsyncIterableStream(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 consumeStream({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 createAsyncIterableStream(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 UnsupportedFunctionalityError$1({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return createAsyncIterableStream(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:text()).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:s=!0,sendFinish:i=!0,onError:l=()=>"An error occurred."}={}){const c=t!=null?getResponseUIMessageId({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var f;const h=(f=this.tools)==null?void 0:f[p.toolName];return h==null?p.dynamic:h?.type==="dynamic"?!0:void 0},d=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const h=n?.({part:p}),b=p.type;switch(b){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{o&&f.enqueue({type:b,id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.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"&&f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),a&&p.sourceType==="document"&&f.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 y=u(p);f.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}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const y=u(p);p.invalid?f.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}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):f.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}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{f.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId,...p.signature!=null?{signature:p.signature}:{}});break}case"tool-result":{const y=u(p);f.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}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=u(p);f.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}:{},...y!=null?{dynamic:y}:{}});break}case"tool-output-denied":{f.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{f.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{s&&f.enqueue({type:"start",...h!=null?{messageMetadata:h}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:p.finishReason,...h!=null?{messageMetadata:h}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=b;throw new Error(`Unknown chunk type: ${y}`)}}h!=null&&b!=="start"&&b!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:h})}}));return createAsyncIterableStream(handleUIMessageStreamFinish({stream:d,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:s,sendFinish:i,sendStart:l,onError:c,...u}={}){pipeUIMessageStreamToResponse({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:s,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){pipeTextStreamToResponse({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:i,onError:l,...c}={}){return createUIMessageStreamResponse({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return createTextStreamResponse({textStream:this.textStream,...e})}};record(string(),jsonValueSchema$1.optional()),createIdGenerator$1({prefix:"aiobj",size:24}),createIdGenerator$1({prefix:"aiobj",size:24});var name$1="AI_MCPClientError",marker$1=`vercel.ai.error.${name$1}`,symbol$1=Symbol.for(marker$1),_a$1,_b,MCPClientError=class extends(_b=AISDKError$1,_a$1=symbol$1,_b){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o,statusCode:a,url:s,responseBody:i}){super({name:e,message:t,cause:r}),this[_a$1]=!0,this.data=n,this.code=o,this.statusCode=a,this.url=s,this.responseBody=i}static isInstance(e){return AISDKError$1.hasMarker(e,marker$1)}},LATEST_PROTOCOL_VERSION="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05"],ToolMetaSchema=optional(record(string(),unknown())),ClientOrServerImplementationSchema=looseObject({name:string(),version:string(),title:optional(string())}),BaseParamsSchema=looseObject({_meta:optional(object$2({}).loose())}),ResultSchema=BaseParamsSchema,RequestSchema=object$2({method:string(),params:optional(BaseParamsSchema)}),ElicitationCapabilitySchema=object$2({applyDefaults:optional(boolean())}).loose(),ServerCapabilitiesSchema=looseObject({experimental:optional(object$2({}).loose()),logging:optional(object$2({}).loose()),completions:optional(object$2({}).loose()),prompts:optional(looseObject({listChanged:optional(boolean())})),resources:optional(looseObject({subscribe:optional(boolean()),listChanged:optional(boolean())})),tools:optional(looseObject({listChanged:optional(boolean())})),elicitation:optional(ElicitationCapabilitySchema)});object$2({elicitation:optional(ElicitationCapabilitySchema)}).loose();var InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ClientOrServerImplementationSchema,instructions:optional(string())}),PaginatedResultSchema=ResultSchema.extend({nextCursor:optional(string())}),ToolSchema=object$2({name:string(),title:optional(string()),description:optional(string()),inputSchema:object$2({type:literal("object"),properties:optional(object$2({}).loose())}).loose(),outputSchema:optional(object$2({}).loose()),annotations:optional(object$2({title:optional(string())}).loose()),_meta:ToolMetaSchema}).loose(),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array$1(ToolSchema)}),TextContentSchema=object$2({type:literal("text"),text:string()}).loose(),ImageContentSchema=object$2({type:literal("image"),data:base64(),mimeType:string()}).loose(),ResourceSchema=object$2({uri:string(),name:string(),title:optional(string()),description:optional(string()),mimeType:optional(string()),size:optional(number$1())}).loose(),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array$1(ResourceSchema)}),ResourceContentsSchema=object$2({uri:string(),name:optional(string()),title:optional(string()),mimeType:optional(string())}).loose(),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:base64()}),EmbeddedResourceSchema=object$2({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema])}).loose(),ResourceLinkContentSchema=object$2({type:literal("resource_link"),uri:string(),name:string(),description:optional(string()),mimeType:optional(string())}).loose(),CallToolResultSchema=ResultSchema.extend({content:array$1(union([TextContentSchema,ImageContentSchema,EmbeddedResourceSchema,ResourceLinkContentSchema])),structuredContent:optional(unknown()),isError:boolean().default(!1).optional()}).or(ResultSchema.extend({toolResult:unknown()})),ResourceTemplateSchema=object$2({uriTemplate:string(),name:string(),title:optional(string()),description:optional(string()),mimeType:optional(string())}).loose(),ListResourceTemplatesResultSchema=ResultSchema.extend({resourceTemplates:array$1(ResourceTemplateSchema)}),ReadResourceResultSchema=ResultSchema.extend({contents:array$1(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),PromptReferenceSchema=object$2({type:literal("ref/prompt"),name:string()}).loose(),ResourceReferenceSchema=object$2({type:literal("ref/resource"),uri:string()}).loose(),CompletionArgumentSchema=object$2({name:string(),value:string()}).loose();BaseParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceReferenceSchema]),argument:CompletionArgumentSchema,context:optional(object$2({arguments:record(string(),string())}).loose())});var CompleteResultSchema=ResultSchema.extend({completion:object$2({values:array$1(string()).max(100),total:optional(number$1().int()),hasMore:optional(boolean())}).loose()}),PromptArgumentSchema=object$2({name:string(),description:optional(string()),required:optional(boolean())}).loose(),PromptSchema=object$2({name:string(),title:optional(string()),description:optional(string()),arguments:optional(array$1(PromptArgumentSchema))}).loose(),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array$1(PromptSchema)}),PromptMessageSchema=object$2({role:union([literal("user"),literal("assistant")]),content:union([TextContentSchema,ImageContentSchema,EmbeddedResourceSchema,ResourceLinkContentSchema])}).loose(),GetPromptResultSchema=ResultSchema.extend({description:optional(string()),messages:array$1(PromptMessageSchema)}),ElicitationRequestParamsSchema=BaseParamsSchema.extend({message:string(),requestedSchema:unknown()}),ElicitationRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitationRequestParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:union([literal("accept"),literal("decline"),literal("cancel")]),content:optional(record(string(),unknown()))}),JSONRPC_VERSION="2.0",JSONRPCRequestSchema=object$2({jsonrpc:literal(JSONRPC_VERSION),id:union([string(),number$1().int()])}).merge(RequestSchema).strict(),JSONRPCResponseSchema=object$2({jsonrpc:literal(JSONRPC_VERSION),id:union([string(),number$1().int()]),result:ResultSchema}).strict(),JSONRPCErrorSchema=object$2({jsonrpc:literal(JSONRPC_VERSION),id:union([string(),number$1().int()]),error:object$2({code:number$1().int(),message:string(),data:optional(unknown())})}).strict(),JSONRPCNotificationSchema=object$2({jsonrpc:literal(JSONRPC_VERSION)}).merge(object$2({method:string(),params:optional(BaseParamsSchema)})).strict(),JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResponseSchema,JSONRPCErrorSchema]);async function parseJSONRPCMessage(e){return JSONRPCMessageSchema.parse(await parseJSON$1({text:e}))}var VERSION$3=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",SafeUrlSchema=string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).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"}),OAuthTokensSchema=object$2({access_token:string(),id_token:string().optional(),token_type:string(),expires_in:number$1().optional(),scope:string().optional(),refresh_token:string().optional(),authorization_server:SafeUrlSchema.optional(),token_endpoint:SafeUrlSchema.optional()}).strip(),OAuthProtectedResourceMetadataSchema=object$2({resource:string().url(),authorization_servers:array$1(SafeUrlSchema).optional(),jwks_uri:string().url().optional(),scopes_supported:array$1(string()).optional(),bearer_methods_supported:array$1(string()).optional(),resource_signing_alg_values_supported:array$1(string()).optional(),resource_name:string().optional(),resource_documentation:string().optional(),resource_policy_uri:string().url().optional(),resource_tos_uri:string().url().optional(),tls_client_certificate_bound_access_tokens:boolean().optional(),authorization_details_types_supported:array$1(string()).optional(),dpop_signing_alg_values_supported:array$1(string()).optional(),dpop_bound_access_tokens_required:boolean().optional()}).passthrough(),OAuthMetadataSchema=object$2({issuer:string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array$1(string()).optional(),response_types_supported:array$1(string()),grant_types_supported:array$1(string()).optional(),code_challenge_methods_supported:array$1(string()),token_endpoint_auth_methods_supported:array$1(string()).optional(),token_endpoint_auth_signing_alg_values_supported:array$1(string()).optional()}).passthrough(),OpenIdProviderMetadataSchema=object$2({issuer:string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array$1(string()).optional(),response_types_supported:array$1(string()),grant_types_supported:array$1(string()).optional(),subject_types_supported:array$1(string()),id_token_signing_alg_values_supported:array$1(string()),claims_supported:array$1(string()).optional(),token_endpoint_auth_methods_supported:array$1(string()).optional()}).passthrough(),OpenIdProviderDiscoveryMetadataSchema=OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({code_challenge_methods_supported:!0})),OAuthClientInformationSchema=object$2({client_id:string(),client_secret:string().optional(),client_id_issued_at:number$1().optional(),client_secret_expires_at:number$1().optional(),authorization_server:SafeUrlSchema.optional(),token_endpoint:SafeUrlSchema.optional()}).strip(),OAuthClientMetadataSchema=object$2({redirect_uris:array$1(SafeUrlSchema),token_endpoint_auth_method:string().optional(),grant_types:array$1(string()).optional(),response_types:array$1(string()).optional(),client_name:string().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:SafeUrlSchema.optional(),scope:string().optional(),contacts:array$1(string()).optional(),tos_uri:SafeUrlSchema.optional(),policy_uri:string().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string().optional(),software_version:string().optional(),software_statement:string().optional()}).strip(),OAuthErrorResponseSchema=object$2({error:string(),error_description:string().optional(),error_uri:string().optional()}),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),name2$1="AI_MCPClientOAuthError",marker2$1=`vercel.ai.error.${name2$1}`,symbol2$1=Symbol.for(marker2$1),_a2$1,_b2,MCPClientOAuthError=class extends(_b2=AISDKError$1,_a2$1=symbol2$1,_b2){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[_a2$1]=!0}static isInstance(e){return AISDKError$1.hasMarker(e,marker2$1)}},ServerError=class extends MCPClientOAuthError{};ServerError.errorCode="server_error";var InvalidClientError=class extends MCPClientOAuthError{};InvalidClientError.errorCode="invalid_client";var InvalidGrantError=class extends MCPClientOAuthError{};InvalidGrantError.errorCode="invalid_grant";var UnauthorizedClientError=class extends MCPClientOAuthError{};UnauthorizedClientError.errorCode="unauthorized_client";var OAUTH_ERRORS={[ServerError.errorCode]:ServerError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError};function resourceUrlFromServerUrl(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function resourceUrlStripSlash(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function checkResourceAllowed({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 UnauthorizedError=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function normalizeUrl(e){return new URL(e).href}function createAuthorizationServerInformation(e,t){return{authorizationServerUrl:normalizeUrl(e),tokenEndpoint:normalizeUrl(t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e))}}function addAuthorizationServerInformationToTokens(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function addAuthorizationServerInformationToClientInformation(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function getAuthorizationServerInformationFromCredentials(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:normalizeUrl(e.authorization_server),tokenEndpoint:normalizeUrl(e.token_endpoint)}}async function getStoredAuthorizationServerInformation({provider:e,clientInformation:t,tokens:r}){var n;const o=getAuthorizationServerInformationFromCredentials(r);if(o)return o;const a=await((n=e.authorizationServerInformation)==null?void 0:n.call(e));return a?{authorizationServerUrl:normalizeUrl(a.authorizationServerUrl),tokenEndpoint:normalizeUrl(a.tokenEndpoint)}:getAuthorizationServerInformationFromCredentials(t)}async function saveAuthorizationServerInformation({provider:e,clientInformation:t,authorizationServerInformation:r}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(r),!0):e.saveClientInformation?(await e.saveClientInformation(addAuthorizationServerInformationToClientInformation(t,r)),!0):!1}function assertResourceMetadataUrlSameOrigin(e,t){if(!t)return;const r=new URL(e).origin;if(t.origin!==r)throw new MCPClientOAuthError({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${r}`})}function assertAuthorizationServerInformationMatches({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new MCPClientOAuthError({message:"OAuth authorization server metadata does not match the metadata that issued the stored credentials"})}function extractResourceMetadataUrl(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="([^"]*)"/,s=r.match(a);if(s)try{return new URL(s[1])}catch{return}}function buildWellKnownPath(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function fetchWithCorsRetry(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?fetchWithCorsRetry(e,void 0,r):void 0;throw n}}async function tryMetadataDiscovery(e,t,r=fetch){return await fetchWithCorsRetry(e,{"MCP-Protocol-Version":t},r)}function shouldAttemptFallback(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function discoverMetadataWithFallback(e,t,r,n){var o,a;const s=new URL(e),i=(o=n?.protocolVersion)!=null?o:LATEST_PROTOCOL_VERSION;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=buildWellKnownPath(t,s.pathname);l=new URL(u,(a=n?.metadataServerUrl)!=null?a:s),l.search=s.search}let c=await tryMetadataDiscovery(l,i,r);if(!n?.metadataUrl&&shouldAttemptFallback(c,s.pathname)){const u=new URL(`/.well-known/${t}`,s);c=await tryMetadataDiscovery(u,i,r)}return c}async function discoverOAuthProtectedResourceMetadata(e,t,r=fetch){const n=await discoverMetadataWithFallback(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 OAuthProtectedResourceMetadataSchema.parse(await n.json())}function buildDiscoveryUrls(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 s=`${t.origin}${a}`;return o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth",expectedIssuer:s}),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:s}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc",expectedIssuer:s}),o}function assertMetadataIssuerMatches(e,t){if(e.issuer!==t)throw new MCPClientOAuthError({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function discoverAuthorizationServerMetadata(e,{fetchFn:t=fetch,protocolVersion:r=LATEST_PROTOCOL_VERSION}={}){var n;const o={"MCP-Protocol-Version":r},a=buildDiscoveryUrls(e);for(const{url:s,type:i,expectedIssuer:l}of a){const c=await fetchWithCorsRetry(s,o,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(i==="oauth"){const u=OAuthMetadataSchema.parse(await c.json());return assertMetadataIssuerMatches(u,l),u}else{const u=OpenIdProviderDiscoveryMetadataSchema.parse(await c.json());if(assertMetadataIssuerMatches(u,l),!((n=u.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function startAuthorization(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:s}){const i="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);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 pkceChallenge(),d=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),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"),s&&c.searchParams.set("resource",resourceUrlStripSlash(s)),{authorizationUrl:c,codeVerifier:d}}function selectClientAuthMethod(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 applyClientAuthentication(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":applyBasicAuth(o,a,r);return;case"client_secret_post":applyPostAuth(o,a,n);return;case"none":applyPublicAuth(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function applyBasicAuth(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 applyPostAuth(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function applyPublicAuth(e,t){t.set("client_id",e)}async function parseErrorResponse(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=OAuthErrorResponseSchema.parse(await parseJSON$1({text:r})),{error:o,error_description:a,error_uri:s}=n,i=OAUTH_ERRORS[o]||ServerError;return new i({message:a||"",cause:s})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ServerError({message:o})}}async function exchangeAuthorization(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:a,resource:s,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(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"}),f=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(a)});if(i)await i(p,f,e,t);else{const b=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=selectClientAuthMethod(r,b);applyClientAuthentication(y,r,p,f)}s&&f.set("resource",resourceUrlStripSlash(s));const h=await(l??fetch)(d,{method:"POST",headers:p,body:f});if(!h.ok)throw await parseErrorResponse(h);return OAuthTokensSchema.parse(await h.json())}async function refreshAuthorization(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:s}){var i;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"}),d=new URLSearchParams({grant_type:l,refresh_token:n});if(a)await a(u,d,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],h=selectClientAuthMethod(r,f);applyClientAuthentication(h,r,u,d)}o&&d.set("resource",resourceUrlStripSlash(o));const p=await(s??fetch)(c,{method:"POST",headers:u,body:d});if(!p.ok)throw await parseErrorResponse(p);return OAuthTokensSchema.parse({refresh_token:n,...await p.json()})}async function registerClient(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 parseErrorResponse(a);return OAuthClientInformationFullSchema.parse(await a.json())}async function auth(e,t){var r,n;try{return await authInternal(e,t)}catch(o){if(o instanceof InvalidClientError||o instanceof UnauthorizedClientError)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await authInternal(e,t);if(o instanceof InvalidGrantError)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await authInternal(e,t);throw o}}async function selectResourceURL(e,t,r){const n=resourceUrlFromServerUrl(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!checkResourceAllowed({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 authInternal(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:a,fetchFn:s}){var i,l;let c,u;assertResourceMetadataUrlSameOrigin(t,a);try{c=await discoverOAuthProtectedResourceMetadata(t,{resourceMetadataUrl:a},s),c.authorization_servers&&c.authorization_servers.length>0&&(u=c.authorization_servers[0])}catch{}u||(u=t);const d=await selectResourceURL(t,e,c);await((i=e.validateAuthorizationServerURL)==null?void 0:i.call(e,t,u));const p=await discoverAuthorizationServerMetadata(u,{fetchFn:s}),f=createAuthorizationServerInformation(u,p);let h=await Promise.resolve(e.clientInformation());if(!h){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 S=await registerClient(u,{metadata:p,clientMetadata:e.clientMetadata,fetchFn:s});h=addAuthorizationServerInformationToClientInformation(S,f),await e.saveClientInformation(h)}if(r!==void 0){if(e.storedState){const $=await e.storedState();if($!==void 0&&$!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const S=await getStoredAuthorizationServerInformation({provider:e,clientInformation:h});if(!S)throw new MCPClientOAuthError({message:"Stored OAuth authorization server metadata is required when exchanging an authorization code"});assertAuthorizationServerInformationMatches({storedAuthorizationServerInformation:S,currentAuthorizationServerInformation:f});const v=await e.codeVerifier(),_=await exchangeAuthorization(u,{metadata:p,clientInformation:h,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(addAuthorizationServerInformationToTokens(_,f)),"AUTHORIZED"}const b=await e.tokens();if(b?.refresh_token){const S=await getStoredAuthorizationServerInformation({provider:e,clientInformation:h,tokens:b});S?assertAuthorizationServerInformationMatches({storedAuthorizationServerInformation:S,currentAuthorizationServerInformation:f}):await((l=e.invalidateCredentials)==null?void 0:l.call(e,"tokens"));try{if(S){const v=await refreshAuthorization(u,{metadata:p,clientInformation:h,refreshToken:b.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(addAuthorizationServerInformationToTokens(v,f)),"AUTHORIZED"}}catch(v){if(!(!(v instanceof MCPClientOAuthError)||v instanceof ServerError))throw v}}const y=e.state?await e.state():void 0;y&&e.saveState&&await e.saveState(y);const{authorizationUrl:w,codeVerifier:g}=await startAuthorization(u,{metadata:p,clientInformation:h,state:y,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:d});if(!await saveAuthorizationServerInformation({provider:e,clientInformation:h,authorizationServerInformation:f}))throw new MCPClientOAuthError({message:"OAuth authorization server metadata must be saveable before starting authorization"});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(w),"REDIRECT"}function isMessageEvent(e){return e===void 0||e==="message"}var SseMCPTransport=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:LATEST_PROTOCOL_VERSION};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return withUserAgentSuffix$1(r,`ai-sdk/${VERSION$3}`,getRuntimeEnvironmentUserAgent$1())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,a,s,i,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=extractResourceMetadataUrl(u);try{if(await auth(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const b=new UnauthorizedError;return(a=this.onerror)==null||a.call(this,b),t(b)}}catch(h){return(s=this.onerror)==null||s.call(this,h),t(h)}return r(!0)}if(!u.ok||!u.body){let h=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(h+=". This server does not support SSE transport. Try using `http` transport instead");const b=new MCPClientError({message:h});return(i=this.onerror)==null||i.call(this,b),t(b)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader(),f=async()=>{var h,b,y,w,g;try{for(;;){const{done:m,value:S}=await p.read();if(m){if(this.connected)throw this.connected=!1,new MCPClientError({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:v,data:_}=S;if(v==="endpoint"){if(this.endpoint)continue;const $=new URL(_,this.url);if($.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(h=this.sseConnection)==null||h.close(),(b=this.abortController)==null||b.abort(),new MCPClientError({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${$.origin}`});this.endpoint=$,this.connected=!0,e()}else if(isMessageEvent(v))try{const $=await parseJSONRPCMessage(_);(y=this.onmessage)==null||y.call(this,$)}catch($){const T=new MCPClientError({message:"MCP SSE Transport Error: Failed to parse message",cause:$});(w=this.onerror)==null||w.call(this,T)}}}catch(m){if(m instanceof Error&&m.name==="AbortError")return;(g=this.onerror)==null||g.call(this,m),t(m)}};this.sseConnection={close:()=>p.cancel()},f()}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 MCPClientError({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,a,s,i,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},d=await this.fetchFn(t.href,u);if(d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=extractResourceMetadataUrl(d);try{if(await auth(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const f=new UnauthorizedError;(a=this.onerror)==null||a.call(this,f);return}}catch(p){(s=this.onerror)==null||s.call(this,p);return}return r(!0)}if(!d.ok){const p=await d.text().catch(()=>null),f=new MCPClientError({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${p}`});(i=this.onerror)==null||i.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}};function isMessageEvent2(e){return e===void 0||e==="message"}var HttpMCPTransport=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:LATEST_PROTOCOL_VERSION};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 withUserAgentSuffix$1(r,`ai-sdk/${VERSION$3}`,getRuntimeEnvironmentUserAgent$1())}authorizeOnce(e){return this.authProvider?(this.authPromise||(this.authPromise=auth(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 MCPClientError({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,s,i,l,c;try{const d={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,d),f=p.headers.get("mcp-session-id");if(f&&(this.sessionId=f),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=extractResourceMetadataUrl(p);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED")throw new UnauthorizedError}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let g=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(g+=". This server does not support HTTP transport. Try using `sse` transport instead");const m=new MCPClientError({message:g,statusCode:p.status,url:this.url.href,responseBody:w??void 0});throw(a=this.onerror)==null||a.call(this,m),m}if(!("id"in e))return;const b=p.headers.get("content-type")||"";if(b.includes("application/json")){const w=await p.json(),g=Array.isArray(w)?w.map(m=>JSONRPCMessageSchema.parse(m)):[JSONRPCMessageSchema.parse(w)];for(const m of g)(s=this.onmessage)==null||s.call(this,m);return}if(b.includes("text/event-stream")){if(!p.body){const S=new MCPClientError({message:"MCP HTTP Transport Error: text/event-stream response without body",statusCode:p.status,url:this.url.href});throw(i=this.onerror)==null||i.call(this,S),S}const g=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader();(async()=>{var S,v,_;try{for(;;){const{done:$,value:T}=await g.read();if($)return;const{event:R,data:x}=T;if(isMessageEvent2(R))try{const E=await parseJSONRPCMessage(x);(S=this.onmessage)==null||S.call(this,E)}catch(E){const A=new MCPClientError({message:"MCP HTTP Transport Error: Failed to parse message",cause:E});(v=this.onerror)==null||v.call(this,A)}}}catch($){if($ instanceof Error&&$.name==="AbortError")return;(_=this.onerror)==null||_.call(this,$)}})();return}const y=new MCPClientError({message:`MCP HTTP Transport Error: Unexpected content type: ${b}`,statusCode:p.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,y),y}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 MCPClientError({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,s,i;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=extractResourceMetadataUrl(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED"){const b=new UnauthorizedError;(n=this.onerror)==null||n.call(this,b);return}}catch(h){(o=this.onerror)==null||o.call(this,h);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const h=new MCPClientError({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,h);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader(),f=async()=>{var h,b,y,w;try{for(;;){const{done:g,value:m}=await p.read();if(g)return;const{event:S,data:v,id:_}=m;if(_&&(this.lastInboundEventId=_),isMessageEvent2(S))try{const $=await parseJSONRPCMessage(v);(h=this.onmessage)==null||h.call(this,$)}catch($){const T=new MCPClientError({message:"MCP HTTP Transport Error: Failed to parse message",cause:$});(b=this.onerror)==null||b.call(this,T)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(y=this.onerror)==null||y.call(this,g),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,f()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(s=this.onerror)==null||s.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function createMcpTransport(e){switch(e.type){case"sse":return new SseMCPTransport(e);case"http":return new HttpMCPTransport(e);default:throw new MCPClientError({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function isCustomMcpTransport(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var CLIENT_VERSION="1.0.0";function mcpToModelOutput({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 createMCPClient(e){const t=new DefaultMCPClient(e);return await t.init(),t}var DefaultMCPClient=class{constructor({transport:e,name:t,clientName:r=t??"ai-sdk-mcp-client",version:n=CLIENT_VERSION,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??{},isCustomMcpTransport(e)?this.transport=e:this.transport=createMcpTransport(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new MCPClientError({message:"Unsupported message type"}));return}this.onResponse(s)},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:LATEST_PROTOCOL_VERSION,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:InitializeResultSchema});if(e===void 0)throw new MCPClientError({message:"Server sent invalid initialize result"});if(!SUPPORTED_PROTOCOL_VERSIONS.includes(e.protocolVersion))throw new MCPClientError({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 MCPClientError({message:"Server does not support completions"});break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new MCPClientError({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new MCPClientError({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new MCPClientError({message:"Server does not support prompts"});break;default:throw new MCPClientError({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new MCPClientError({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=r?.signal;a?.throwIfAborted();const s=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:s},l=()=>{this.responseHandlers.delete(s)};this.responseHandlers.set(s,c=>{if(a?.aborted)return o(new MCPClientError({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 d=new MCPClientError({message:"Failed to parse server response",cause:u});o(d)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:ListToolsResultSchema,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:CallToolResultSchema,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:ListResourcesResultSchema,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:ReadResourceResultSchema,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:ListResourceTemplatesResultSchema,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:ListPromptsResultSchema,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:GetPromptResultSchema,options:r})}catch(n){throw n}}async completeInternal({options:e,...t}){return this.request({request:{method:"completion/complete",params:t},resultSchema:CompleteResultSchema,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:s,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const d=s??c?.title;if(t!=="automatic"&&!Object.prototype.hasOwnProperty.call(t,a))continue;const p=this,f=t!=="automatic"?(r=t[a])==null?void 0:r.outputSchema:void 0,h=async(y,w)=>{var g;(g=w?.abortSignal)==null||g.throwIfAborted();const m=await p.callTool({name:a,args:y,options:w});return m.isError?m:f!=null?p.extractStructuredContent(m,f,a):m},b=t==="automatic"?dynamicTool({description:i,title:d,metadata:{clientName:this.clientInfo.name},inputSchema:jsonSchema({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:h,toModelOutput:mcpToModelOutput}):{description:i,title:d,metadata:{clientName:this.clientInfo.name},inputSchema:t[a].inputSchema,...f!=null?{outputSchema:f}:{},execute:h,toModelOutput:mcpToModelOutput};o[a]={...b,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await safeValidateTypes$1({value:e.structuredContent,schema:asSchema(t)});if(!n.success)throw new MCPClientError({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 safeParseJSON$1({text:n.text,schema:t});if(!o.success)throw new MCPClientError({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new MCPClientError({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!==ElicitationRequestSchema)throw new MCPClientError({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=ElicitationRequestSchema.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=ElicitResultSchema.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 MCPClientError({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 MCPClientError({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new MCPClientError({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},openaiErrorDataSchema=object$2({error:object$2({message:string(),type:string().nullish(),param:any().nullish(),code:union([string(),number$1()]).nullish()})}),openaiFailedResponseHandler=createJsonErrorResponseHandler$1({errorSchema:openaiErrorDataSchema,errorToMessage:e=>e.error.message});function getOpenAILanguageModelCapabilities(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 convertOpenAIChatUsage(e){var t,r,n,o,a,s;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 i=(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=(s=(a=e.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?s:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function serializeToolCallArguments(e){return JSON.stringify(e===void 0?{}:e)}function convertToOpenAIChatMessages({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:a,content:s}of e)switch(a){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((i,l)=>{var c,u,d;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${convertToBase64$1(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new UnsupportedFunctionalityError$1({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:convertToBase64$1(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:convertToBase64$1(i.data),format:"mp3"}};default:throw new UnsupportedFunctionalityError$1({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new UnsupportedFunctionalityError$1({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(d=i.filename)!=null?d:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${convertToBase64$1(i.data)}`}}}else throw new UnsupportedFunctionalityError$1({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of s)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:serializeToolCallArguments(c.input)}});break}}n.push({role:"assistant",content:l.length>0?i||null:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of s){if(i.type==="tool-approval-response")continue;const l=i.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:i.toolCallId,content:c})}break}default:{const i=a;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function getResponseMetadata$1({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function mapOpenAIFinishReason(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 openaiChatResponseSchema=lazySchema(()=>zodSchema(object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({message:object$2({role:literal("assistant").nullish(),content:string().nullish(),tool_calls:array$1(object$2({id:string().nullish(),type:literal("function"),function:object$2({name:string(),arguments:string()})})).nullish(),annotations:array$1(object$2({type:literal("url_citation"),url_citation:object$2({start_index:number$1(),end_index:number$1(),url:string(),title:string()})})).nullish()}),index:number$1(),logprobs:object$2({content:array$1(object$2({token:string(),logprob:number$1(),top_logprobs:array$1(object$2({token:string(),logprob:number$1()}))})).nullish()}).nullish(),finish_reason:string().nullish()})),usage:object$2({prompt_tokens:number$1().nullish(),completion_tokens:number$1().nullish(),total_tokens:number$1().nullish(),prompt_tokens_details:object$2({cached_tokens:number$1().nullish()}).nullish(),completion_tokens_details:object$2({reasoning_tokens:number$1().nullish(),accepted_prediction_tokens:number$1().nullish(),rejected_prediction_tokens:number$1().nullish()}).nullish()}).nullish()}))),openaiChatChunkSchema=lazySchema(()=>zodSchema(union([object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({delta:object$2({role:_enum(["assistant"]).nullish(),content:string().nullish(),tool_calls:array$1(object$2({index:number$1(),id:string().nullish(),type:literal("function").nullish(),function:object$2({name:string().nullish(),arguments:string().nullish()})})).nullish(),annotations:array$1(object$2({type:literal("url_citation"),url_citation:object$2({start_index:number$1(),end_index:number$1(),url:string(),title:string()})})).nullish()}).nullish(),logprobs:object$2({content:array$1(object$2({token:string(),logprob:number$1(),top_logprobs:array$1(object$2({token:string(),logprob:number$1()}))})).nullish()}).nullish(),finish_reason:string().nullish(),index:number$1()})),usage:object$2({prompt_tokens:number$1().nullish(),completion_tokens:number$1().nullish(),total_tokens:number$1().nullish(),prompt_tokens_details:object$2({cached_tokens:number$1().nullish()}).nullish(),completion_tokens_details:object$2({reasoning_tokens:number$1().nullish(),accepted_prediction_tokens:number$1().nullish(),rejected_prediction_tokens:number$1().nullish()}).nullish()}).nullish()}),openaiErrorDataSchema]))),openaiLanguageModelChatOptions=lazySchema(()=>zodSchema(object$2({logitBias:record(number(),number$1()).optional(),logprobs:union([boolean(),number$1()]).optional(),parallelToolCalls:boolean().optional(),user:string().optional(),reasoningEffort:_enum(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:number$1().optional(),store:boolean().optional(),metadata:record(string().max(64),string().max(512)).optional(),prediction:record(string(),any()).optional(),serviceTier:_enum(["auto","flex","priority","default"]).optional(),strictJsonSchema:boolean().optional(),textVerbosity:_enum(["low","medium","high"]).optional(),promptCacheKey:string().optional(),promptCacheRetention:_enum(["in_memory","24h"]).optional(),safetyIdentifier:string().optional(),systemMessageMode:_enum(["system","developer","remove"]).optional(),forceReasoning:boolean().optional()})));function prepareChatTools({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 UnsupportedFunctionalityError$1({functionality:`tool choice type: ${a}`})}}}var OpenAIChatLanguageModel=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:s,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:d,providerOptions:p}){var f,h,b,y,w;const g=[],m=(f=await parseProviderOptions$1({provider:"openai",providerOptions:p,schema:openaiLanguageModelChatOptions}))!=null?f:{},S=getOpenAILanguageModelCapabilities(this.modelId),v=(h=m.forceReasoning)!=null?h:S.isReasoningModel;o!=null&&g.push({type:"unsupported",feature:"topK"});const{messages:_,warnings:$}=convertToOpenAIChatMessages({prompt:e,systemMessageMode:(b=m.systemMessageMode)!=null?b:v?"developer":S.systemMessageMode});g.push(...$);const T=(y=m.strictJsonSchema)!=null?y:!0,R={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs=="number"?!0:void 0,top_logprobs:typeof m.logprobs=="number"?m.logprobs:typeof m.logprobs=="boolean"&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:s,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:T,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,prompt_cache_retention:m.promptCacheRetention,safety_identifier:m.safetyIdentifier,messages:_};v?((m.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(R.temperature!=null&&(R.temperature=void 0,g.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),R.top_p!=null&&(R.top_p=void 0,g.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),R.logprobs!=null&&(R.logprobs=void 0,g.push({type:"other",message:"logprobs is not supported for reasoning models"}))),R.frequency_penalty!=null&&(R.frequency_penalty=void 0,g.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),R.presence_penalty!=null&&(R.presence_penalty=void 0,g.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),R.logit_bias!=null&&(R.logit_bias=void 0,g.push({type:"other",message:"logitBias is not supported for reasoning models"})),R.top_logprobs!=null&&(R.top_logprobs=void 0,g.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),R.max_tokens!=null&&(R.max_completion_tokens==null&&(R.max_completion_tokens=R.max_tokens),R.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&R.temperature!=null&&(R.temperature=void 0,g.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),m.serviceTier==="flex"&&!S.supportsFlexProcessing&&(g.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),R.service_tier=void 0),m.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(g.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"}),R.service_tier=void 0);const{tools:x,toolChoice:E,toolWarnings:A}=prepareChatTools({tools:u,toolChoice:d});return{args:{...R,tools:x,tool_choice:E},warnings:[...g,...A]}}async doGenerate(e){var t,r,n,o,a,s,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:d,rawValue:p}=await postJsonToApi$1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),body:l,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiChatResponseSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=d.choices[0],h=[],b=f.message.content;b!=null&&b.length>0&&h.push({type:"text",text:b});for(const g of(t=f.message.tool_calls)!=null?t:[])h.push({type:"tool-call",toolCallId:(r=g.id)!=null?r:generateId$1(),toolName:g.function.name,input:g.function.arguments});for(const g of(n=f.message.annotations)!=null?n:[])h.push({type:"source",sourceType:"url",id:generateId$1(),url:g.url_citation.url,title:g.url_citation.title});const y=(o=d.usage)==null?void 0:o.completion_tokens_details;(a=d.usage)==null||a.prompt_tokens_details;const w={openai:{}};return y?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),((s=f.logprobs)==null?void 0:s.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:h,finishReason:{unified:mapOpenAIFinishReason(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:convertOpenAIChatUsage(d.usage),request:{body:l},response:{...getResponseMetadata$1(d),headers:u,body:p},warnings:c,providerMetadata:w}}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 postJsonToApi$1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),body:n,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler$1(openaiChatChunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var h,b,y,w,g,m,S,v,_,$,T,R,x,E,A,D,U;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const K=p.value;if("error"in K){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:K.error});return}if(!c){const X=getResponseMetadata$1(K);Object.values(X).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...getResponseMetadata$1(K)}))}K.usage!=null&&(l=K.usage,((h=K.usage.completion_tokens_details)==null?void 0:h.accepted_prediction_tokens)!=null&&(d.openai.acceptedPredictionTokens=(b=K.usage.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((y=K.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(d.openai.rejectedPredictionTokens=(w=K.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const G=K.choices[0];if(G?.finish_reason!=null&&(i={unified:mapOpenAIFinishReason(G.finish_reason),raw:G.finish_reason}),((g=G?.logprobs)==null?void 0:g.content)!=null&&(d.openai.logprobs=G.logprobs.content),G?.delta==null)return;const te=G.delta;if(te.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:te.content})),te.tool_calls!=null)for(const X of te.tool_calls){const ue=X.index;if(s[ue]==null){if(X.type!=null&&X.type!=="function")throw new InvalidResponseDataError$1({data:X,message:"Expected 'function' type."});if(X.id==null)throw new InvalidResponseDataError$1({data:X,message:"Expected 'id' to be a string."});if(((m=X.function)==null?void 0:m.name)==null)throw new InvalidResponseDataError$1({data:X,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),s[ue]={id:X.id,type:"function",function:{name:X.function.name,arguments:(S=X.function.arguments)!=null?S:""},hasFinished:!1};const C=s[ue];((v=C.function)==null?void 0:v.name)!=null&&((_=C.function)==null?void 0:_.arguments)!=null&&(C.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:C.id,delta:C.function.arguments}),isParsableJson$1(C.function.arguments)&&(f.enqueue({type:"tool-input-end",id:C.id}),f.enqueue({type:"tool-call",toolCallId:($=C.id)!=null?$:generateId$1(),toolName:C.function.name,input:C.function.arguments}),C.hasFinished=!0));continue}const V=s[ue];V.hasFinished||(((T=X.function)==null?void 0:T.arguments)!=null&&(V.function.arguments+=(x=(R=X.function)==null?void 0:R.arguments)!=null?x:""),f.enqueue({type:"tool-input-delta",id:V.id,delta:(E=X.function.arguments)!=null?E:""}),((A=V.function)==null?void 0:A.name)!=null&&((D=V.function)==null?void 0:D.arguments)!=null&&isParsableJson$1(V.function.arguments)&&(f.enqueue({type:"tool-input-end",id:V.id}),f.enqueue({type:"tool-call",toolCallId:(U=V.id)!=null?U:generateId$1(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}if(te.annotations!=null)for(const X of te.annotations)f.enqueue({type:"source",sourceType:"url",id:generateId$1(),url:X.url_citation.url,title:X.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:convertOpenAIChatUsage(l),...d!=null?{providerMetadata:d}:{}})}})),request:{body:n},response:{headers:o}}}};function convertOpenAICompletionUsage(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,s=(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:s,reasoning:void 0},raw:e}}function convertToOpenAICompletionPrompt({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
593
|
-
|
|
594
|
-
`,e=e.slice(1));for(const{role:o,content:a}of e)switch(o){case"system":throw new InvalidPromptError({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const s=a.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
|
|
595
|
-
${s}
|
|
596
|
-
|
|
597
|
-
`;break}case"assistant":{const s=a.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new UnsupportedFunctionalityError$1({functionality:"tool-call messages"})}}).join("");n+=`${r}:
|
|
598
|
-
${s}
|
|
599
|
-
|
|
600
|
-
`;break}case"tool":throw new UnsupportedFunctionalityError$1({functionality:"tool messages"});default:{const s=o;throw new Error(`Unsupported role: ${s}`)}}return n+=`${r}:
|
|
601
|
-
`,{prompt:n,stopSequences:[`
|
|
602
|
-
${t}:`]}}function getResponseMetadata2({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 mapOpenAIFinishReason2(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 openaiCompletionResponseSchema=lazySchema(()=>zodSchema(object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({text:string(),finish_reason:string(),logprobs:object$2({tokens:array$1(string()),token_logprobs:array$1(number$1()),top_logprobs:array$1(record(string(),number$1())).nullish()}).nullish()})),usage:object$2({prompt_tokens:number$1(),completion_tokens:number$1(),total_tokens:number$1()}).nullish()}))),openaiCompletionChunkSchema=lazySchema(()=>zodSchema(union([object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({text:string(),finish_reason:string().nullish(),index:number$1(),logprobs:object$2({tokens:array$1(string()),token_logprobs:array$1(number$1()),top_logprobs:array$1(record(string(),number$1())).nullish()}).nullish()})),usage:object$2({prompt_tokens:number$1(),completion_tokens:number$1(),total_tokens:number$1()}).nullish()}),openaiErrorDataSchema]))),openaiLanguageModelCompletionOptions=lazySchema(()=>zodSchema(object$2({echo:boolean().optional(),logitBias:record(string(),number$1()).optional(),suffix:string().optional(),user:string().optional(),logprobs:union([boolean(),number$1()]).optional()}))),OpenAICompletionLanguageModel=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:s,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:d,providerOptions:p}){const f=[],h={...await parseProviderOptions$1({provider:"openai",providerOptions:p,schema:openaiLanguageModelCompletionOptions}),...await parseProviderOptions$1({provider:this.providerOptionsName,providerOptions:p,schema:openaiLanguageModelCompletionOptions})};o!=null&&f.push({type:"unsupported",feature:"topK"}),c?.length&&f.push({type:"unsupported",feature:"tools"}),u!=null&&f.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:y}=convertToOpenAICompletionPrompt({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:h?.logprobs===!0?0:h?.logprobs===!1?void 0:h?.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:s,seed:d,prompt:b,stop:w.length>0?w:void 0},warnings:f}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:a,rawValue:s}=await postJsonToApi$1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),body:r,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiCompletionResponseSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=a.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:convertOpenAICompletionUsage(a.usage),finishReason:{unified:mapOpenAIFinishReason2(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...getResponseMetadata2(a),headers:o,body:s},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 postJsonToApi$1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),body:n,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler$1(openaiCompletionChunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch});let s={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,d){if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){s={unified:"error",raw:void 0},d.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){s={unified:"error",raw:void 0},d.enqueue({type:"error",error:p.error});return}c&&(c=!1,d.enqueue({type:"response-metadata",...getResponseMetadata2(p)}),d.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(s={unified:mapOpenAIFinishReason2(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(i.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&d.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:s,providerMetadata:i,usage:convertOpenAICompletionUsage(l)})}})),request:{body:n},response:{headers:o}}}},openaiEmbeddingModelOptions=lazySchema(()=>zodSchema(object$2({dimensions:number$1().optional(),user:string().optional()}))),openaiTextEmbeddingResponseSchema=lazySchema(()=>zodSchema(object$2({data:array$1(object$2({embedding:array$1(number$1())})),usage:object$2({prompt_tokens:number$1()}).nullish()}))),OpenAIEmbeddingModel=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 TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const a=(o=await parseProviderOptions$1({provider:"openai",providerOptions:n,schema:openaiEmbeddingModelOptions}))!=null?o:{},{responseHeaders:s,value:i,rawValue:l}=await postJsonToApi$1({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiTextEmbeddingResponseSchema),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:s,body:l}}}},openaiImageResponseSchema=lazySchema(()=>zodSchema(object$2({created:number$1().nullish(),data:array$1(object$2({b64_json:string(),revised_prompt:string().nullish()})),background:string().nullish(),output_format:string().nullish(),size:string().nullish(),quality:string().nullish(),usage:object$2({input_tokens:number$1().nullish(),output_tokens:number$1().nullish(),total_tokens:number$1().nullish(),input_tokens_details:object$2({image_tokens:number$1().nullish(),text_tokens:number$1().nullish()}).nullish()}).nullish()}))),modelMaxImagesPerCall={"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},defaultResponseFormatPrefixes=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function hasDefaultResponseFormat(e){return defaultResponseFormatPrefixes.some(t=>e.startsWith(t))}var baseImageModelOptionsObject=object$2({quality:_enum(["standard","hd","low","medium","high","auto"]).optional(),background:_enum(["transparent","opaque","auto"]).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),outputCompression:number$1().int().min(0).max(100).optional(),user:string().optional()}),openaiImageModelGenerationOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({style:_enum(["vivid","natural"]).optional(),moderation:_enum(["auto","low"]).optional()}))),openaiImageModelEditOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({inputFidelity:_enum(["high","low"]).optional()}))),OpenAIImageModel=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=modelMaxImagesPerCall[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:s,providerOptions:i,headers:l,abortSignal:c}){var u,d,p,f,h,b,y,w,g,m,S;const v=[];a!=null&&v.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&v.push({type:"unsupported",feature:"seed"});const _=(p=(d=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:d.call(u))!=null?p:new Date;if(t!=null){const x=(f=await parseProviderOptions$1({provider:"openai",providerOptions:i,schema:openaiImageModelEditOptions}))!=null?f:{},{value:E,responseHeaders:A}=await postFormDataToApi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),l),formData:convertToFormData({model:this.modelId,prompt:e,image:await Promise.all(t.map(D=>D.type==="file"?new Blob([D.data instanceof Uint8Array?new Blob([D.data],{type:D.mediaType}):new Blob([convertBase64ToUint8Array(D.data)],{type:D.mediaType})],{type:D.mediaType}):downloadBlob(D.url))),mask:r!=null?await fileToBlob(r):void 0,n,size:o,quality:x.quality,background:x.background,output_format:x.outputFormat,output_compression:x.outputCompression,input_fidelity:x.inputFidelity,user:x.user}),failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiImageResponseSchema),abortSignal:c,fetch:this.config.fetch});return{images:E.data.map(D=>D.b64_json),warnings:v,usage:E.usage!=null?{inputTokens:(h=E.usage.input_tokens)!=null?h:void 0,outputTokens:(b=E.usage.output_tokens)!=null?b:void 0,totalTokens:(y=E.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:A},providerMetadata:{openai:{images:E.data.map((D,U)=>{var K,G,te,X,ue,V;return{...D.revised_prompt?{revisedPrompt:D.revised_prompt}:{},created:(K=E.created)!=null?K:void 0,size:(G=E.size)!=null?G:void 0,quality:(te=E.quality)!=null?te:void 0,background:(X=E.background)!=null?X:void 0,outputFormat:(ue=E.output_format)!=null?ue:void 0,...distributeTokenDetails((V=E.usage)==null?void 0:V.input_tokens_details,U,E.data.length)}})}}}}const $=(w=await parseProviderOptions$1({provider:"openai",providerOptions:i,schema:openaiImageModelGenerationOptions}))!=null?w:{},{value:T,responseHeaders:R}=await postJsonToApi$1({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,quality:$.quality,style:$.style,background:$.background,moderation:$.moderation,output_format:$.outputFormat,output_compression:$.outputCompression,user:$.user,...hasDefaultResponseFormat(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiImageResponseSchema),abortSignal:c,fetch:this.config.fetch});return{images:T.data.map(x=>x.b64_json),warnings:v,usage:T.usage!=null?{inputTokens:(g=T.usage.input_tokens)!=null?g:void 0,outputTokens:(m=T.usage.output_tokens)!=null?m:void 0,totalTokens:(S=T.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:T.data.map((x,E)=>{var A,D,U,K,G,te;return{...x.revised_prompt?{revisedPrompt:x.revised_prompt}:{},created:(A=T.created)!=null?A:void 0,size:(D=T.size)!=null?D:void 0,quality:(U=T.quality)!=null?U:void 0,background:(K=T.background)!=null?K:void 0,outputFormat:(G=T.output_format)!=null?G:void 0,...distributeTokenDetails((te=T.usage)==null?void 0:te.input_tokens_details,E,T.data.length)}})}}}}};function distributeTokenDetails(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 fileToBlob(e){if(!e)return;if(e.type==="url")return downloadBlob(e.url);const t=e.data instanceof Uint8Array?e.data:convertBase64ToUint8Array(e.data);return new Blob([t],{type:e.mediaType})}var applyPatchInputSchema=lazySchema(()=>zodSchema(object$2({callId:string(),operation:discriminatedUnion("type",[object$2({type:literal("create_file"),path:string(),diff:string()}),object$2({type:literal("delete_file"),path:string()}),object$2({type:literal("update_file"),path:string(),diff:string()})])}))),applyPatchOutputSchema=lazySchema(()=>zodSchema(object$2({status:_enum(["completed","failed"]),output:string().optional()}))),applyPatchToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.apply_patch",inputSchema:applyPatchInputSchema,outputSchema:applyPatchOutputSchema}),applyPatch=applyPatchToolFactory,codeInterpreterInputSchema=lazySchema(()=>zodSchema(object$2({code:string().nullish(),containerId:string()}))),codeInterpreterOutputSchema=lazySchema(()=>zodSchema(object$2({outputs:array$1(discriminatedUnion("type",[object$2({type:literal("logs"),logs:string()}),object$2({type:literal("image"),url:string()})])).nullish()}))),codeInterpreterArgsSchema=lazySchema(()=>zodSchema(object$2({container:union([string(),object$2({fileIds:array$1(string()).optional()})]).optional()}))),codeInterpreterToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.code_interpreter",inputSchema:codeInterpreterInputSchema,outputSchema:codeInterpreterOutputSchema}),codeInterpreter=(e={})=>codeInterpreterToolFactory(e),customArgsSchema=lazySchema(()=>zodSchema(object$2({name:string(),description:string().optional(),format:union([object$2({type:literal("grammar"),syntax:_enum(["regex","lark"]),definition:string()}),object$2({type:literal("text")})]).optional()}))),customInputSchema=lazySchema(()=>zodSchema(string())),customToolFactory=createProviderToolFactory({id:"openai.custom",inputSchema:customInputSchema}),customTool=e=>customToolFactory(e),comparisonFilterSchema=object$2({key:string(),type:_enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:union([string(),number$1(),boolean(),array$1(string())])}),compoundFilterSchema=object$2({type:_enum(["and","or"]),filters:array$1(union([comparisonFilterSchema,lazy(()=>compoundFilterSchema)]))}),fileSearchArgsSchema=lazySchema(()=>zodSchema(object$2({vectorStoreIds:array$1(string()),maxNumResults:number$1().optional(),ranking:object$2({ranker:string().optional(),scoreThreshold:number$1().optional()}).optional(),filters:union([comparisonFilterSchema,compoundFilterSchema]).optional()}))),fileSearchOutputSchema=lazySchema(()=>zodSchema(object$2({queries:array$1(string()),results:array$1(object$2({attributes:record(string(),unknown()),fileId:string(),filename:string(),score:number$1(),text:string()})).nullable()}))),fileSearch=createProviderToolFactoryWithOutputSchema({id:"openai.file_search",inputSchema:object$2({}),outputSchema:fileSearchOutputSchema}),imageGenerationArgsSchema=lazySchema(()=>zodSchema(object$2({background:_enum(["auto","opaque","transparent"]).optional(),inputFidelity:_enum(["low","high"]).optional(),inputImageMask:object$2({fileId:string().optional(),imageUrl:string().optional()}).optional(),model:string().optional(),moderation:_enum(["auto"]).optional(),outputCompression:number$1().int().min(0).max(100).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),partialImages:number$1().int().min(0).max(3).optional(),quality:_enum(["auto","low","medium","high"]).optional(),size:_enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),imageGenerationInputSchema=lazySchema(()=>zodSchema(object$2({}))),imageGenerationOutputSchema=lazySchema(()=>zodSchema(object$2({result:string()}))),imageGenerationToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.image_generation",inputSchema:imageGenerationInputSchema,outputSchema:imageGenerationOutputSchema}),imageGeneration=(e={})=>imageGenerationToolFactory(e),localShellInputSchema=lazySchema(()=>zodSchema(object$2({action:object$2({type:literal("exec"),command:array$1(string()),timeoutMs:number$1().optional(),user:string().optional(),workingDirectory:string().optional(),env:record(string(),string()).optional()})}))),localShellOutputSchema=lazySchema(()=>zodSchema(object$2({output:string()}))),localShell=createProviderToolFactoryWithOutputSchema({id:"openai.local_shell",inputSchema:localShellInputSchema,outputSchema:localShellOutputSchema}),shellInputSchema=lazySchema(()=>zodSchema(object$2({action:object$2({commands:array$1(string()),timeoutMs:number$1().optional(),maxOutputLength:number$1().optional()})}))),shellOutputSchema=lazySchema(()=>zodSchema(object$2({output:array$1(object$2({stdout:string(),stderr:string(),outcome:discriminatedUnion("type",[object$2({type:literal("timeout")}),object$2({type:literal("exit"),exitCode:number$1()})])}))}))),shellSkillsSchema=array$1(discriminatedUnion("type",[object$2({type:literal("skillReference"),skillId:string(),version:string().optional()}),object$2({type:literal("inline"),name:string(),description:string(),source:object$2({type:literal("base64"),mediaType:literal("application/zip"),data:string()})})])).optional(),shellArgsSchema=lazySchema(()=>zodSchema(object$2({environment:union([object$2({type:literal("containerAuto"),fileIds:array$1(string()).optional(),memoryLimit:_enum(["1g","4g","16g","64g"]).optional(),networkPolicy:discriminatedUnion("type",[object$2({type:literal("disabled")}),object$2({type:literal("allowlist"),allowedDomains:array$1(string()),domainSecrets:array$1(object$2({domain:string(),name:string(),value:string()})).optional()})]).optional(),skills:shellSkillsSchema}),object$2({type:literal("containerReference"),containerId:string()}),object$2({type:literal("local").optional(),skills:array$1(object$2({name:string(),description:string(),path:string()})).optional()})]).optional()}))),shell=createProviderToolFactoryWithOutputSchema({id:"openai.shell",inputSchema:shellInputSchema,outputSchema:shellOutputSchema}),toolSearchArgsSchema=lazySchema(()=>zodSchema(object$2({execution:_enum(["server","client"]).optional(),description:string().optional(),parameters:record(string(),unknown()).optional()}))),toolSearchInputSchema=lazySchema(()=>zodSchema(object$2({arguments:unknown().optional(),call_id:string().nullish()}))),toolSearchOutputSchema=lazySchema(()=>zodSchema(object$2({tools:array$1(record(string(),unknown()))}))),toolSearchToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.tool_search",inputSchema:toolSearchInputSchema,outputSchema:toolSearchOutputSchema}),toolSearch=(e={})=>toolSearchToolFactory(e),webSearchArgsSchema=lazySchema(()=>zodSchema(object$2({externalWebAccess:boolean().optional(),filters:object$2({allowedDomains:array$1(string()).optional()}).optional(),searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object$2({type:literal("approximate"),country:string().optional(),city:string().optional(),region:string().optional(),timezone:string().optional()}).optional()}))),webSearchInputSchema=lazySchema(()=>zodSchema(object$2({}))),webSearchOutputSchema=lazySchema(()=>zodSchema(object$2({action:discriminatedUnion("type",[object$2({type:literal("search"),query:string().optional(),queries:array$1(string()).optional()}),object$2({type:literal("openPage"),url:string().nullish()}),object$2({type:literal("findInPage"),url:string().nullish(),pattern:string().nullish()})]).optional(),sources:array$1(discriminatedUnion("type",[object$2({type:literal("url"),url:string()}),object$2({type:literal("api"),name:string()})])).optional()}))),webSearchToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.web_search",inputSchema:webSearchInputSchema,outputSchema:webSearchOutputSchema}),webSearch=(e={})=>webSearchToolFactory(e),webSearchPreviewArgsSchema=lazySchema(()=>zodSchema(object$2({searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object$2({type:literal("approximate"),country:string().optional(),city:string().optional(),region:string().optional(),timezone:string().optional()}).optional()}))),webSearchPreviewInputSchema=lazySchema(()=>zodSchema(object$2({}))),webSearchPreviewOutputSchema=lazySchema(()=>zodSchema(object$2({action:discriminatedUnion("type",[object$2({type:literal("search"),query:string().optional()}),object$2({type:literal("openPage"),url:string().nullish()}),object$2({type:literal("findInPage"),url:string().nullish(),pattern:string().nullish()})]).optional()}))),webSearchPreview=createProviderToolFactoryWithOutputSchema({id:"openai.web_search_preview",inputSchema:webSearchPreviewInputSchema,outputSchema:webSearchPreviewOutputSchema}),jsonValueSchema=lazy(()=>union([string(),number$1(),boolean(),_null(),array$1(jsonValueSchema),record(string(),jsonValueSchema)])),mcpArgsSchema=lazySchema(()=>zodSchema(object$2({serverLabel:string(),allowedTools:union([array$1(string()),object$2({readOnly:boolean().optional(),toolNames:array$1(string()).optional()})]).optional(),authorization:string().optional(),connectorId:string().optional(),headers:record(string(),string()).optional(),requireApproval:union([_enum(["always","never"]),object$2({never:object$2({toolNames:array$1(string()).optional()}).optional()})]).optional(),serverDescription:string().optional(),serverUrl:string().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),mcpInputSchema=lazySchema(()=>zodSchema(object$2({}))),mcpOutputSchema=lazySchema(()=>zodSchema(object$2({type:literal("call"),serverLabel:string(),name:string(),arguments:string(),output:string().nullish(),error:union([string(),jsonValueSchema]).optional()}))),mcpToolFactory=createProviderToolFactoryWithOutputSchema({id:"openai.mcp",inputSchema:mcpInputSchema,outputSchema:mcpOutputSchema}),mcp=e=>mcpToolFactory(e),openaiTools={applyPatch,customTool,codeInterpreter,fileSearch,imageGeneration,localShell,shell,webSearchPreview,webSearch,mcp,toolSearch};function convertOpenAIResponsesUsage(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,s=e.output_tokens,i=(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-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:s,text:s-l,reasoning:l},raw:e}}function serializeToolCallArguments2(e){return JSON.stringify(e===void 0?{}:e)}function isFileId(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function convertToOpenAIResponsesInput({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,passThroughUnsupportedFiles:a=!1,store:s,hasConversation:i=!1,hasPreviousResponseId:l=!1,hasLocalShellTool:c=!1,hasShellTool:u=!1,hasApplyPatchTool:d=!1,customProviderToolNames:p}){var f,h,b,y,w,g,m,S,v,_,$,T,R,x,E,A,D,U,K,G,te,X,ue;let V=[];const C=[],N=new Set;for(const{role:L,content:I}of e)switch(L){case"system":{switch(r){case"system":{V.push({role:"system",content:I});break}case"developer":{V.push({role:"developer",content:I});break}case"remove":{C.push({type:"other",message:"system messages are removed for this model"});break}default:{const k=r;throw new Error(`Unsupported system message mode: ${k}`)}}break}case"user":{V.push({role:"user",content:I.map((k,O)=>{var q,B,F;switch(k.type){case"text":return{type:"input_text",text:k.text};case"file":{const j=k.mediaType==="image/*"?"image/jpeg":k.mediaType;if(j.startsWith("image/"))return{type:"input_image",...k.data instanceof URL?{image_url:k.data.toString()}:typeof k.data=="string"&&isFileId(k.data,o)?{file_id:k.data}:{image_url:`data:${j};base64,${convertToBase64$1(k.data)}`},detail:(B=(q=k.providerOptions)==null?void 0:q[n])==null?void 0:B.imageDetail};if(k.data instanceof URL)return{type:"input_file",file_url:k.data.toString()};if(j!=="application/pdf"&&!a)throw new UnsupportedFunctionalityError$1({functionality:`file part media type ${j}`});return{type:"input_file",...typeof k.data=="string"&&isFileId(k.data,o)?{file_id:k.data}:{filename:(F=k.filename)!=null?F:j==="application/pdf"?`part-${O}.pdf`:`part-${O}`,file_data:`data:${j};base64,${convertToBase64$1(k.data)}`}}}}})});break}case"assistant":{const k={};for(const O of I)switch(O.type){case"text":{const q=(f=O.providerOptions)==null?void 0:f[n],B=q?.itemId,F=q?.phase;if(i&&B!=null)break;if(s&&B!=null){V.push({type:"item_reference",id:B});break}V.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:B,...F!=null&&{phase:F}});break}case"tool-call":{const q=(g=(b=(h=O.providerOptions)==null?void 0:h[n])==null?void 0:b.itemId)!=null?g:(w=(y=O.providerMetadata)==null?void 0:y[n])==null?void 0:w.itemId,B=($=(S=(m=O.providerOptions)==null?void 0:m[n])==null?void 0:S.namespace)!=null?$:(_=(v=O.providerMetadata)==null?void 0:v[n])==null?void 0:_.namespace;if(i&&q!=null)break;const F=t.toProviderToolName(O.toolName);if(F==="tool_search"){if(s&&q!=null){V.push({type:"item_reference",id:q});break}const M=typeof O.input=="string"?await parseJSON$1({text:O.input,schema:toolSearchInputSchema}):await validateTypes$1({value:O.input,schema:toolSearchInputSchema}),Z=M.call_id!=null?"client":"server";V.push({type:"tool_search_call",id:q??O.toolCallId,execution:Z,call_id:(T=M.call_id)!=null?T:null,status:"completed",arguments:M.arguments});break}if(O.providerExecuted){s&&q!=null&&V.push({type:"item_reference",id:q});break}if(l&&s&&q!=null)break;const j=c&&F==="local_shell"||u&&F==="shell"||d&&F==="apply_patch"||((R=p?.has(F))!=null?R:!1);if(s&&q!=null&&j){V.push({type:"item_reference",id:q});break}if(c&&F==="local_shell"){const M=await validateTypes$1({value:O.input,schema:localShellInputSchema});V.push({type:"local_shell_call",call_id:O.toolCallId,id:q,action:{type:"exec",command:M.action.command,timeout_ms:M.action.timeoutMs,user:M.action.user,working_directory:M.action.workingDirectory,env:M.action.env}});break}if(u&&F==="shell"){const M=await validateTypes$1({value:O.input,schema:shellInputSchema});V.push({type:"shell_call",call_id:O.toolCallId,id:q,status:"completed",action:{commands:M.action.commands,timeout_ms:M.action.timeoutMs,max_output_length:M.action.maxOutputLength}});break}if(d&&F==="apply_patch"){const M=await validateTypes$1({value:O.input,schema:applyPatchInputSchema});V.push({type:"apply_patch_call",call_id:M.callId,id:q,status:"completed",operation:M.operation});break}if(p?.has(F)){V.push({type:"custom_tool_call",call_id:O.toolCallId,name:F,input:typeof O.input=="string"?O.input:JSON.stringify(O.input),id:q});break}V.push({type:"function_call",call_id:O.toolCallId,name:F,arguments:serializeToolCallArguments2(O.input),...B!=null&&{namespace:B}});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied"||i)break;const q=t.toProviderToolName(O.toolName);if(q==="tool_search"){const B=(A=(E=(x=O.providerOptions)==null?void 0:x[n])==null?void 0:E.itemId)!=null?A:O.toolCallId;if(s)V.push({type:"item_reference",id:B});else if(O.output.type==="json"){const F=await validateTypes$1({value:O.output.value,schema:toolSearchOutputSchema});V.push({type:"tool_search_output",id:B,execution:"server",call_id:null,status:"completed",tools:F.tools})}break}if(u&&q==="shell"){if(O.output.type==="json"){const B=await validateTypes$1({value:O.output.value,schema:shellOutputSchema});V.push({type:"shell_call_output",call_id:O.toolCallId,output:B.output.map(F=>({stdout:F.stdout,stderr:F.stderr,outcome:F.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:F.outcome.exitCode}}))})}break}if(s){const B=(K=(U=(D=O.providerOptions)==null?void 0:D[n])==null?void 0:U.itemId)!=null?K:O.toolCallId;V.push({type:"item_reference",id:B})}else C.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const q=await parseProviderOptions$1({provider:n,providerOptions:O.providerOptions,schema:openaiResponsesReasoningProviderOptionsSchema}),B=q?.itemId;if((i||l)&&B!=null)break;if(B!=null){const F=k[B];if(s)F===void 0&&(V.push({type:"item_reference",id:B}),k[B]={type:"reasoning",id:B,summary:[]});else{const j=[];O.text.length>0?j.push({type:"summary_text",text:O.text}):F!==void 0&&C.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),F===void 0?(k[B]={type:"reasoning",id:B,encrypted_content:q?.reasoningEncryptedContent,summary:j},V.push(k[B])):(F.summary.push(...j),q?.reasoningEncryptedContent!=null&&(F.encrypted_content=q.reasoningEncryptedContent))}}else{const F=q?.reasoningEncryptedContent;if(F!=null){const j=[];O.text.length>0&&j.push({type:"summary_text",text:O.text}),V.push({type:"reasoning",encrypted_content:F,summary:j})}else C.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`})}break}}break}case"tool":{for(const k of I){if(k.type==="tool-approval-response"){const F=k;if(N.has(F.approvalId))continue;N.add(F.approvalId),s&&V.push({type:"item_reference",id:F.approvalId}),V.push({type:"mcp_approval_response",approval_request_id:F.approvalId,approve:F.approved});continue}const O=k.output;if(O.type==="execution-denied"&&((te=(G=O.providerOptions)==null?void 0:G.openai)==null?void 0:te.approvalId))continue;const q=t.toProviderToolName(k.toolName);if(q==="tool_search"&&O.type==="json"){const F=await validateTypes$1({value:O.value,schema:toolSearchOutputSchema});V.push({type:"tool_search_output",execution:"client",call_id:k.toolCallId,status:"completed",tools:F.tools});continue}if(c&&q==="local_shell"&&O.type==="json"){const F=await validateTypes$1({value:O.value,schema:localShellOutputSchema});V.push({type:"local_shell_call_output",call_id:k.toolCallId,output:F.output});continue}if(u&&q==="shell"&&O.type==="json"){const F=await validateTypes$1({value:O.value,schema:shellOutputSchema});V.push({type:"shell_call_output",call_id:k.toolCallId,output:F.output.map(j=>({stdout:j.stdout,stderr:j.stderr,outcome:j.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:j.outcome.exitCode}}))});continue}if(d&&k.toolName==="apply_patch"&&O.type==="json"){const F=await validateTypes$1({value:O.value,schema:applyPatchOutputSchema});V.push({type:"apply_patch_call_output",call_id:k.toolCallId,status:F.status,output:F.output});continue}if(p?.has(q)){let F;switch(O.type){case"text":case"error-text":F=O.value;break;case"execution-denied":F=(X=O.reason)!=null?X:"Tool execution denied.";break;case"json":case"error-json":F=JSON.stringify(O.value);break;case"content":F=O.value.map(j=>{var M,Z,H,J,oe;switch(j.type){case"text":return{type:"input_text",text:j.text};case"image-data":return{type:"input_image",image_url:`data:${j.mediaType};base64,${j.data}`,detail:(Z=(M=j.providerOptions)==null?void 0:M[n])==null?void 0:Z.imageDetail};case"image-url":return{type:"input_image",image_url:j.url,detail:(J=(H=j.providerOptions)==null?void 0:H[n])==null?void 0:J.imageDetail};case"file-data":return{type:"input_file",filename:(oe=j.filename)!=null?oe:"data",file_data:`data:${j.mediaType};base64,${j.data}`};case"file-url":return{type:"input_file",file_url:j.url};default:C.push({type:"other",message:`unsupported custom tool content part type: ${j.type}`});return}}).filter(isNonNullable);break;default:F=""}V.push({type:"custom_tool_call_output",call_id:k.toolCallId,output:F});continue}let B;switch(O.type){case"text":case"error-text":B=O.value;break;case"execution-denied":B=(ue=O.reason)!=null?ue:"Tool execution denied.";break;case"json":case"error-json":B=JSON.stringify(O.value);break;case"content":B=O.value.map(F=>{var j,M,Z,H,J;switch(F.type){case"text":return{type:"input_text",text:F.text};case"image-data":return{type:"input_image",image_url:`data:${F.mediaType};base64,${F.data}`,detail:(M=(j=F.providerOptions)==null?void 0:j[n])==null?void 0:M.imageDetail};case"image-url":return{type:"input_image",image_url:F.url,detail:(H=(Z=F.providerOptions)==null?void 0:Z[n])==null?void 0:H.imageDetail};case"file-data":return{type:"input_file",filename:(J=F.filename)!=null?J:"data",file_data:`data:${F.mediaType};base64,${F.data}`};case"file-url":return{type:"input_file",file_url:F.url};default:{C.push({type:"other",message:`unsupported tool content part type: ${F.type}`});return}}}).filter(isNonNullable);break}V.push({type:"function_call_output",call_id:k.toolCallId,output:B})}break}default:{const k=L;throw new Error(`Unsupported role: ${k}`)}}return!s&&V.some(L=>"type"in L&&L.type==="reasoning"&&L.encrypted_content==null)&&(C.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),V=V.filter(L=>!("type"in L)||L.type!=="reasoning"||L.encrypted_content!=null)),{input:V,warnings:C}}var openaiResponsesReasoningProviderOptionsSchema=object$2({itemId:string().nullish(),reasoningEncryptedContent:string().nullish()});function mapOpenAIResponseFinishReason({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 jsonValueSchema2=lazy(()=>union([string(),number$1(),boolean(),_null(),array$1(jsonValueSchema2),record(string(),jsonValueSchema2.optional())])),openaiResponsesChunkSchema=lazySchema(()=>zodSchema(union([object$2({type:literal("response.output_text.delta"),item_id:string(),delta:string(),logprobs:array$1(object$2({token:string(),logprob:number$1(),top_logprobs:array$1(object$2({token:string(),logprob:number$1()}))})).nullish()}),object$2({type:_enum(["response.completed","response.incomplete"]),response:object$2({incomplete_details:object$2({reason:string()}).nullish(),usage:object$2({input_tokens:number$1(),input_tokens_details:object$2({cached_tokens:number$1().nullish(),orchestration_input_tokens:number$1().nullish(),orchestration_input_cached_tokens:number$1().nullish()}).nullish(),output_tokens:number$1(),output_tokens_details:object$2({reasoning_tokens:number$1().nullish(),orchestration_output_tokens:number$1().nullish()}).nullish()}),service_tier:string().nullish()})}),object$2({type:literal("response.failed"),response:object$2({error:object$2({code:string().nullish(),message:string()}).nullish(),incomplete_details:object$2({reason:string()}).nullish(),usage:object$2({input_tokens:number$1(),input_tokens_details:object$2({cached_tokens:number$1().nullish(),orchestration_input_tokens:number$1().nullish(),orchestration_input_cached_tokens:number$1().nullish()}).nullish(),output_tokens:number$1(),output_tokens_details:object$2({reasoning_tokens:number$1().nullish(),orchestration_output_tokens:number$1().nullish()}).nullish()}).nullish(),service_tier:string().nullish()})}),object$2({type:literal("response.created"),response:object$2({id:string(),created_at:number$1(),model:string(),service_tier:string().nullish()})}),object$2({type:literal("response.output_item.added"),output_index:number$1(),item:discriminatedUnion("type",[object$2({type:literal("message"),id:string(),phase:_enum(["commentary","final_answer"]).nullish()}),object$2({type:literal("reasoning"),id:string(),encrypted_content:string().nullish()}),object$2({type:literal("function_call"),id:string(),call_id:string(),name:string(),arguments:string(),namespace:string().nullish()}),object$2({type:literal("web_search_call"),id:string(),status:string()}),object$2({type:literal("computer_call"),id:string(),status:string()}),object$2({type:literal("file_search_call"),id:string()}),object$2({type:literal("image_generation_call"),id:string()}),object$2({type:literal("code_interpreter_call"),id:string(),container_id:string(),code:string().nullable(),outputs:array$1(discriminatedUnion("type",[object$2({type:literal("logs"),logs:string()}),object$2({type:literal("image"),url:string()})])).nullable(),status:string()}),object$2({type:literal("mcp_call"),id:string(),status:string(),approval_request_id:string().nullish()}),object$2({type:literal("mcp_list_tools"),id:string()}),object$2({type:literal("mcp_approval_request"),id:string()}),object$2({type:literal("apply_patch_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object$2({type:literal("create_file"),path:string(),diff:string()}),object$2({type:literal("delete_file"),path:string()}),object$2({type:literal("update_file"),path:string(),diff:string()})])}),object$2({type:literal("custom_tool_call"),id:string(),call_id:string(),name:string(),input:string()}),object$2({type:literal("shell_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),action:object$2({commands:array$1(string())})}),object$2({type:literal("shell_call_output"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),output:array$1(object$2({stdout:string(),stderr:string(),outcome:discriminatedUnion("type",[object$2({type:literal("timeout")}),object$2({type:literal("exit"),exit_code:number$1()})])}))}),object$2({type:literal("tool_search_call"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown()}),object$2({type:literal("tool_search_output"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array$1(record(string(),jsonValueSchema2.optional()))})])}),object$2({type:literal("response.output_item.done"),output_index:number$1(),item:discriminatedUnion("type",[object$2({type:literal("message"),id:string(),phase:_enum(["commentary","final_answer"]).nullish()}),object$2({type:literal("reasoning"),id:string(),encrypted_content:string().nullish()}),object$2({type:literal("function_call"),id:string(),call_id:string(),name:string(),arguments:string(),status:literal("completed"),namespace:string().nullish()}),object$2({type:literal("custom_tool_call"),id:string(),call_id:string(),name:string(),input:string(),status:literal("completed")}),object$2({type:literal("code_interpreter_call"),id:string(),code:string().nullable(),container_id:string(),outputs:array$1(discriminatedUnion("type",[object$2({type:literal("logs"),logs:string()}),object$2({type:literal("image"),url:string()})])).nullable()}),object$2({type:literal("image_generation_call"),id:string(),result:string()}),object$2({type:literal("web_search_call"),id:string(),status:string(),action:discriminatedUnion("type",[object$2({type:literal("search"),query:string().nullish(),queries:array$1(string()).nullish(),sources:array$1(discriminatedUnion("type",[object$2({type:literal("url"),url:string()}),object$2({type:literal("api"),name:string()})])).nullish()}),object$2({type:literal("open_page"),url:string().nullish()}),object$2({type:literal("find_in_page"),url:string().nullish(),pattern:string().nullish()})]).nullish()}),object$2({type:literal("file_search_call"),id:string(),queries:array$1(string()),results:array$1(object$2({attributes:record(string(),union([string(),number$1(),boolean()])),file_id:string(),filename:string(),score:number$1(),text:string()})).nullish()}),object$2({type:literal("local_shell_call"),id:string(),call_id:string(),action:object$2({type:literal("exec"),command:array$1(string()),timeout_ms:number$1().optional(),user:string().optional(),working_directory:string().optional(),env:record(string(),string()).optional()})}),object$2({type:literal("computer_call"),id:string(),status:literal("completed")}),object$2({type:literal("mcp_call"),id:string(),status:string(),arguments:string(),name:string(),server_label:string(),output:string().nullish(),error:union([string(),object$2({type:string().optional(),code:union([number$1(),string()]).optional(),message:string().optional()}).loose()]).nullish(),approval_request_id:string().nullish()}),object$2({type:literal("mcp_list_tools"),id:string(),server_label:string(),tools:array$1(object$2({name:string(),description:string().optional(),input_schema:any(),annotations:record(string(),unknown()).optional()})),error:union([string(),object$2({type:string().optional(),code:union([number$1(),string()]).optional(),message:string().optional()}).loose()]).optional()}),object$2({type:literal("mcp_approval_request"),id:string(),server_label:string(),name:string(),arguments:string(),approval_request_id:string().optional()}),object$2({type:literal("apply_patch_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object$2({type:literal("create_file"),path:string(),diff:string()}),object$2({type:literal("delete_file"),path:string()}),object$2({type:literal("update_file"),path:string(),diff:string()})])}),object$2({type:literal("shell_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),action:object$2({commands:array$1(string())})}),object$2({type:literal("shell_call_output"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),output:array$1(object$2({stdout:string(),stderr:string(),outcome:discriminatedUnion("type",[object$2({type:literal("timeout")}),object$2({type:literal("exit"),exit_code:number$1()})])}))}),object$2({type:literal("tool_search_call"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown()}),object$2({type:literal("tool_search_output"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array$1(record(string(),jsonValueSchema2.optional()))})])}),object$2({type:literal("response.function_call_arguments.delta"),item_id:string(),output_index:number$1(),delta:string()}),object$2({type:literal("response.custom_tool_call_input.delta"),item_id:string(),output_index:number$1(),delta:string()}),object$2({type:literal("response.image_generation_call.partial_image"),item_id:string(),output_index:number$1(),partial_image_b64:string()}),object$2({type:literal("response.code_interpreter_call_code.delta"),item_id:string(),output_index:number$1(),delta:string()}),object$2({type:literal("response.code_interpreter_call_code.done"),item_id:string(),output_index:number$1(),code:string()}),object$2({type:literal("response.output_text.annotation.added"),annotation:discriminatedUnion("type",[object$2({type:literal("url_citation"),start_index:number$1(),end_index:number$1(),url:string(),title:string()}),object$2({type:literal("file_citation"),file_id:string(),filename:string(),index:number$1()}),object$2({type:literal("container_file_citation"),container_id:string(),file_id:string(),filename:string(),start_index:number$1(),end_index:number$1()}),object$2({type:literal("file_path"),file_id:string(),index:number$1()})])}),object$2({type:literal("response.reasoning_summary_part.added"),item_id:string(),summary_index:number$1()}),object$2({type:literal("response.reasoning_summary_text.delta"),item_id:string(),summary_index:number$1(),delta:string()}),object$2({type:literal("response.reasoning_summary_part.done"),item_id:string(),summary_index:number$1()}),object$2({type:literal("response.apply_patch_call_operation_diff.delta"),item_id:string(),output_index:number$1(),delta:string(),obfuscation:string().nullish()}),object$2({type:literal("response.apply_patch_call_operation_diff.done"),item_id:string(),output_index:number$1(),diff:string()}),object$2({type:literal("error"),sequence_number:number$1(),error:object$2({type:string(),code:string(),message:string(),param:string().nullish()})}),object$2({type:string()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),openaiResponsesResponseSchema=lazySchema(()=>zodSchema(object$2({id:string().optional(),created_at:number$1().optional(),error:object$2({message:string(),type:string(),param:string().nullish(),code:string()}).nullish(),model:string().optional(),output:array$1(discriminatedUnion("type",[object$2({type:literal("message"),role:literal("assistant"),id:string(),phase:_enum(["commentary","final_answer"]).nullish(),content:array$1(object$2({type:literal("output_text"),text:string(),logprobs:array$1(object$2({token:string(),logprob:number$1(),top_logprobs:array$1(object$2({token:string(),logprob:number$1()}))})).nullish(),annotations:array$1(discriminatedUnion("type",[object$2({type:literal("url_citation"),start_index:number$1(),end_index:number$1(),url:string(),title:string()}),object$2({type:literal("file_citation"),file_id:string(),filename:string(),index:number$1()}),object$2({type:literal("container_file_citation"),container_id:string(),file_id:string(),filename:string(),start_index:number$1(),end_index:number$1()}),object$2({type:literal("file_path"),file_id:string(),index:number$1()})]))}))}),object$2({type:literal("web_search_call"),id:string(),status:string(),action:discriminatedUnion("type",[object$2({type:literal("search"),query:string().nullish(),queries:array$1(string()).nullish(),sources:array$1(discriminatedUnion("type",[object$2({type:literal("url"),url:string()}),object$2({type:literal("api"),name:string()})])).nullish()}),object$2({type:literal("open_page"),url:string().nullish()}),object$2({type:literal("find_in_page"),url:string().nullish(),pattern:string().nullish()})]).nullish()}),object$2({type:literal("file_search_call"),id:string(),queries:array$1(string()),results:array$1(object$2({attributes:record(string(),union([string(),number$1(),boolean()])),file_id:string(),filename:string(),score:number$1(),text:string()})).nullish()}),object$2({type:literal("code_interpreter_call"),id:string(),code:string().nullable(),container_id:string(),outputs:array$1(discriminatedUnion("type",[object$2({type:literal("logs"),logs:string()}),object$2({type:literal("image"),url:string()})])).nullable()}),object$2({type:literal("image_generation_call"),id:string(),result:string()}),object$2({type:literal("local_shell_call"),id:string(),call_id:string(),action:object$2({type:literal("exec"),command:array$1(string()),timeout_ms:number$1().optional(),user:string().optional(),working_directory:string().optional(),env:record(string(),string()).optional()})}),object$2({type:literal("function_call"),call_id:string(),name:string(),arguments:string(),id:string(),namespace:string().nullish()}),object$2({type:literal("custom_tool_call"),call_id:string(),name:string(),input:string(),id:string()}),object$2({type:literal("computer_call"),id:string(),status:string().optional()}),object$2({type:literal("reasoning"),id:string(),encrypted_content:string().nullish(),summary:array$1(object$2({type:literal("summary_text"),text:string()}))}),object$2({type:literal("mcp_call"),id:string(),status:string(),arguments:string(),name:string(),server_label:string(),output:string().nullish(),error:union([string(),object$2({type:string().optional(),code:union([number$1(),string()]).optional(),message:string().optional()}).loose()]).nullish(),approval_request_id:string().nullish()}),object$2({type:literal("mcp_list_tools"),id:string(),server_label:string(),tools:array$1(object$2({name:string(),description:string().optional(),input_schema:any(),annotations:record(string(),unknown()).optional()})),error:union([string(),object$2({type:string().optional(),code:union([number$1(),string()]).optional(),message:string().optional()}).loose()]).optional()}),object$2({type:literal("mcp_approval_request"),id:string(),server_label:string(),name:string(),arguments:string(),approval_request_id:string().optional()}),object$2({type:literal("apply_patch_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object$2({type:literal("create_file"),path:string(),diff:string()}),object$2({type:literal("delete_file"),path:string()}),object$2({type:literal("update_file"),path:string(),diff:string()})])}),object$2({type:literal("shell_call"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),action:object$2({commands:array$1(string())})}),object$2({type:literal("shell_call_output"),id:string(),call_id:string(),status:_enum(["in_progress","completed","incomplete"]),output:array$1(object$2({stdout:string(),stderr:string(),outcome:discriminatedUnion("type",[object$2({type:literal("timeout")}),object$2({type:literal("exit"),exit_code:number$1()})])}))}),object$2({type:literal("tool_search_call"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown()}),object$2({type:literal("tool_search_output"),id:string(),execution:_enum(["server","client"]),call_id:string().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array$1(record(string(),jsonValueSchema2.optional()))})])).optional(),service_tier:string().nullish(),incomplete_details:object$2({reason:string()}).nullish(),usage:object$2({input_tokens:number$1(),input_tokens_details:object$2({cached_tokens:number$1().nullish(),orchestration_input_tokens:number$1().nullish(),orchestration_input_cached_tokens:number$1().nullish()}).nullish(),output_tokens:number$1(),output_tokens_details:object$2({reasoning_tokens:number$1().nullish(),orchestration_output_tokens:number$1().nullish()}).nullish()}).optional()}))),TOP_LOGPROBS_MAX=20,openaiLanguageModelResponsesOptionsSchema=lazySchema(()=>zodSchema(object$2({conversation:string().nullish(),include:array$1(_enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:string().nullish(),logprobs:union([boolean(),number$1().min(1).max(TOP_LOGPROBS_MAX)]).optional(),maxToolCalls:number$1().nullish(),metadata:any().nullish(),parallelToolCalls:boolean().nullish(),previousResponseId:string().nullish(),promptCacheKey:string().nullish(),promptCacheRetention:_enum(["in_memory","24h"]).nullish(),reasoningEffort:string().nullish(),reasoningSummary:string().nullish(),safetyIdentifier:string().nullish(),serviceTier:_enum(["auto","flex","priority","default"]).nullish(),store:boolean().nullish(),passThroughUnsupportedFiles:boolean().optional(),strictJsonSchema:boolean().nullish(),textVerbosity:_enum(["low","medium","high"]).nullish(),truncation:_enum(["auto","disabled"]).nullish(),user:string().nullish(),systemMessageMode:_enum(["system","developer","remove"]).optional(),forceReasoning:boolean().optional(),allowedTools:object$2({toolNames:array$1(string()).min(1),mode:_enum(["auto","required"]).optional()}).optional()})));async function prepareResponsesTools({tools:e,toolChoice:t,allowedTools:r,toolNameMapping:n,customProviderToolNames:o}){var a,s,i;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,d=o??new Set;for(const f of e)switch(f.type){case"function":{const h=(a=f.providerOptions)==null?void 0:a.openai,b=prepareFunctionTool({tool:f,options:h}),y=h?.namespace;if(y==null)c.push(b);else{let w=u.get(y.name);if(w==null)w={type:"namespace",name:y.name,description:y.description,tools:[]},u.set(y.name,w),c.push(w);else if(w.description!==y.description)throw new UnsupportedFunctionalityError$1({functionality:`conflicting descriptions for OpenAI tool namespace "${y.name}"`});w.tools.push(b)}break}case"provider":{switch(f.id){case"openai.file_search":{const h=await validateTypes$1({value:f.args,schema:fileSearchArgsSchema});c.push({type:"file_search",vector_store_ids:h.vectorStoreIds,max_num_results:h.maxNumResults,ranking_options:h.ranking?{ranker:h.ranking.ranker,score_threshold:h.ranking.scoreThreshold}:void 0,filters:h.filters});break}case"openai.local_shell":{c.push({type:"local_shell"});break}case"openai.shell":{const h=await validateTypes$1({value:f.args,schema:shellArgsSchema});c.push({type:"shell",...h.environment&&{environment:mapShellEnvironment(h.environment)}});break}case"openai.apply_patch":{c.push({type:"apply_patch"});break}case"openai.web_search_preview":{const h=await validateTypes$1({value:f.args,schema:webSearchPreviewArgsSchema});c.push({type:"web_search_preview",search_context_size:h.searchContextSize,user_location:h.userLocation});break}case"openai.web_search":{const h=await validateTypes$1({value:f.args,schema:webSearchArgsSchema});c.push({type:"web_search",filters:h.filters!=null?{allowed_domains:h.filters.allowedDomains}:void 0,external_web_access:h.externalWebAccess,search_context_size:h.searchContextSize,user_location:h.userLocation});break}case"openai.code_interpreter":{const h=await validateTypes$1({value:f.args,schema:codeInterpreterArgsSchema});c.push({type:"code_interpreter",container:h.container==null?{type:"auto",file_ids:void 0}:typeof h.container=="string"?h.container:{type:"auto",file_ids:h.container.fileIds}});break}case"openai.image_generation":{const h=await validateTypes$1({value:f.args,schema:imageGenerationArgsSchema});c.push({type:"image_generation",background:h.background,input_fidelity:h.inputFidelity,input_image_mask:h.inputImageMask?{file_id:h.inputImageMask.fileId,image_url:h.inputImageMask.imageUrl}:void 0,model:h.model,moderation:h.moderation,partial_images:h.partialImages,quality:h.quality,output_compression:h.outputCompression,output_format:h.outputFormat,size:h.size});break}case"openai.mcp":{const h=await validateTypes$1({value:f.args,schema:mcpArgsSchema}),b=g=>({tool_names:g.toolNames}),y=h.requireApproval,w=y==null?void 0:typeof y=="string"?y:y.never!=null?{never:b(y.never)}:void 0;c.push({type:"mcp",server_label:h.serverLabel,allowed_tools:Array.isArray(h.allowedTools)?h.allowedTools:h.allowedTools?{read_only:h.allowedTools.readOnly,tool_names:h.allowedTools.toolNames}:void 0,authorization:h.authorization,connector_id:h.connectorId,headers:h.headers,require_approval:w??"never",server_description:h.serverDescription,server_url:h.serverUrl});break}case"openai.custom":{const h=await validateTypes$1({value:f.args,schema:customArgsSchema});c.push({type:"custom",name:h.name,description:h.description,format:h.format}),d.add(h.name);break}case"openai.tool_search":{const h=await validateTypes$1({value:f.args,schema:toolSearchArgsSchema});c.push({type:"tool_search",...h.execution!=null?{execution:h.execution}:{},...h.description!=null?{description:h.description}:{},...h.parameters!=null?{parameters:h.parameters}:{}});break}}break}default:l.push({type:"unsupported",feature:`function tool ${f}`});break}if(r!=null)return{tools:c,toolChoice:{type:"allowed_tools",mode:(s=r.mode)!=null?s:"auto",tools:r.toolNames.map(f=>{var h;return{type:"function",name:(h=n?.toProviderToolName(f))!=null?h:f}})},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 f=(i=n?.toProviderToolName(t.toolName))!=null?i:t.toolName;return{tools:c,toolChoice:f==="code_interpreter"||f==="file_search"||f==="image_generation"||f==="web_search_preview"||f==="web_search"||f==="mcp"||f==="apply_patch"?{type:f}:d.has(f)?{type:"custom",name:f}:{type:"function",name:f},toolWarnings:l}}default:{const f=p;throw new UnsupportedFunctionalityError$1({functionality:`tool choice type: ${f}`})}}}function prepareFunctionTool({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 mapShellEnvironment(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:mapShellSkills(r.skills)}}return{type:"local",skills:e.skills}}function mapShellSkills(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 extractApprovalRequestIdToToolCallIdMapping(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 s=(r=(t=a.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;s!=null&&(n[s]=a.toolCallId)}return n}var OpenAIResponsesLanguageModel=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:s,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:d,responseFormat:p}){var f,h,b,y,w,g,m,S,v,_,$;const T=[],R=getOpenAILanguageModelCapabilities(this.modelId);o!=null&&T.push({type:"unsupported",feature:"topK"}),i!=null&&T.push({type:"unsupported",feature:"seed"}),a!=null&&T.push({type:"unsupported",feature:"presencePenalty"}),s!=null&&T.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&T.push({type:"unsupported",feature:"stopSequences"});const x=this.config.provider.includes("azure")?"azure":"openai";let E=await parseProviderOptions$1({provider:x,providerOptions:c,schema:openaiLanguageModelResponsesOptionsSchema});E==null&&x!=="openai"&&(E=await parseProviderOptions$1({provider:"openai",providerOptions:c,schema:openaiLanguageModelResponsesOptionsSchema}));const A=(f=E?.forceReasoning)!=null?f:R.isReasoningModel;E?.conversation&&E?.previousResponseId&&T.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const D=createToolNameMapping({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:j=>j.id==="openai.custom"?j.args.name:void 0}),U=new Set,{tools:K,toolChoice:G,toolWarnings:te}=await prepareResponsesTools({tools:u,toolChoice:d,allowedTools:(h=E?.allowedTools)!=null?h:void 0,toolNameMapping:D,customProviderToolNames:U}),{input:X,warnings:ue}=await convertToOpenAIResponsesInput({prompt:l,toolNameMapping:D,systemMessageMode:(b=E?.systemMessageMode)!=null?b:A?"developer":R.systemMessageMode,providerOptionsName:x,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(y=E?.passThroughUnsupportedFiles)!=null?y:!1,store:(w=E?.store)!=null?w:!0,hasConversation:E?.conversation!=null,hasPreviousResponseId:E?.previousResponseId!=null,hasLocalShellTool:L("openai.local_shell"),hasShellTool:L("openai.shell"),hasApplyPatchTool:L("openai.apply_patch"),customProviderToolNames:U.size>0?U:void 0});T.push(...ue);const V=(g=E?.strictJsonSchema)!=null?g:!0;let C=E?.include;function N(j){C==null?C=[j]:C.includes(j)||(C=[...C,j])}function L(j){return u?.find(M=>M.type==="provider"&&M.id===j)!=null}const I=typeof E?.logprobs=="number"?E?.logprobs:E?.logprobs===!0?TOP_LOGPROBS_MAX:void 0;I&&N("message.output_text.logprobs");const k=(m=u?.find(j=>j.type==="provider"&&(j.id==="openai.web_search"||j.id==="openai.web_search_preview")))==null?void 0:m.name;k&&N("web_search_call.action.sources"),L("openai.code_interpreter")&&N("code_interpreter_call.outputs");const O=E?.store;O===!1&&A&&N("reasoning.encrypted_content");const q={model:this.modelId,input:X,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||E?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:V,name:(S=p.name)!=null?S:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...E?.textVerbosity&&{verbosity:E.textVerbosity}}},conversation:E?.conversation,max_tool_calls:E?.maxToolCalls,metadata:E?.metadata,parallel_tool_calls:E?.parallelToolCalls,previous_response_id:E?.previousResponseId,store:O,user:E?.user,instructions:E?.instructions,service_tier:E?.serviceTier,include:C,prompt_cache_key:E?.promptCacheKey,prompt_cache_retention:E?.promptCacheRetention,safety_identifier:E?.safetyIdentifier,top_logprobs:I,truncation:E?.truncation,...A&&(E?.reasoningEffort!=null||E?.reasoningSummary!=null)&&{reasoning:{...E?.reasoningEffort!=null&&{effort:E.reasoningEffort},...E?.reasoningSummary!=null&&{summary:E.reasoningSummary}}}};A?E?.reasoningEffort==="none"&&R.supportsNonReasoningParameters||(q.temperature!=null&&(q.temperature=void 0,T.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),q.top_p!=null&&(q.top_p=void 0,T.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(E?.reasoningEffort!=null&&T.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),E?.reasoningSummary!=null&&T.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),E?.serviceTier==="flex"&&!R.supportsFlexProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete q.service_tier),E?.serviceTier==="priority"&&!R.supportsPriorityProcessing&&(T.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 q.service_tier);const B=($=(_=(v=u?.find(j=>j.type==="provider"&&j.id==="openai.shell"))==null?void 0:v.args)==null?void 0:_.environment)==null?void 0:$.type,F=B==="containerAuto"||B==="containerReference";return{webSearchToolName:k,args:{...q,tools:K,tool_choice:G},warnings:[...T,...te],store:O,toolNameMapping:D,providerOptionsName:x,isShellProviderExecuted:F}}async doGenerate(e){var t,r,n,o,a,s,i,l,c,u,d,p,f,h,b,y,w,g,m,S,v,_,$,T,R,x,E,A;const{args:D,warnings:U,webSearchToolName:K,toolNameMapping:G,providerOptionsName:te,isShellProviderExecuted:X}=await this.getArgs(e),ue=this.config.url({path:"/responses",modelId:this.modelId}),V=extractApprovalRequestIdToToolCallIdMapping(e.prompt),{responseHeaders:C,value:N,rawValue:L}=await postJsonToApi$1({url:ue,headers:combineHeaders$1(this.config.headers(),e.headers),body:D,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiResponsesResponseSchema),abortSignal:e.abortSignal,fetch:this.config.fetch});if(N.error)throw new APICallError$1({message:N.error.message,url:ue,requestBodyValues:D,statusCode:400,responseHeaders:C,responseBody:L,isRetryable:!1});const I=[],k=[];let O=!1;const q=[];for(const j of N.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const M of j.summary)I.push({type:"reasoning",text:M.text,providerMetadata:{[te]:{itemId:j.id,reasoningEncryptedContent:(t=j.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{I.push({type:"tool-call",toolCallId:j.id,toolName:G.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:j.id,toolName:G.toCustomToolName("image_generation"),result:{result:j.result}});break}case"tool_search_call":{const M=(r=j.call_id)!=null?r:j.id,Z=j.execution==="server";Z&&q.push(M),I.push({type:"tool-call",toolCallId:M,toolName:G.toCustomToolName("tool_search"),input:JSON.stringify({arguments:j.arguments,call_id:j.call_id}),...Z?{providerExecuted:!0}:{},providerMetadata:{[te]:{itemId:j.id}}});break}case"tool_search_output":{const M=(o=(n=j.call_id)!=null?n:q.shift())!=null?o:j.id;I.push({type:"tool-result",toolCallId:M,toolName:G.toCustomToolName("tool_search"),result:{tools:j.tools},providerMetadata:{[te]:{itemId:j.id}}});break}case"local_shell_call":{I.push({type:"tool-call",toolCallId:j.call_id,toolName:G.toCustomToolName("local_shell"),input:JSON.stringify({action:j.action}),providerMetadata:{[te]:{itemId:j.id}}});break}case"shell_call":{I.push({type:"tool-call",toolCallId:j.call_id,toolName:G.toCustomToolName("shell"),input:JSON.stringify({action:{commands:j.action.commands}}),...X&&{providerExecuted:!0},providerMetadata:{[te]:{itemId:j.id}}});break}case"shell_call_output":{I.push({type:"tool-result",toolCallId:j.call_id,toolName:G.toCustomToolName("shell"),result:{output:j.output.map(M=>({stdout:M.stdout,stderr:M.stderr,outcome:M.outcome.type==="exit"?{type:"exit",exitCode:M.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const M of j.content){(s=(a=e.providerOptions)==null?void 0:a[te])!=null&&s.logprobs&&M.logprobs&&k.push(M.logprobs);const Z={itemId:j.id,...j.phase!=null&&{phase:j.phase},...M.annotations.length>0&&{annotations:M.annotations}};I.push({type:"text",text:M.text,providerMetadata:{[te]:Z}});for(const H of M.annotations)H.type==="url_citation"?I.push({type:"source",sourceType:"url",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:generateId$1(),url:H.url,title:H.title}):H.type==="file_citation"?I.push({type:"source",sourceType:"document",id:(p=(d=(u=this.config).generateId)==null?void 0:d.call(u))!=null?p:generateId$1(),mediaType:"text/plain",title:H.filename,filename:H.filename,providerMetadata:{[te]:{type:H.type,fileId:H.file_id,index:H.index}}}):H.type==="container_file_citation"?I.push({type:"source",sourceType:"document",id:(b=(h=(f=this.config).generateId)==null?void 0:h.call(f))!=null?b:generateId$1(),mediaType:"text/plain",title:H.filename,filename:H.filename,providerMetadata:{[te]:{type:H.type,fileId:H.file_id,containerId:H.container_id}}}):H.type==="file_path"&&I.push({type:"source",sourceType:"document",id:(g=(w=(y=this.config).generateId)==null?void 0:w.call(y))!=null?g:generateId$1(),mediaType:"application/octet-stream",title:H.file_id,filename:H.file_id,providerMetadata:{[te]:{type:H.type,fileId:H.file_id,index:H.index}}})}break}case"function_call":{O=!0,I.push({type:"tool-call",toolCallId:j.call_id,toolName:j.name,input:j.arguments,providerMetadata:{[te]:{itemId:j.id,...j.namespace!=null&&{namespace:j.namespace}}}});break}case"custom_tool_call":{O=!0;const M=G.toCustomToolName(j.name);I.push({type:"tool-call",toolCallId:j.call_id,toolName:M,input:JSON.stringify(j.input),providerMetadata:{[te]:{itemId:j.id}}});break}case"web_search_call":{I.push({type:"tool-call",toolCallId:j.id,toolName:G.toCustomToolName(K??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:j.id,toolName:G.toCustomToolName(K??"web_search"),result:mapWebSearchOutput(j.action)});break}case"mcp_call":{const M=j.approval_request_id!=null&&(m=V[j.approval_request_id])!=null?m:j.id,Z=`mcp.${j.name}`;I.push({type:"tool-call",toolCallId:M,toolName:Z,input:j.arguments,providerExecuted:!0,dynamic:!0}),I.push({type:"tool-result",toolCallId:M,toolName:Z,result:{type:"call",serverLabel:j.server_label,name:j.name,arguments:j.arguments,...j.output!=null?{output:j.output}:{},...j.error!=null?{error:j.error}:{}},providerMetadata:{[te]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const M=(S=j.approval_request_id)!=null?S:j.id,Z=($=(_=(v=this.config).generateId)==null?void 0:_.call(v))!=null?$:generateId$1(),H=`mcp.${j.name}`;I.push({type:"tool-call",toolCallId:Z,toolName:H,input:j.arguments,providerExecuted:!0,dynamic:!0}),I.push({type:"tool-approval-request",approvalId:M,toolCallId:Z});break}case"computer_call":{I.push({type:"tool-call",toolCallId:j.id,toolName:G.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:j.id,toolName:G.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:j.status||"completed"}});break}case"file_search_call":{I.push({type:"tool-call",toolCallId:j.id,toolName:G.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:j.id,toolName:G.toCustomToolName("file_search"),result:{queries:j.queries,results:(R=(T=j.results)==null?void 0:T.map(M=>({attributes:M.attributes,fileId:M.file_id,filename:M.filename,score:M.score,text:M.text})))!=null?R:null}});break}case"code_interpreter_call":{I.push({type:"tool-call",toolCallId:j.id,toolName:G.toCustomToolName("code_interpreter"),input:JSON.stringify({code:j.code,containerId:j.container_id}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:j.id,toolName:G.toCustomToolName("code_interpreter"),result:{outputs:j.outputs}});break}case"apply_patch_call":{I.push({type:"tool-call",toolCallId:j.call_id,toolName:G.toCustomToolName("apply_patch"),input:JSON.stringify({callId:j.call_id,operation:j.operation}),providerMetadata:{[te]:{itemId:j.id}}});break}}const B={[te]:{responseId:N.id,...k.length>0?{logprobs:k}:{},...typeof N.service_tier=="string"?{serviceTier:N.service_tier}:{}}},F=N.usage;return{content:I,finishReason:{unified:mapOpenAIResponseFinishReason({finishReason:(x=N.incomplete_details)==null?void 0:x.reason,hasFunctionCall:O}),raw:(A=(E=N.incomplete_details)==null?void 0:E.reason)!=null?A:void 0},usage:convertOpenAIResponsesUsage(F),request:{body:D},response:{id:N.id,timestamp:new Date(N.created_at*1e3),modelId:N.model,headers:C,body:L},providerMetadata:B,warnings:U}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:a,providerOptionsName:s,isShellProviderExecuted:i}=await this.getArgs(e),l=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:c,value:u}=await postJsonToApi$1({url:l,headers:combineHeaders$1(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler$1(openaiResponsesChunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=this,p=extractApprovalRequestIdToToolCallIdMapping(e.prompt),f=new Map;let h={unified:"other",raw:void 0},b;const y=[];let w=null;const g={},m=[];let S,v=!1;const _={};let $;const T=[];return{stream:u.pipeThrough(new TransformStream({start(R){R.enqueue({type:"stream-start",warnings:r})},transform(R,x){var E,A,D,U,K,G,te,X,ue,V,C,N,L,I,k,O,q,B,F,j,M,Z,H,J,oe,se,_e,Te,Se,Q,ve,de,ne,ae,ee,Y,ce,le;if(e.includeRawChunks&&x.enqueue({type:"raw",rawValue:R.rawValue}),!R.success){const W=isOpenAIChatCompletionChunk(R.rawValue)?createOpenAIResponsesChatCompletionsMismatchError({value:R.rawValue,cause:R.error,url:l,requestBodyValues:t,responseHeaders:c}):R.error;h={unified:"error",raw:void 0},x.enqueue({type:"error",error:W});return}const P=R.value;if(isResponseOutputItemAddedChunk(P)){if(P.item.type==="function_call")g[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},x.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="custom_tool_call"){const W=o.toCustomToolName(P.item.name);g[P.output_index]={toolName:W,toolCallId:P.item.call_id},x.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:W})}else if(P.item.type==="web_search_call")g[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),x.enqueue({type:"tool-input-end",id:P.item.id}),x.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")g[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")g[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),x.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")x.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 W=P.item.id,he=o.toCustomToolName("tool_search"),Ee=P.item.execution==="server";g[P.output_index]={toolName:he,toolCallId:W,toolSearchExecution:(E=P.item.execution)!=null?E:"server"},Ee&&x.enqueue({type:"tool-input-start",id:W,toolName:he,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:W,operation:he}=P.item;if(g[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:W,applyPatch:{hasDiff:he.type==="delete_file",endEmitted:he.type==="delete_file"}},x.enqueue({type:"tool-input-start",id:W,toolName:o.toCustomToolName("apply_patch")}),he.type==="delete_file"){const Ee=JSON.stringify({callId:W,operation:he});x.enqueue({type:"tool-input-delta",id:W,delta:Ee}),x.enqueue({type:"tool-input-end",id:W})}else x.enqueue({type:"tool-input-delta",id:W,delta:`{"callId":"${escapeJSONDelta(W)}","operation":{"type":"${escapeJSONDelta(he.type)}","path":"${escapeJSONDelta(he.path)}","diff":"`})}else P.item.type==="shell_call"?g[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(m.splice(0,m.length),S=(A=P.item.phase)!=null?A:void 0,x.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[s]:{itemId:P.item.id,...P.item.phase!=null&&{phase:P.item.phase}}}})):isResponseOutputItemAddedChunk(P)&&P.item.type==="reasoning"&&(_[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},x.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[s]:{itemId:P.item.id,reasoningEncryptedContent:(D=P.item.encrypted_content)!=null?D:null}}})))}}else if(isResponseOutputItemDoneChunk(P)){if(P.item.type==="message"){const W=(U=P.item.phase)!=null?U:S;S=void 0,x.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[s]:{itemId:P.item.id,...W!=null&&{phase:W},...m.length>0&&{annotations:m}}}})}else if(P.item.type==="function_call")g[P.output_index]=void 0,v=!0,x.enqueue({type:"tool-input-end",id:P.item.call_id,...P.item.namespace!=null&&{providerMetadata:{[s]:{namespace:P.item.namespace}}}}),x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[s]:{itemId:P.item.id,...P.item.namespace!=null&&{namespace:P.item.namespace}}}});else if(P.item.type==="custom_tool_call"){g[P.output_index]=void 0,v=!0;const W=o.toCustomToolName(P.item.name);x.enqueue({type:"tool-input-end",id:P.item.call_id}),x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:W,input:JSON.stringify(P.item.input),providerMetadata:{[s]:{itemId:P.item.id}}})}else if(P.item.type==="web_search_call")g[P.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:mapWebSearchOutput(P.item.action)});else if(P.item.type==="computer_call")g[P.output_index]=void 0,x.enqueue({type:"tool-input-end",id:P.item.id}),x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.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")g[P.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(G=(K=P.item.results)==null?void 0:K.map(W=>({attributes:W.attributes,fileId:W.file_id,filename:W.filename,score:W.score,text:W.text})))!=null?G:null}});else if(P.item.type==="code_interpreter_call")g[P.output_index]=void 0,x.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")x.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 W=g[P.output_index],he=P.item.execution==="server";if(W!=null){const Ee=he?W.toolCallId:(te=P.item.call_id)!=null?te:P.item.id;he?T.push(Ee):x.enqueue({type:"tool-input-start",id:Ee,toolName:W.toolName}),x.enqueue({type:"tool-input-end",id:Ee}),x.enqueue({type:"tool-call",toolCallId:Ee,toolName:W.toolName,input:JSON.stringify({arguments:P.item.arguments,call_id:he?null:Ee}),...he?{providerExecuted:!0}:{},providerMetadata:{[s]:{itemId:P.item.id}}})}g[P.output_index]=void 0}else if(P.item.type==="tool_search_output"){const W=(ue=(X=P.item.call_id)!=null?X:T.shift())!=null?ue:P.item.id;x.enqueue({type:"tool-result",toolCallId:W,toolName:o.toCustomToolName("tool_search"),result:{tools:P.item.tools},providerMetadata:{[s]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_call"){g[P.output_index]=void 0;const W=(V=P.item.approval_request_id)!=null?V:void 0,he=W!=null&&(N=(C=f.get(W))!=null?C:p[W])!=null?N:P.item.id,Ee=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:he,toolName:Ee,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-result",toolCallId:he,toolName:Ee,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:{[s]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")g[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const W=g[P.output_index];W?.applyPatch&&!W.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(W.applyPatch.hasDiff||x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:escapeJSONDelta(P.item.operation.diff)}),x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:W.toolCallId}),W.applyPatch.endEmitted=!0),W&&P.item.status==="completed"&&x.enqueue({type:"tool-call",toolCallId:W.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[s]:{itemId:P.item.id}}}),g[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){g[P.output_index]=void 0;const W=(k=(I=(L=d.config).generateId)==null?void 0:I.call(L))!=null?k:generateId$1(),he=(O=P.item.approval_request_id)!=null?O:P.item.id;f.set(he,W);const Ee=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:W,toolName:Ee,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-approval-request",approvalId:he,toolCallId:W})}else if(P.item.type==="local_shell_call")g[P.output_index]=void 0,x.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:{[s]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")g[P.output_index]=void 0,x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[s]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")x.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="exit"?{type:"exit",exitCode:W.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const W=_[P.item.id],he=Object.entries(W.summaryParts).filter(([Ee,Ye])=>Ye==="active"||Ye==="can-conclude").map(([Ee])=>Ee);for(const Ee of he)x.enqueue({type:"reasoning-end",id:`${P.item.id}:${Ee}`,providerMetadata:{[s]:{itemId:P.item.id,reasoningEncryptedContent:(q=P.item.encrypted_content)!=null?q:null}}});delete _[P.item.id]}}else if(isResponseFunctionCallArgumentsDeltaChunk(P)){const W=g[P.output_index];W!=null&&x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:P.delta})}else if(isResponseCustomToolCallInputDeltaChunk(P)){const W=g[P.output_index];W!=null&&x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:P.delta})}else if(isResponseApplyPatchCallOperationDiffDeltaChunk(P)){const W=g[P.output_index];W?.applyPatch&&(x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:escapeJSONDelta(P.delta)}),W.applyPatch.hasDiff=!0)}else if(isResponseApplyPatchCallOperationDiffDoneChunk(P)){const W=g[P.output_index];W?.applyPatch&&!W.applyPatch.endEmitted&&(W.applyPatch.hasDiff||(x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:escapeJSONDelta(P.diff)}),W.applyPatch.hasDiff=!0),x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:W.toolCallId}),W.applyPatch.endEmitted=!0)}else if(isResponseImageGenerationCallPartialImageChunk(P))x.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(isResponseCodeInterpreterCallCodeDeltaChunk(P)){const W=g[P.output_index];W!=null&&x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:escapeJSONDelta(P.delta)})}else if(isResponseCodeInterpreterCallCodeDoneChunk(P)){const W=g[P.output_index];W!=null&&(x.enqueue({type:"tool-input-delta",id:W.toolCallId,delta:'"}'}),x.enqueue({type:"tool-input-end",id:W.toolCallId}),x.enqueue({type:"tool-call",toolCallId:W.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:W.codeInterpreter.containerId}),providerExecuted:!0}))}else if(isResponseCreatedChunk(P))w=P.response.id,x.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(isTextDeltaChunk(P))x.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(F=(B=e.providerOptions)==null?void 0:B[s])!=null&&F.logprobs&&P.logprobs&&y.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const W=_[P.item_id];W.summaryParts[P.summary_index]="active";for(const he of Object.keys(W.summaryParts))W.summaryParts[he]==="can-conclude"&&(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${he}`,providerMetadata:{[s]:{itemId:P.item_id}}}),W.summaryParts[he]="concluded");x.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[s]:{itemId:P.item_id,reasoningEncryptedContent:(M=(j=_[P.item_id])==null?void 0:j.encryptedContent)!=null?M:null}}})}}else if(P.type==="response.reasoning_summary_text.delta")x.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[s]:{itemId:P.item_id}}});else if(P.type==="response.reasoning_summary_part.done")a?(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[s]:{itemId:P.item_id}}}),_[P.item_id].summaryParts[P.summary_index]="concluded"):_[P.item_id].summaryParts[P.summary_index]="can-conclude";else if(isResponseFinishedChunk(P))h={unified:mapOpenAIResponseFinishReason({finishReason:(Z=P.response.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:v}),raw:(J=(H=P.response.incomplete_details)==null?void 0:H.reason)!=null?J:void 0},b=P.response.usage,typeof P.response.service_tier=="string"&&($=P.response.service_tier);else if(isResponseFailedChunk(P)){const W=(oe=P.response.incomplete_details)==null?void 0:oe.reason;h={unified:W?mapOpenAIResponseFinishReason({finishReason:W,hasFunctionCall:v}):"error",raw:W??"error"},b=(se=P.response.usage)!=null?se:void 0}else isResponseAnnotationAddedChunk(P)?(m.push(P.annotation),P.annotation.type==="url_citation"?x.enqueue({type:"source",sourceType:"url",id:(Se=(Te=(_e=d.config).generateId)==null?void 0:Te.call(_e))!=null?Se:generateId$1(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?x.enqueue({type:"source",sourceType:"document",id:(de=(ve=(Q=d.config).generateId)==null?void 0:ve.call(Q))!=null?de:generateId$1(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[s]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?x.enqueue({type:"source",sourceType:"document",id:(ee=(ae=(ne=d.config).generateId)==null?void 0:ae.call(ne))!=null?ee:generateId$1(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[s]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&x.enqueue({type:"source",sourceType:"document",id:(le=(ce=(Y=d.config).generateId)==null?void 0:ce.call(Y))!=null?le:generateId$1(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[s]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):isErrorChunk(P)&&x.enqueue({type:"error",error:P})},flush(R){const x={[s]:{responseId:w,...y.length>0?{logprobs:y}:{},...$!==void 0?{serviceTier:$}:{}}};R.enqueue({type:"finish",finishReason:h,usage:convertOpenAIResponsesUsage(b),providerMetadata:x})}})),request:{body:t},response:{headers:c}}}};function isTextDeltaChunk(e){return e.type==="response.output_text.delta"}function isOpenAIChatCompletionChunk(e){const t=asRecord(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!="string"}function createOpenAIResponsesChatCompletionsMismatchError({value:e,cause:t,url:r,requestBodyValues:n,responseHeaders:o}){return new APICallError$1({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 asRecord(e){return typeof e=="object"&&e!=null?e:void 0}function isResponseOutputItemDoneChunk(e){return e.type==="response.output_item.done"}function isResponseFinishedChunk(e){return e.type==="response.completed"||e.type==="response.incomplete"}function isResponseFailedChunk(e){return e.type==="response.failed"}function isResponseCreatedChunk(e){return e.type==="response.created"}function isResponseFunctionCallArgumentsDeltaChunk(e){return e.type==="response.function_call_arguments.delta"}function isResponseCustomToolCallInputDeltaChunk(e){return e.type==="response.custom_tool_call_input.delta"}function isResponseImageGenerationCallPartialImageChunk(e){return e.type==="response.image_generation_call.partial_image"}function isResponseCodeInterpreterCallCodeDeltaChunk(e){return e.type==="response.code_interpreter_call_code.delta"}function isResponseCodeInterpreterCallCodeDoneChunk(e){return e.type==="response.code_interpreter_call_code.done"}function isResponseApplyPatchCallOperationDiffDeltaChunk(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function isResponseApplyPatchCallOperationDiffDoneChunk(e){return e.type==="response.apply_patch_call_operation_diff.done"}function isResponseOutputItemAddedChunk(e){return e.type==="response.output_item.added"}function isResponseAnnotationAddedChunk(e){return e.type==="response.output_text.annotation.added"}function isErrorChunk(e){return e.type==="error"}function mapWebSearchOutput(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 escapeJSONDelta(e){return JSON.stringify(e).slice(1,-1)}var openaiSpeechModelOptionsSchema=lazySchema(()=>zodSchema(object$2({instructions:string().nullish(),speed:number$1().min(.25).max(4).default(1).nullish()}))),OpenAISpeechModel=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:s}){const i=[],l=await parseProviderOptions$1({provider:"openai",providerOptions:s,schema:openaiSpeechModelOptionsSchema}),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:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const d in u){const p=u[d];p!==void 0&&(c[d]=p)}}return a&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:c,warnings:i}}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:s}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await postJsonToApi$1({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),body:a,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createBinaryResponseHandler(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:s,request:{body:JSON.stringify(a)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},openaiTranscriptionResponseSchema=lazySchema(()=>zodSchema(object$2({text:string(),language:string().nullish(),duration:number$1().nullish(),words:array$1(object$2({word:string(),start:number$1(),end:number$1()})).nullish(),segments:array$1(object$2({id:number$1(),seek:number$1(),start:number$1(),end:number$1(),text:string(),tokens:array$1(number$1()),temperature:number$1(),avg_logprob:number$1(),compression_ratio:number$1(),no_speech_prob:number$1()})).nullish()}))),openAITranscriptionModelOptions=lazySchema(()=>zodSchema(object$2({include:array$1(string()).optional(),language:string().optional(),prompt:string().optional(),temperature:number$1().min(0).max(1).default(0).optional(),timestampGranularities:array$1(_enum(["word","segment"])).default(["segment"]).optional()}))),languageMap={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"},OpenAITranscriptionModel=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 parseProviderOptions$1({provider:"openai",providerOptions:r,schema:openAITranscriptionModelOptions}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([convertBase64ToUint8Array(e)]);a.append("model",this.modelId);const i=mediaTypeToExtension(t);if(a.append("file",new File([s],"audio",{type:t}),`audio.${i}`),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 d of u)a.append(`${c}[]`,String(d));else a.append(c,String(u))}return{formData:a,warnings:n}}async doGenerate(e){var t,r,n,o,a,s,i,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:d}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:h}=await postFormDataToApi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:combineHeaders$1(this.config.headers(),e.headers),formData:u,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler$1(openaiTranscriptionResponseSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=p.language!=null&&p.language in languageMap?languageMap[p.language]:void 0;return{text:p.text,segments:(i=(s=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?s:(a=p.words)==null?void 0:a.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:b,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:d,response:{timestamp:c,modelId:this.modelId,headers:f,body:h}}}},VERSION$2="3.0.78";function createOpenAI(e={}){var t,r;const n=(t=withoutTrailingSlash$1(loadOptionalSetting({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",a=()=>withUserAgentSuffix$1({Authorization:`Bearer ${loadApiKey$1({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${VERSION$2}`),s=b=>new OpenAIChatLanguageModel(b,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch}),i=b=>new OpenAICompletionLanguageModel(b,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch}),l=b=>new OpenAIEmbeddingModel(b,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch}),c=b=>new OpenAIImageModel(b,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch}),u=b=>new OpenAITranscriptionModel(b,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch}),d=b=>new OpenAISpeechModel(b,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,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 f(b)},f=b=>new OpenAIResponsesLanguageModel(b,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:a,fetch:e.fetch,fileIdPrefixes:["file-"]}),h=function(b){return p(b)};return h.specificationVersion="v3",h.languageModel=p,h.chat=s,h.completion=i,h.responses=f,h.embedding=l,h.embeddingModel=l,h.textEmbedding=l,h.textEmbeddingModel=l,h.image=c,h.imageModel=c,h.transcription=u,h.transcriptionModel=u,h.speech=d,h.speechModel=d,h.tools=openaiTools,h}createOpenAI();var marker="vercel.ai.error",symbol=Symbol.for(marker),_a,_AISDKError=class Gt extends Error{constructor({name:t,message:r,cause:n}){super(r),this[_a]=!0,this.name=t,this.cause=n}static isInstance(t){return Gt.hasMarker(t,marker)}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}};_a=symbol;var AISDKError=_AISDKError,name="AI_APICallError",marker2=`vercel.ai.error.${name}`,symbol2=Symbol.for(marker2),_a2,APICallError=class extends AISDKError{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:a,cause:s,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name,message:e,cause:s}),this[_a2]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=a,this.isRetryable=i,this.data=l}static isInstance(e){return AISDKError.hasMarker(e,marker2)}};_a2=symbol2;var name2="AI_EmptyResponseBodyError",marker3=`vercel.ai.error.${name2}`,symbol3=Symbol.for(marker3),_a3,EmptyResponseBodyError=class extends AISDKError{constructor({message:e="Empty response body"}={}){super({name:name2,message:e}),this[_a3]=!0}static isInstance(e){return AISDKError.hasMarker(e,marker3)}};_a3=symbol3;function getErrorMessage(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var name3="AI_InvalidArgumentError",marker4=`vercel.ai.error.${name3}`,symbol4=Symbol.for(marker4),_a4,InvalidArgumentError=class extends AISDKError{constructor({message:e,cause:t,argument:r}){super({name:name3,message:e,cause:t}),this[_a4]=!0,this.argument=r}static isInstance(e){return AISDKError.hasMarker(e,marker4)}};_a4=symbol4;var name5="AI_InvalidResponseDataError",marker6=`vercel.ai.error.${name5}`,symbol6=Symbol.for(marker6),_a6,InvalidResponseDataError=class extends AISDKError{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:name5,message:t}),this[_a6]=!0,this.data=e}static isInstance(e){return AISDKError.hasMarker(e,marker6)}};_a6=symbol6;var name6="AI_JSONParseError",marker7=`vercel.ai.error.${name6}`,symbol7=Symbol.for(marker7),_a7,JSONParseError=class extends AISDKError{constructor({text:e,cause:t}){super({name:name6,message:`JSON parsing failed: Text: ${e}.
|
|
603
|
-
Error message: ${getErrorMessage(t)}`,cause:t}),this[_a7]=!0,this.text=e}static isInstance(e){return AISDKError.hasMarker(e,marker7)}};_a7=symbol7;var name7="AI_LoadAPIKeyError",marker8=`vercel.ai.error.${name7}`,symbol8=Symbol.for(marker8),_a8,LoadAPIKeyError=class extends AISDKError{constructor({message:e}){super({name:name7,message:e}),this[_a8]=!0}static isInstance(e){return AISDKError.hasMarker(e,marker8)}};_a8=symbol8;var name10="AI_NoSuchModelError",marker11=`vercel.ai.error.${name10}`,symbol11=Symbol.for(marker11),_a11,NoSuchModelError=class extends AISDKError{constructor({errorName:e=name10,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[_a11]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return AISDKError.hasMarker(e,marker11)}};_a11=symbol11;var name12="AI_TypeValidationError",marker13=`vercel.ai.error.${name12}`,symbol13=Symbol.for(marker13),_a13,_TypeValidationError=class jt extends AISDKError{constructor({value:t,cause:r}){super({name:name12,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
604
|
-
Error message: ${getErrorMessage(r)}`,cause:r}),this[_a13]=!0,this.value=t}static isInstance(t){return AISDKError.hasMarker(t,marker13)}static wrap({value:t,cause:r}){return jt.isInstance(r)&&r.value===t?r:new jt({value:t,cause:r})}};_a13=symbol13;var TypeValidationError=_TypeValidationError,name13="AI_UnsupportedFunctionalityError",marker14=`vercel.ai.error.${name13}`,symbol14=Symbol.for(marker14),_a14,UnsupportedFunctionalityError=class extends AISDKError{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:name13,message:t}),this[_a14]=!0,this.functionality=e}static isInstance(e){return AISDKError.hasMarker(e,marker14)}};_a14=symbol14;function combineHeaders(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function extractResponseHeaders(e){return Object.fromEntries([...e.headers])}var createIdGenerator=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,s=new Array(t);for(let i=0;i<t;i++)s[i]=r[Math.random()*a|0];return s.join("")};if(e==null)return o;if(r.includes(n))throw new InvalidArgumentError({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},generateId=createIdGenerator();function isAbortError(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var FETCH_FAILED_ERROR_MESSAGES=["fetch failed","failed to fetch"];function handleFetchError({error:e,url:t,requestBodyValues:r}){if(isAbortError(e))return e;if(e instanceof TypeError&&FETCH_FAILED_ERROR_MESSAGES.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new APICallError({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function getRuntimeEnvironmentUserAgent(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 normalizeHeaders(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 withUserAgentSuffix(e,...t){const r=new Headers(normalizeHeaders(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var VERSION$1="3.0.18";function loadApiKey({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new LoadAPIKeyError({message:`${n} API key must be a string.`});if(typeof process>"u")throw new LoadAPIKeyError({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 LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new LoadAPIKeyError({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var suspectProtoRx=/"__proto__"\s*:/,suspectConstructorRx=/"constructor"\s*:/;function _parse(e){const t=JSON.parse(e);return t===null||typeof t!="object"||suspectProtoRx.test(e)===!1&&suspectConstructorRx.test(e)===!1?t:filter(t)}function filter(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 secureJsonParse(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return _parse(e)}try{return _parse(e)}finally{Error.stackTraceLimit=t}}var validatorSymbol=Symbol.for("vercel.ai.validator");function validator(e){return{[validatorSymbol]:!0,validate:e}}function isValidator(e){return typeof e=="object"&&e!==null&&validatorSymbol in e&&e[validatorSymbol]===!0&&"validate"in e}function asValidator(e){return isValidator(e)?e:typeof e=="function"?e():standardSchemaValidator(e)}function standardSchemaValidator(e){return validator(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new TypeValidationError({value:t,cause:r.issues})}})}async function validateTypes({value:e,schema:t}){const r=await safeValidateTypes({value:e,schema:t});if(!r.success)throw TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function safeValidateTypes({value:e,schema:t}){const r=asValidator(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:TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function parseJSON({text:e,schema:t}){try{const r=secureJsonParse(e);return t==null?r:validateTypes({value:r,schema:t})}catch(r){throw JSONParseError.isInstance(r)||TypeValidationError.isInstance(r)?r:new JSONParseError({text:e,cause:r})}}async function safeParseJSON({text:e,schema:t}){try{const r=secureJsonParse(e);return t==null?{success:!0,value:r,rawValue:r}:await safeValidateTypes({value:r,schema:t})}catch(r){return{success:!1,error:JSONParseError.isInstance(r)?r:new JSONParseError({text:e,cause:r}),rawValue:void 0}}}function isParsableJson(e){try{return secureJsonParse(e),!0}catch{return!1}}function parseJsonEventStream({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await safeParseJSON({text:r,schema:t}))}}))}async function parseProviderOptions({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await safeValidateTypes({value:t[e],schema:r});if(!n.success)throw new InvalidArgumentError({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var getOriginalFetch2=()=>globalThis.fetch,postJsonToApi=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s})=>postToApi({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:s}),postToApi=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:s=getOriginalFetch2()})=>{try{const i=await s(e,{method:"POST",headers:withUserAgentSuffix(t,`ai-sdk/provider-utils/${VERSION$1}`,getRuntimeEnvironmentUserAgent()),body:r.content,signal:a}),l=extractResponseHeaders(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw isAbortError(u)||APICallError.isInstance(u)?u:new APICallError({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(isAbortError(c)||APICallError.isInstance(c))?c:new APICallError({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw handleFetchError({error:i,url:e,requestBodyValues:r.values})}},createJsonErrorResponseHandler=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const s=await n.text(),i=extractResponseHeaders(n);if(s.trim()==="")return{responseHeaders:i,value:new APICallError({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r?.(n)})};try{const l=await parseJSON({text:s,schema:e});return{responseHeaders:i,value:new APICallError({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new APICallError({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r?.(n)})}}},createEventSourceResponseHandler=e=>async({response:t})=>{const r=extractResponseHeaders(t);if(t.body==null)throw new EmptyResponseBodyError({});return{responseHeaders:r,value:parseJsonEventStream({stream:t.body,schema:e})}},createJsonResponseHandler=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),a=await safeParseJSON({text:o,schema:e}),s=extractResponseHeaders(t);if(!a.success)throw new APICallError({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:s,value:a.value,rawValue:a.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:btoa$1}=globalThis;function convertUint8ArrayToBase64(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return btoa$1(t)}function convertToBase64(e){return e instanceof Uint8Array?convertUint8ArrayToBase64(e):e}function withoutTrailingSlash(e){return e?.replace(/\/$/,"")}function getOpenAIMetadata(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function convertToOpenAICompatibleChatMessages(e){const t=[];for(const{role:r,content:n,...o}of e){const a=getOpenAIMetadata({...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,...getOpenAIMetadata(n[0])});break}t.push({role:"user",content:n.map(s=>{const i=getOpenAIMetadata(s);switch(s.type){case"text":return{type:"text",text:s.text,...i};case"file":if(s.mediaType.startsWith("image/")){const l=s.mediaType==="image/*"?"image/jpeg":s.mediaType;return{type:"image_url",image_url:{url:s.data instanceof URL?s.data.toString():`data:${l};base64,${convertToBase64(s.data)}`},...i}}else throw new UnsupportedFunctionalityError({functionality:`file part media type ${s.mediaType}`})}}),...a});break}case"assistant":{let s="";const i=[];for(const l of n){const c=getOpenAIMetadata(l);switch(l.type){case"text":{s+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:s,tool_calls:i.length>0?i:void 0,...a});break}case"tool":{for(const s of n){const i=s.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=getOpenAIMetadata(s);t.push({role:"tool",tool_call_id:s.toolCallId,content:l,...c})}break}default:{const s=r;throw new Error(`Unsupported role: ${s}`)}}}return t}function getResponseMetadata({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 mapOpenAICompatibleFinishReason(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 openaiCompatibleProviderOptions=object$2({user:string().optional(),reasoningEffort:string().optional(),textVerbosity:string().optional()}),openaiCompatibleErrorDataSchema=object$2({error:object$2({message:string(),type:string().nullish(),param:any().nullish(),code:union([string(),number$1()]).nullish()})}),defaultOpenAICompatibleErrorStructure={errorSchema:openaiCompatibleErrorDataSchema,errorToMessage:e=>e.error.message};function prepareTools({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 UnsupportedFunctionalityError({functionality:`tool choice type: ${a}`})}}}var OpenAICompatibleChatLanguageModel=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:defaultOpenAICompatibleErrorStructure;this.chunkSchema=createOpenAICompatibleChatChunkSchema(o.errorSchema),this.failedResponseHandler=createJsonErrorResponseHandler(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:s,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:d,tools:p}){var f,h,b,y;const w=[],g=Object.assign((f=await parseProviderOptions({provider:"openai-compatible",providerOptions:i,schema:openaiCompatibleProviderOptions}))!=null?f:{},(h=await parseProviderOptions({provider:this.providerOptionsName,providerOptions:i,schema:openaiCompatibleProviderOptions}))!=null?h:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:m,toolChoice:S,toolWarnings:v}=prepareTools({tools:p,toolChoice:d});return{args:{model:this.modelId,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:s,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((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([_])=>!Object.keys(openaiCompatibleProviderOptions.shape).includes(_))),reasoning_effort:g.reasoningEffort,verbosity:g.textVerbosity,messages:convertToOpenAICompatibleChatMessages(e),tools:m,tool_choice:S},warnings:[...w,...v]}}async doGenerate(e){var t,r,n,o,a,s,i,l,c,u,d,p,f,h,b,y,w;const{args:g,warnings:m}=await this.getArgs({...e}),S=JSON.stringify(g),{responseHeaders:v,value:_,rawValue:$}=await postJsonToApi({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:combineHeaders(this.config.headers(),e.headers),body:g,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:createJsonResponseHandler(OpenAICompatibleChatResponseSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),T=_.choices[0],R=[],x=T.message.content;x!=null&&x.length>0&&R.push({type:"text",text:x});const E=(t=T.message.reasoning_content)!=null?t:T.message.reasoning;if(E!=null&&E.length>0&&R.push({type:"reasoning",text:E}),T.message.tool_calls!=null)for(const U of T.message.tool_calls)R.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:generateId(),toolName:U.function.name,input:U.function.arguments});const A={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:$}))},D=(a=_.usage)==null?void 0:a.completion_tokens_details;return D?.accepted_prediction_tokens!=null&&(A[this.providerOptionsName].acceptedPredictionTokens=D?.accepted_prediction_tokens),D?.rejected_prediction_tokens!=null&&(A[this.providerOptionsName].rejectedPredictionTokens=D?.rejected_prediction_tokens),{content:R,finishReason:mapOpenAICompatibleFinishReason(T.finish_reason),usage:{inputTokens:(i=(s=_.usage)==null?void 0:s.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=_.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(d=(u=_.usage)==null?void 0:u.total_tokens)!=null?d:void 0,reasoningTokens:(h=(f=(p=_.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?h:void 0,cachedInputTokens:(w=(y=(b=_.usage)==null?void 0:b.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:A,request:{body:S},response:{...getResponseMetadata(_),headers:v,body:$},warnings:m}}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:s,value:i}=await postJsonToApi({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:combineHeaders(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler(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 d=!0;const p=this.providerOptionsName;let f=!1,h=!1;return{stream:i.pipeThrough(new TransformStream({start(b){b.enqueue({type:"stream-start",warnings:n})},transform(b,y){var w,g,m,S,v,_,$,T,R,x,E,A,D;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){c="error",y.enqueue({type:"error",error:b.error});return}const U=b.value;if(a?.processChunk(b.rawValue),"error"in U){c="error",y.enqueue({type:"error",error:U.error.message});return}if(d&&(d=!1,y.enqueue({type:"response-metadata",...getResponseMetadata(U)})),U.usage!=null){const{prompt_tokens:X,completion_tokens:ue,total_tokens:V,prompt_tokens_details:C,completion_tokens_details:N}=U.usage;u.promptTokens=X??void 0,u.completionTokens=ue??void 0,u.totalTokens=V??void 0,N?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=N?.reasoning_tokens),N?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=N?.accepted_prediction_tokens),N?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=N?.rejected_prediction_tokens),C?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=C?.cached_tokens)}const K=U.choices[0];if(K?.finish_reason!=null&&(c=mapOpenAICompatibleFinishReason(K.finish_reason)),K?.delta==null)return;const G=K.delta,te=(w=G.reasoning_content)!=null?w:G.reasoning;if(te&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:te})),G.content&&(h||(y.enqueue({type:"text-start",id:"txt-0"}),h=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:G.content})),G.tool_calls!=null)for(const X of G.tool_calls){const ue=X.index;if(l[ue]==null){if(X.id==null)throw new InvalidResponseDataError({data:X,message:"Expected 'id' to be a string."});if(((g=X.function)==null?void 0:g.name)==null)throw new InvalidResponseDataError({data:X,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),l[ue]={id:X.id,type:"function",function:{name:X.function.name,arguments:(m=X.function.arguments)!=null?m:""},hasFinished:!1};const C=l[ue];((S=C.function)==null?void 0:S.name)!=null&&((v=C.function)==null?void 0:v.arguments)!=null&&(C.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:C.id,delta:C.function.arguments}),isParsableJson(C.function.arguments)&&(y.enqueue({type:"tool-input-end",id:C.id}),y.enqueue({type:"tool-call",toolCallId:(_=C.id)!=null?_:generateId(),toolName:C.function.name,input:C.function.arguments}),C.hasFinished=!0));continue}const V=l[ue];V.hasFinished||((($=X.function)==null?void 0:$.arguments)!=null&&(V.function.arguments+=(R=(T=X.function)==null?void 0:T.arguments)!=null?R:""),y.enqueue({type:"tool-input-delta",id:V.id,delta:(x=X.function.arguments)!=null?x:""}),((E=V.function)==null?void 0:E.name)!=null&&((A=V.function)==null?void 0:A.arguments)!=null&&isParsableJson(V.function.arguments)&&(y.enqueue({type:"tool-input-end",id:V.id}),y.enqueue({type:"tool-call",toolCallId:(D=V.id)!=null?D:generateId(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(b){var y,w,g,m,S,v;f&&b.enqueue({type:"reasoning-end",id:"reasoning-0"}),h&&b.enqueue({type:"text-end",id:"txt-0"});for(const $ of l.filter(T=>!T.hasFinished))b.enqueue({type:"tool-input-end",id:$.id}),b.enqueue({type:"tool-call",toolCallId:(y=$.id)!=null?y:generateId(),toolName:$.function.name,input:$.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:(w=u.promptTokens)!=null?w:void 0,outputTokens:(g=u.completionTokens)!=null?g:void 0,totalTokens:(m=u.totalTokens)!=null?m:void 0,reasoningTokens:(S=u.completionTokensDetails.reasoningTokens)!=null?S:void 0,cachedInputTokens:(v=u.promptTokensDetails.cachedTokens)!=null?v:void 0},providerMetadata:_})}})),request:{body:o},response:{headers:s}}}},openaiCompatibleTokenUsageSchema=object$2({prompt_tokens:number$1().nullish(),completion_tokens:number$1().nullish(),total_tokens:number$1().nullish(),prompt_tokens_details:object$2({cached_tokens:number$1().nullish()}).nullish(),completion_tokens_details:object$2({reasoning_tokens:number$1().nullish(),accepted_prediction_tokens:number$1().nullish(),rejected_prediction_tokens:number$1().nullish()}).nullish()}).nullish(),OpenAICompatibleChatResponseSchema=object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({message:object$2({role:literal("assistant").nullish(),content:string().nullish(),reasoning_content:string().nullish(),reasoning:string().nullish(),tool_calls:array$1(object$2({id:string().nullish(),function:object$2({name:string(),arguments:string()})})).nullish()}),finish_reason:string().nullish()})),usage:openaiCompatibleTokenUsageSchema}),createOpenAICompatibleChatChunkSchema=e=>union([object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({delta:object$2({role:_enum(["assistant"]).nullish(),content:string().nullish(),reasoning_content:string().nullish(),reasoning:string().nullish(),tool_calls:array$1(object$2({index:number$1(),id:string().nullish(),function:object$2({name:string().nullish(),arguments:string().nullish()})})).nullish()}).nullish(),finish_reason:string().nullish()})),usage:openaiCompatibleTokenUsageSchema}),e]);object$2({echo:boolean().optional(),logitBias:record(string(),number$1()).optional(),suffix:string().optional(),user:string().optional()});var usageSchema=object$2({prompt_tokens:number$1(),completion_tokens:number$1(),total_tokens:number$1()});object$2({id:string().nullish(),created:number$1().nullish(),model:string().nullish(),choices:array$1(object$2({text:string(),finish_reason:string()})),usage:usageSchema.nullish()}),object$2({dimensions:number$1().optional(),user:string().optional()}),object$2({data:array$1(object$2({embedding:array$1(number$1())})),usage:object$2({prompt_tokens:number$1()}).nullish(),providerMetadata:record(string(),record(string(),any())).optional()}),object$2({data:array$1(object$2({b64_json:string()}))});var buildDeepseekMetadata=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}}},deepSeekMetadataExtractor={extractMetadata:async({parsedBody:e})=>{const t=await safeValidateTypes({value:e,schema:deepSeekResponseSchema});return!t.success||t.value.usage==null?void 0:buildDeepseekMetadata(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await safeValidateTypes({value:t,schema:deepSeekStreamChunkSchema});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:()=>buildDeepseekMetadata(e)}}},deepSeekUsageSchema=object$2({prompt_cache_hit_tokens:number$1().nullish(),prompt_cache_miss_tokens:number$1().nullish()}),deepSeekResponseSchema=object$2({usage:deepSeekUsageSchema.nullish()}),deepSeekStreamChunkSchema=object$2({choices:array$1(object$2({finish_reason:string().nullish()})).nullish(),usage:deepSeekUsageSchema.nullish()}),VERSION="1.0.30";function createDeepSeek(e={}){var t;const r=withoutTrailingSlash((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>withUserAgentSuffix({Authorization:`Bearer ${loadApiKey({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${VERSION}`);class o extends OpenAICompatibleChatLanguageModel{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=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:deepSeekMetadataExtractor}),s=i=>a(i);return s.languageModel=a,s.chat=a,s.textEmbeddingModel=i=>{throw new NoSuchModelError({modelId:i,modelType:"textEmbeddingModel"})},s.imageModel=i=>{throw new NoSuchModelError({modelId:i,modelType:"imageModel"})},s}createDeepSeek();const getAISDKTools=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:a}of r.tools){const s=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=dynamicTool({description:o,inputSchema:jsonSchema({...a,properties:a.properties??{},additionalProperties:!1}),execute:s})}return t}catch(r){throw r}},getBuiltinMcpTools=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 s of a){const{name:i,description:l}=s,c=s.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 d={type:"object",properties:u.properties??{},...u.required?{required:u.required}:{},additionalProperties:!1,...u};t[i]=dynamicTool({description:l??"",inputSchema:jsonSchema(d),async execute(p){if(!r.executeTool)throw new Error("navigator.modelContextTesting.executeTool is not available");return r.executeTool(i,JSON.stringify(p??{}))}})}return t};function generateReActToolsPrompt(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
605
|
-
# 工具调用
|
|
606
|
-
|
|
607
|
-
你可以根据需要调用以下工具:
|
|
608
|
-
|
|
609
|
-
<tools>
|
|
610
|
-
`;return t.forEach(([n,o])=>{const a=o,s=a.description||"无描述",i=a.parameters||a.inputSchema||{};r+=`${JSON.stringify({name:n,description:s,parameters:i},null,2)}
|
|
611
|
-
`}),r+=`
|
|
612
|
-
</tools>
|
|
613
|
-
|
|
614
|
-
## 工具调用格式
|
|
615
|
-
|
|
616
|
-
要调用工具,请使用以下 XML 格式:
|
|
617
|
-
Thought: [你的思考过程]
|
|
618
|
-
<tool_call>
|
|
619
|
-
{"name": "toolName", "arguments": {"arg1": "value1"}}
|
|
620
|
-
</tool_call>
|
|
621
|
-
|
|
622
|
-
工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
|
|
623
|
-
|
|
624
|
-
## 使用示例
|
|
625
|
-
|
|
626
|
-
如果用户要求"获取今天的日期",你可以这样调用工具:
|
|
627
|
-
Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
|
|
628
|
-
<tool_call>{"name": "get-today", "arguments": {}}</tool_call>
|
|
629
|
-
|
|
630
|
-
然后等待工具返回结果(Observation),再根据结果给出最终答案。
|
|
631
|
-
|
|
632
|
-
## 任务完成
|
|
633
|
-
|
|
634
|
-
当任务完成或无法继续时,直接给出最终答案即可。
|
|
635
|
-
|
|
636
|
-
**重要提示**:
|
|
637
|
-
- 必须严格按照 XML 格式调用工具
|
|
638
|
-
- arguments 必须是有效的 JSON 格式
|
|
639
|
-
- 如果不需要调用工具,直接给出最终答案即可
|
|
640
|
-
`,r}function parseReActAction(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,s=o.arguments||o.args||o.input||{};if(a&&t[a])return{toolName:a,arguments:s}}catch{}return null}const AIProviderFactories={openai:createOpenAI,deepseek:createDeepSeek};class AgentModelProvider{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=AIProviderFactories[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:()=>getBuiltinMcpTools(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,a=o.headers?{headers:o.headers}:void 0;r=new StreamableHTTPClientTransport(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 SSEClientTransport(new URL(o.url),{requestInit:a})}else"type"in t&&t.type==="extension"?r=new ExtensionClientTransport(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await createMCPClient({transport:r});return o.__transport__=r,o}else{const o=new WebMcpClient({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 InMemoryTransport||r&&r instanceof MessageChannelTransport)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 getAISDKTools(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=generateReActToolsPrompt(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
641
|
-
${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const a=o,s=a.execute||a.call;return typeof s!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await s(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 i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(a,l,o.system)},d=i[0]?.role==="system"?i:[u,...i];return t===streamText?this._chatReActStream(d,a,l,n,o):this._chatReActNonStream(d,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 s=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(a<n)s.unshift(l),a++;else{const u=this._removeImageFromMessage(l);u&&s.unshift(u)}else s.unshift(l)}return o.push(...s),o}async _chatReActNonStream(t,r,n,o,a){let s=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=a.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:f,...h}=a,y=(await generateText({model:this.llm(n),messages:p,...h})).text,w={role:"assistant",content:y};l.push(w),s.push(w);const g=parseReActAction(y,r);if(!g)return this.responseMessages=s,{text:y,response:{messages:s}};const m=await this._executeReActToolCall(g.toolName,g.arguments,r),_={role:"user",content:`<tool_response>
|
|
642
|
-
${m.success?JSON.stringify(m.result):`工具执行失败 - ${m.error}`}
|
|
643
|
-
</tool_response>`};l.push(_),s.push(_)}return this.responseMessages=s,{text:s[s.length-2]?.content||"",response:{messages:s}}}_chatReActStream(t,r,n,o,a){const s=this,i=this.llm(n);let l,c;const u=new Promise((p,f)=>{l=p,c=f});return{fullStream:new ReadableStream({async start(p){let f=[...t];const h=t[0]?.role==="system"?t[0]:null,b=h?t.slice(1):[...t];let y=0,w="";const g=a.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const m=s._buildMessagesForModel(h,b,g),{tools:S,...v}=a;delete v.system,delete v.onFinish;const _=await streamText({...v,model:i,messages:m});let $="";for await(const G of _.fullStream)G.type==="text-delta"?($+=G.text||"",p.enqueue({type:"text-delta",text:G.text})):G.type==="text-start"?p.enqueue({type:"text-start"}):G.type==="text-end"||G.type==="finish-step"||G.type==="finish"||G.type==="start"||G.type==="start-step"||p.enqueue(G);w+=$;const T={role:"assistant",content:w};b.push(T),f.push(T);const R=parseReActAction(w,r);if(!R){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),s.responseMessages=f,l({messages:f});return}if(R.toolName==="computer"&&R.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),s.responseMessages=f,l({messages:f});return}const x=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:x,toolName:R.toolName});const E=JSON.stringify(R.arguments,null,2);p.enqueue({type:"tool-input-delta",id:x,delta:E}),p.enqueue({type:"tool-input-end",id:x}),p.enqueue({type:"tool-call",toolCallId:x,toolName:R.toolName,input:R.arguments});const A=await s._executeReActToolCall(R.toolName,R.arguments,r);let D,U=A.result;if(A.success&&A.result&&typeof A.result=="object"&&A.result.screenshot){D=A.result.screenshot;const{screenshot:G,...te}=A.result;U=te}let K="";if(A.success){U&&Array.isArray(U.content)&&U.content.length>0&&U.content[0].text?K=U.content[0].text:K=JSON.stringify(U);let G=`<tool_response>
|
|
644
|
-
${K}
|
|
645
|
-
</tool_response>`;D&&(G+=`
|
|
646
|
-
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:x,result:G});const te=D?{role:"user",content:[{type:"text",text:G},{type:"image",image:D}]}:{role:"user",content:G};b.push(te),f.push(te),w=""}else K=`工具执行失败 - ${A.error}`,p.enqueue({type:"tool-error",toolCallId:x,input:R.arguments,error:{message:K}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),s.responseMessages=f,l({messages:f})}catch(m){p.error(m),c(m)}}}),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||{},s=this._tempMergeTools(a,!1),i=()=>{const f=this._tempMergeTools(a,!1);Object.entries(f).forEach(([h,b])=>{s[h]=b}),Object.keys(s).forEach(h=>{h in f||delete s[h]})},l=o.prepareStep,c=async f=>{i();const h=this._getActiveToolNames(s),b=typeof l=="function"?await l(f):void 0,y=b&&typeof b=="object"?b:{};return{...y,activeTools:Array.isArray(y.activeTools)?y.activeTools.filter(w=>h.includes(w)):h}},u={model:this.llm(r),stopWhen:stepCountIs(n),...o,tools:s,prepareStep:c,activeTools:this._getActiveToolNames(s)};let d=null;if(o.message&&!o.messages)d={role:"user",content:o.message},this.responseMessages.push(d),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const f=o.messages[o.messages.length-1];f.role==="user"&&(d=f)}const p=t(u);return p?.response?.then(f=>{const h=f.messages?.[0];d&&h?.role!=="user"&&this.responseMessages.push(d),this.responseMessages.push(...f.messages)}),p}async chat(t){return this._chat(generateText,t)}async chatStream(t){return this._chat(streamText,t)}}const isBrowser=()=>typeof window<"u"&&typeof navigator<"u",isDomAvailable=()=>isBrowser()&&typeof document<"u";let overlayElement=null,labelElement=null,styleElement=null,activeCount=0;const BODY_GLOW_CLASS="next-sdk-tool-body-glow";function ensureDomReady(){return isDomAvailable()}function ensureStyleElement(){if(!ensureDomReady()||styleElement)return;const e=document.createElement("style");e.textContent=`
|
|
647
|
-
.${BODY_GLOW_CLASS} {
|
|
648
|
-
position: relative;
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
.next-sdk-tool-overlay {
|
|
652
|
-
position: fixed;
|
|
653
|
-
inset: 0;
|
|
654
|
-
z-index: 999999;
|
|
655
|
-
pointer-events: none;
|
|
656
|
-
display: flex;
|
|
657
|
-
align-items: flex-end;
|
|
658
|
-
justify-content: flex-start;
|
|
659
|
-
padding: 0 0 18px 18px;
|
|
660
|
-
background: transparent;
|
|
661
|
-
animation: next-sdk-overlay-fade-in 260ms ease-out;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
.next-sdk-tool-overlay--exit {
|
|
665
|
-
animation: next-sdk-overlay-fade-out 220ms ease-in forwards;
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
.next-sdk-tool-overlay__glow-ring {
|
|
669
|
-
display: none;
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
.next-sdk-tool-overlay__panel {
|
|
673
|
-
position: relative;
|
|
674
|
-
min-width: min(320px, 78vw);
|
|
675
|
-
max-width: min(420px, 82vw);
|
|
676
|
-
padding: 10px 14px;
|
|
677
|
-
border-radius: 999px;
|
|
678
|
-
background:
|
|
679
|
-
linear-gradient(135deg, rgba(15, 23, 42, 0.9), rgba(17, 24, 39, 0.9)),
|
|
680
|
-
radial-gradient(circle at top left, rgba(96, 165, 250, 0.25), transparent 55%),
|
|
681
|
-
radial-gradient(circle at bottom right, rgba(45, 212, 191, 0.22), transparent 60%);
|
|
682
|
-
box-shadow:
|
|
683
|
-
0 12px 28px rgba(15, 23, 42, 0.78),
|
|
684
|
-
0 0 0 1px rgba(148, 163, 184, 0.26);
|
|
685
|
-
display: flex;
|
|
686
|
-
align-items: center;
|
|
687
|
-
gap: 10px;
|
|
688
|
-
pointer-events: none;
|
|
689
|
-
transform-origin: center;
|
|
690
|
-
animation: next-sdk-panel-pop-in 260ms cubic-bezier(0.18, 0.89, 0.32, 1.28);
|
|
691
|
-
color: #e5e7eb;
|
|
692
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif;
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
.next-sdk-tool-overlay__indicator {
|
|
696
|
-
width: 26px;
|
|
697
|
-
height: 26px;
|
|
698
|
-
border-radius: 999px;
|
|
699
|
-
background: radial-gradient(circle at 30% 10%, #f9fafb, #93c5fd);
|
|
700
|
-
box-shadow:
|
|
701
|
-
0 0 0 1px rgba(191, 219, 254, 0.6),
|
|
702
|
-
0 8px 18px rgba(37, 99, 235, 0.8),
|
|
703
|
-
0 0 28px rgba(56, 189, 248, 0.9);
|
|
704
|
-
position: relative;
|
|
705
|
-
flex-shrink: 0;
|
|
706
|
-
display: flex;
|
|
707
|
-
align-items: center;
|
|
708
|
-
justify-content: center;
|
|
709
|
-
overflow: hidden;
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
.next-sdk-tool-overlay__indicator-orbit {
|
|
713
|
-
position: absolute;
|
|
714
|
-
inset: 2px;
|
|
715
|
-
border-radius: inherit;
|
|
716
|
-
border: 1px solid rgba(248, 250, 252, 0.6);
|
|
717
|
-
box-sizing: border-box;
|
|
718
|
-
opacity: 0.9;
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
.next-sdk-tool-overlay__indicator-orbit::before {
|
|
722
|
-
content: '';
|
|
723
|
-
position: absolute;
|
|
724
|
-
width: 6px;
|
|
725
|
-
height: 6px;
|
|
726
|
-
border-radius: 999px;
|
|
727
|
-
background: #f9fafb;
|
|
728
|
-
box-shadow:
|
|
729
|
-
0 0 12px rgba(248, 250, 252, 0.9),
|
|
730
|
-
0 0 24px rgba(250, 249, 246, 0.9);
|
|
731
|
-
top: 0;
|
|
732
|
-
left: 50%;
|
|
733
|
-
transform: translate(-50%, -50%);
|
|
734
|
-
transform-origin: 50% 18px;
|
|
735
|
-
animation: next-sdk-indicator-orbit 1.4s linear infinite;
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
.next-sdk-tool-overlay__indicator-core {
|
|
739
|
-
width: 14px;
|
|
740
|
-
height: 14px;
|
|
741
|
-
border-radius: inherit;
|
|
742
|
-
background: radial-gradient(circle at 30% 20%, #f9fafb, #bfdbfe);
|
|
743
|
-
box-shadow:
|
|
744
|
-
0 0 12px rgba(248, 250, 252, 0.9),
|
|
745
|
-
0 0 32px rgba(191, 219, 254, 0.8);
|
|
746
|
-
opacity: 0.96;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
.next-sdk-tool-overlay__content {
|
|
750
|
-
display: flex;
|
|
751
|
-
flex-direction: column;
|
|
752
|
-
gap: 1px;
|
|
753
|
-
min-width: 0;
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
.next-sdk-tool-overlay__title {
|
|
757
|
-
font-size: 11px;
|
|
758
|
-
letter-spacing: 0.08em;
|
|
759
|
-
text-transform: uppercase;
|
|
760
|
-
color: rgba(156, 163, 175, 0.96);
|
|
761
|
-
display: flex;
|
|
762
|
-
align-items: center;
|
|
763
|
-
gap: 6px;
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
.next-sdk-tool-overlay__title-dot {
|
|
767
|
-
width: 6px;
|
|
768
|
-
height: 6px;
|
|
769
|
-
border-radius: 999px;
|
|
770
|
-
background: #22c55e;
|
|
771
|
-
box-shadow:
|
|
772
|
-
0 0 8px rgba(34, 197, 94, 0.9),
|
|
773
|
-
0 0 14px rgba(22, 163, 74, 0.9);
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
.next-sdk-tool-overlay__label {
|
|
777
|
-
font-size: 12px;
|
|
778
|
-
font-weight: 500;
|
|
779
|
-
color: #e5e7eb;
|
|
780
|
-
white-space: nowrap;
|
|
781
|
-
text-overflow: ellipsis;
|
|
782
|
-
overflow: hidden;
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
@keyframes next-sdk-overlay-fade-in {
|
|
786
|
-
from { opacity: 0; }
|
|
787
|
-
to { opacity: 1; }
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
@keyframes next-sdk-overlay-fade-out {
|
|
791
|
-
from { opacity: 1; }
|
|
792
|
-
to { opacity: 0; }
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
@keyframes next-sdk-indicator-orbit {
|
|
796
|
-
from {
|
|
797
|
-
transform: translate(-50%, -50%) rotate(0deg) translateY(0);
|
|
798
|
-
}
|
|
799
|
-
to {
|
|
800
|
-
transform: translate(-50%, -50%) rotate(360deg) translateY(0);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
@keyframes next-sdk-panel-pop-in {
|
|
805
|
-
0% {
|
|
806
|
-
opacity: 0;
|
|
807
|
-
transform: scale(0.92) translateY(10px);
|
|
808
|
-
}
|
|
809
|
-
100% {
|
|
810
|
-
opacity: 1;
|
|
811
|
-
transform: scale(1) translateY(0);
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
`,document.head.appendChild(e),styleElement=e}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const e=document.createElement("div");e.className="next-sdk-tool-overlay";const t=document.createElement("div");t.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-orbit";const a=document.createElement("div");a.className="next-sdk-tool-overlay__indicator-core";const s=document.createElement("div");s.className="next-sdk-tool-overlay__content";const i=document.createElement("div");i.className="next-sdk-tool-overlay__title",i.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",i.prepend(l),s.appendChild(i),s.appendChild(c),n.appendChild(o),n.appendChild(a),r.appendChild(n),r.appendChild(s),e.appendChild(t),e.appendChild(r),document.body.appendChild(e),overlayElement=e,labelElement=c}function updateOverlay(e){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=e.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const e=overlayElement;let t=!1,r;const n=()=>{t||(t=!0,r!==void 0&&(clearTimeout(r),r=void 0),e.parentNode&&e.parentNode.removeChild(e),overlayElement===e&&(overlayElement=null,labelElement=null),e.removeEventListener("animationend",n))};e.addEventListener("animationend",n),r=setTimeout(n,500)}function showToolInvokeEffect(e){ensureDomReady()&&(activeCount+=1,updateOverlay(e))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(e,t,r){if(!r)return;const n=t||e;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const MSG_TOOL_CALL="next-sdk:tool-call",MSG_TOOL_RESPONSE="next-sdk:tool-response",MSG_TOOL_REGISTERED="next-sdk:tool-registered",MSG_TOOL_UNREGISTERED="next-sdk:tool-unregistered",MSG_REMOTER_READY="next-sdk:remoter-ready",activePages=new Map,normalizeRoute=e=>e.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(e){if(!isBrowser())return;const t={type:e};broadcastTargets.forEach(({win:r,origin:n})=>{try{r.postMessage(t,n)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",e=>{if(e.data?.type!==MSG_REMOTER_READY||!e.source||e.origin!==window.location.origin)return;const t=e.source;broadcastTargets.add({win:t,origin:e.origin||"*"})})}setupIframeRemoterBridge();function notifyServerToolListChanged(e){if(!e)return;const t=e;try{typeof t.sendToolListChanged=="function"?t.sendToolListChanged():t.server&&typeof t.server.sendToolListChanged=="function"&&t.server.sendToolListChanged()}catch{}}function isToolReadyOnRoute(e,t){const r=activePages.get(e);return!!r&&r.has(t)}let _navigator=null;function setNavigator(e){_navigator=e}function isCurrentPathMatched(e){if(!isBrowser())return!1;const t=normalizeRoute(e);return normalizeRoute(window.location.pathname)===t}function waitForNavigationReady(e){return isBrowser()?new Promise(t=>{let r=!1;const n=()=>{r||(r=!0,window.removeEventListener("message",o),t())},o=a=>{a.source===window&&a.data?.type===MSG_TOOL_REGISTERED&&n()};window.addEventListener("message",o),setTimeout(n,e)}):Promise.resolve()}function registerNavigateTool(e,t){const r=t?.name??"navigate_to_page",n=t?.title??"页面跳转",o=t?.description??'当需要的工具在当前页面不可用时,使用此工具跳转到特定页面。例如:要查询订单时跳转到 "/orders",要创建价保时跳转到 "/price-protection"。',a=t?.timeoutMs??5e3,s={type:"object",properties:{path:{type:"string",description:'目标页面的路由地址,例如 "/orders"、"/inventory"、"/price-protection" 等。'}},required:["path"]},i=async({path:l})=>{if(!isBrowser())return{content:[{type:"text",text:"当前环境不支持页面跳转(window 不存在)。"}]};if(!_navigator)return{content:[{type:"text",text:"页面跳转失败:尚未在应用入口调用 setNavigator 注册导航函数,无法执行路由跳转。"}]};try{if(isCurrentPathMatched(l))return{content:[{type:"text",text:`当前已在页面:${l}。请继续你的下一步操作。`}]};const c=waitForNavigationReady(a);return await _navigator(l)!==!0&&(await c,await new Promise(d=>setTimeout(d,500))),{content:[{type:"text",text:`已成功跳转至页面:${l}。请继续你的下一步操作。`}]}}catch(c){return{content:[{type:"text",text:`页面跳转失败:${c instanceof Error?c.message:String(c)}。`}]}}};if(e&&typeof e.registerTool=="function")return e.__isNextSdkBridgeSetup?e.registerTool({name:r,title:n,description:o,inputSchema:s,execute:i}):e.registerTool(r,{title:n,description:o,inputSchema:s},i);throw new Error("Failed to register navigate tool: invalid server instance.")}function buildPageHandler(e,t,r=3e4,n){return o=>{const a=randomUUID();return new Promise((s,i)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",d),c&&window.removeEventListener("message",c),n&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),i(new Error(`工具 [${e}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const d=y=>{y.source===window&&y.data?.type===MSG_TOOL_RESPONSE&&y.data.callId===a&&(u(),y.data.error?i(new Error(y.data.error)):s(y.data.result))};window.addEventListener("message",d);const p=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:a,toolName:e,route:t,input:o},window.location.origin||"*")};let f=!1;const h=()=>{f||(f=!0,p())};(async()=>{try{if(n&&showToolInvokeEffect(n),isToolReadyOnRoute(t,e)){h();return}if(c=y=>{y.source!==window||y.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",c),h())},window.addEventListener("message",c),_navigator&&await _navigator(t)===!0){c&&window.removeEventListener("message",c),h();return}isToolReadyOnRoute(t,e)&&(window.removeEventListener("message",c),h())}catch(y){u(),i(y instanceof Error?y:new Error(String(y)))}})()})}}function withPageTools(e){const t=new Map,r=(n,o,a=!1)=>{const s=t.get(o),i=!!s;if(t.delete(o),s)try{s.remove()}catch{}return!a&&i&&(notifyServerToolListChanged(n),broadcastToolChange(MSG_TOOL_UNREGISTERED)),!!s};return new Proxy(e,{get(n,o,a){return o==="unregisterTool"?s=>r(n,s,!1):o==="registerTool"?(s,i,l)=>{r(n,s,!0);const c=n.registerTool.bind(n);if(typeof l=="function"){const w=c(s,i,l);return t.set(s,w),notifyServerToolListChanged(n),broadcastToolChange(MSG_TOOL_REGISTERED),w}const{route:u,timeout:d,invokeEffect:p}=l,f=normalizeRoute(u),h=resolveRuntimeEffectConfig(s,i?.title,p),b=buildPageHandler(s,f,d,h),y=c(s,i,b);return t.set(s,y),notifyServerToolListChanged(n),broadcastToolChange(MSG_TOOL_REGISTERED),y}:Reflect.get(n,o,a)}})}function registerPageTool(e){const{route:t,handlers:r}=e,n=normalizeRoute(t??window.location.pathname),o=Object.keys(r),a=async s=>{if(s.source!==window||s.data?.type!==MSG_TOOL_CALL||!(s.data.toolName in r))return;const{callId:i,toolName:l,input:c}=s.data;try{const u=r[l];if(!u)throw new Error(`Tool "${l}" handler not found.`);const d=await u(c);window.postMessage({type:MSG_TOOL_RESPONSE,callId:i,result:d},window.location.origin||"*")}catch(u){window.postMessage({type:MSG_TOOL_RESPONSE,callId:i,error:u instanceof Error?u.message:String(u)},window.location.origin||"*")}};return activePages.set(n,new Set(o)),window.addEventListener("message",a),broadcastToolChange(MSG_TOOL_REGISTERED),()=>{activePages.delete(n),window.removeEventListener("message",a),broadcastToolChange(MSG_TOOL_UNREGISTERED)}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const t=document.modelContext;if(!t||t.__isNextSdkBridgeSetup)return;isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const r=t.registerTool?.bind(t),n=t.unregisterTool?.bind(t);typeof r=="function"&&(t.registerTool=(o,a)=>{const s=o.name,i={...o};a?.signal&&a.signal.addEventListener("abort",()=>{_registeredTools.delete(s),broadcastToolChange(MSG_TOOL_UNREGISTERED)});const l=i.routeConfig&&typeof i.routeConfig=="object"&&"route"in i.routeConfig?i.routeConfig:null;if(l){const c=normalizeRoute(l.route),u=resolveRuntimeEffectConfig(s,i.title,l.invokeEffect),d=buildPageHandler(s,c,l.timeout,u);i.execute=d,delete i.routeConfig}_registeredTools.set(s,{name:s,title:o.title,description:o.description,inputSchema:o.inputSchema});try{r(i,a),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(s)}}),t.unregisterTool=o=>{try{typeof n=="function"&&n(o)}catch{}finally{_registeredTools.delete(o),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},t.__isNextSdkBridgeSetup=!0}const MAIN_SKILL_PATH_REG=/^\.\/[^/]+\/SKILL\.md$/,FRONT_MATTER_BLOCK_REG=/^---\s*\n([\s\S]+?)\s*\n---/;async function parseSkillFrontMatter(e){if(typeof e!="string"&&typeof e!="function")return null;const r=(typeof e=="string"?e:await e()).match(FRONT_MATTER_BLOCK_REG);if(!r?.[1])return null;const n=r[1],o=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m),s=o?.[1]?.trim(),i=a?.[1]?.trim();return s&&i?{name:s,description:i}:null}async function normalizeSkillModuleKeys(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.replace(/\\/g,"/"),a=o.lastIndexOf("skills/"),s=a>=0?o.slice(a+7):o,i=s.startsWith("./")?s:`./${s}`,l=typeof n=="string"?n:await n();t[i]=l}return t}async function getMainSkillPaths(e){const t=await normalizeSkillModuleKeys(e);return Object.keys(t).filter(r=>MAIN_SKILL_PATH_REG.test(r))}async function getSkillOverviews(e){const t=await normalizeSkillModuleKeys(e),r=Object.keys(t).filter(o=>MAIN_SKILL_PATH_REG.test(o)),n=[];for(const o of r){const a=t[o];if(!a)continue;const s=await parseSkillFrontMatter(a);s&&n.push({name:s.name,description:s.description,path:o})}return n}function formatSkillsForSystemPrompt(e){return e.length===0?"":`## 可用技能
|
|
815
|
-
|
|
816
|
-
${e.map(r=>`- **${r.name}**: ${r.description}`).join(`
|
|
817
|
-
`)}
|
|
818
|
-
|
|
819
|
-
当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}async function getSkillMdContent(e,t){const r=await normalizeSkillModuleKeys(e),n=r[t];if(n)return n;const o=t.replace(/^\.?\//,"/"),a=Object.keys(r).find(s=>s.endsWith(o));return a?r[a]:void 0}async function getMainSkillPathByName(e,t){const r=await normalizeSkillModuleKeys(e),n=await getMainSkillPaths(r),o=n.find(a=>a.startsWith(`./${t}/SKILL.md`));if(o)return o;for(const a of n){const s=r[a];if(s){const i=await parseSkillFrontMatter(s);if(i&&i.name===t)return a}}}const SKILL_INPUT_SCHEMA=objectType({skillName:stringType().optional().describe('进入某个技能的主入口名称。优先匹配技能的目录名(如 ecommerce),或者技能的中文名称(如"客户价保单创建及审核")。'),path:stringType().optional().describe("你想查阅的文档的路径。如 ./calculator/SKILL.md 或从其他文档里看到的相对路径 ./reference/inventory.md。"),currentPath:stringType().optional().describe("你当前正在阅读的文档路径(如果有)。比如你刚刚读取了 ./ecommerce/SKILL.md,请把这个路径原样传回来,这样系统才能根据你的相对路径准确找到下一份文件。")});function createSkillTools(e){let t=!1,r;return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整文档内容。如果你想根据相对路径查阅文件,请务必同时提供你当前所在的文件路径 currentPath。",inputSchema:SKILL_INPUT_SCHEMA,execute:async o=>{t||(r=await normalizeSkillModuleKeys(e),t=!0);const a=r,{skillName:s,path:i,currentPath:l}=o;let c,u="";if(i){let d=".";if(l){const h=l.lastIndexOf("/");h>=0&&(d=l.slice(0,h))}const p=`http://localhost/${d}/`;if(u="."+new URL(i,p).pathname,c=await getSkillMdContent(a,u),c===void 0&&(i.startsWith("./")||i.startsWith("../"))&&l){const h=l.split("/");if(h.length>=2){const y=`http://localhost/${h[1]}/`,g="."+new URL(i,y).pathname;c=await getSkillMdContent(a,g),c&&(u=g)}}if(c&&!a[u]){const h=u.replace(/^\.?\//,"/"),b=Object.keys(a).find(y=>y.endsWith(h));b&&(u=b)}}else if(s){const d=await getMainSkillPathByName(a,s);d&&(u=d,c=await getSkillMdContent(a,d))}return c===void 0?{error:"未找到对应技能文档",skillName:s,path:i,providedCurrentPath:l,attemptedPath:u}:{content:c,path:u}}}}}function deepCompareStrict(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let o=0;o<n;o++)if(!deepCompareStrict(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(const s of n)if(!deepCompareStrict(e[s],t[s]))return!1;return!0}return e===t}function encodePointer(e){return encodeURI(escapePointer(e))}function escapePointer(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const schemaArrayKeyword={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},schemaMapKeyword={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ignoredKeyword={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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};let initialBaseURI=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function dereference(e,t=Object.create(null),r=initialBaseURI,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const a=e.$id||e.id;if(a){const s=new URL(a,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:dereference(e,t,r))}}else if(e!==!0&&e!==!1)return t;const o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){const a=new URL(e.$ref,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const a=new URL(e.$recursiveRef,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){const a=new URL("#"+e.$anchor,r.href);t[a.href]=e}for(let a in e){if(ignoredKeyword[a])continue;const s=`${n}/${encodePointer(a)}`,i=e[a];if(Array.isArray(i)){if(schemaArrayKeyword[a]){const l=i.length;for(let c=0;c<l;c++)dereference(i[c],t,r,`${s}/${c}`)}}else if(schemaMapKeyword[a])for(let l in i)dereference(i[l],t,r,`${s}/${encodePointer(l)}`);else dereference(i,t,r,s)}return t}const DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/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,URIREF=/^(?:[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,URITEMPLATE=/^(?:(?:[^\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(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,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)*)*)$/,EMAIL=e=>{if(e[0]==='"')return!1;const[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},IPV4=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\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,DURATION=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function bind(e){return e.test.bind(e)}const format={date,time:time.bind(void 0,!1),"date-time":date_time,duration:DURATION,uri,"uri-reference":bind(URIREF),"uri-template":bind(URITEMPLATE),url:bind(URL_),email:EMAIL,hostname:bind(HOSTNAME),ipv4:bind(IPV4),ipv6:bind(IPV6),regex,uuid:bind(UUID),"json-pointer":bind(JSON_POINTER),"json-pointer-uri-fragment":bind(JSON_POINTER_URI_FRAGMENT),"relative-json-pointer":bind(RELATIVE_JSON_POINTER)};function isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}function date(e){const t=e.match(DATE);if(!t)return!1;const r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&isLeapYear(r)?29:DAYS[n])}function time(e,t){const r=t.match(TIME);if(!r)return!1;const n=+r[1],o=+r[2],a=+r[3],s=!!r[5];return(n<=23&&o<=59&&a<=59||n==23&&o==59&&a==60)&&(!e||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(e){const t=e.split(DATE_TIME_SEPARATOR);return t.length==2&&date(t[0])&&time(!0,t[1])}const NOT_URI_FRAGMENT=/\/|:/,URI_PATTERN=/^(?:[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 uri(e){return NOT_URI_FRAGMENT.test(e)&&URI_PATTERN.test(e)}const Z_ANCHOR=/[^\\]\\Z/;function regex(e){if(Z_ANCHOR.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function ucs2length(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}function validate(e,t,r="2019-09",n=dereference(t),o=!0,a=null,s="#",i="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const c=typeof e;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:d,$recursiveRef:p,$recursiveAnchor:f,type:h,const:b,enum:y,required:w,not:g,anyOf:m,allOf:S,oneOf:v,if:_,then:$,else:T,format:R,properties:x,patternProperties:E,additionalProperties:A,unevaluatedProperties:D,minProperties:U,maxProperties:K,propertyNames:G,dependentRequired:te,dependentSchemas:X,dependencies:ue,prefixItems:V,items:C,additionalItems:N,unevaluatedItems:L,contains:I,minContains:k,maxContains:O,minItems:q,maxItems:B,uniqueItems:F,minimum:j,maximum:M,exclusiveMinimum:Z,exclusiveMaximum:H,multipleOf:J,minLength:oe,maxLength:se,pattern:_e,__absolute_ref__:Te,__absolute_recursive_ref__:Se}=t,Q=[];if(f===!0&&a===null&&(a=t),p==="#"){const de=a===null?n[Se]:a,ne=`${i}/$recursiveRef`,ae=validate(e,a===null?t:a,r,n,o,de,s,ne,l);ae.valid||Q.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:ne,error:"A subschema had errors."},...ae.errors)}if(d!==void 0){const ne=n[Te||d];if(ne===void 0){let Y=`Unresolved $ref "${d}".`;throw Te&&Te!==d&&(Y+=` Absolute URI "${Te}".`),Y+=`
|
|
820
|
-
Known schemas:
|
|
821
|
-
- ${Object.keys(n).join(`
|
|
822
|
-
- `)}`,new Error(Y)}const ae=`${i}/$ref`,ee=validate(e,ne,r,n,o,a,s,ae,l);if(ee.valid||Q.push({instanceLocation:s,keyword:"$ref",keywordLocation:ae,error:"A subschema had errors."},...ee.errors),r==="4"||r==="7")return{valid:Q.length===0,errors:Q}}if(Array.isArray(h)){let de=h.length,ne=!1;for(let ae=0;ae<de;ae++)if(u===h[ae]||h[ae]==="integer"&&u==="number"&&e%1===0&&e===e){ne=!0;break}ne||Q.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(u!=="number"||e%1||e!==e)&&Q.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`}):h!==void 0&&u!==h&&Q.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`});if(b!==void 0&&(u==="object"||u==="array"?deepCompareStrict(e,b)||Q.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(b)}.`}):e!==b&&Q.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(b)}.`})),y!==void 0&&(u==="object"||u==="array"?y.some(de=>deepCompareStrict(e,de))||Q.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(de=>e===de)||Q.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),g!==void 0){const de=`${i}/not`;validate(e,g,r,n,o,a,s,de).valid&&Q.push({instanceLocation:s,keyword:"not",keywordLocation:de,error:'Instance matched "not" schema.'})}let ve=[];if(m!==void 0){const de=`${i}/anyOf`,ne=Q.length;let ae=!1;for(let ee=0;ee<m.length;ee++){const Y=m[ee],ce=Object.create(l),le=validate(e,Y,r,n,o,f===!0?a:null,s,`${de}/${ee}`,ce);Q.push(...le.errors),ae=ae||le.valid,le.valid&&ve.push(ce)}ae?Q.length=ne:Q.splice(ne,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:de,error:"Instance does not match any subschemas."})}if(S!==void 0){const de=`${i}/allOf`,ne=Q.length;let ae=!0;for(let ee=0;ee<S.length;ee++){const Y=S[ee],ce=Object.create(l),le=validate(e,Y,r,n,o,f===!0?a:null,s,`${de}/${ee}`,ce);Q.push(...le.errors),ae=ae&&le.valid,le.valid&&ve.push(ce)}ae?Q.length=ne:Q.splice(ne,0,{instanceLocation:s,keyword:"allOf",keywordLocation:de,error:"Instance does not match every subschema."})}if(v!==void 0){const de=`${i}/oneOf`,ne=Q.length,ae=v.filter((ee,Y)=>{const ce=Object.create(l),le=validate(e,ee,r,n,o,f===!0?a:null,s,`${de}/${Y}`,ce);return Q.push(...le.errors),le.valid&&ve.push(ce),le.valid}).length;ae===1?Q.length=ne:Q.splice(ne,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:de,error:`Instance does not match exactly one subschema (${ae} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...ve),_!==void 0){const de=`${i}/if`;if(validate(e,_,r,n,o,a,s,de,l).valid){if($!==void 0){const ae=validate(e,$,r,n,o,a,s,`${i}/then`,l);ae.valid||Q.push({instanceLocation:s,keyword:"if",keywordLocation:de,error:'Instance does not match "then" schema.'},...ae.errors)}}else if(T!==void 0){const ae=validate(e,T,r,n,o,a,s,`${i}/else`,l);ae.valid||Q.push({instanceLocation:s,keyword:"if",keywordLocation:de,error:'Instance does not match "else" schema.'},...ae.errors)}}if(u==="object"){if(w!==void 0)for(const ee of w)ee in e||Q.push({instanceLocation:s,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${ee}".`});const de=Object.keys(e);if(U!==void 0&&de.length<U&&Q.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${U} properties.`}),K!==void 0&&de.length>K&&Q.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${K} properties.`}),G!==void 0){const ee=`${i}/propertyNames`;for(const Y in e){const ce=`${s}/${encodePointer(Y)}`,le=validate(Y,G,r,n,o,a,ce,ee);le.valid||Q.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:ee,error:`Property name "${Y}" does not match schema.`},...le.errors)}}if(te!==void 0){const ee=`${i}/dependantRequired`;for(const Y in te)if(Y in e){const ce=te[Y];for(const le of ce)le in e||Q.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:ee,error:`Instance has "${Y}" but does not have "${le}".`})}}if(X!==void 0)for(const ee in X){const Y=`${i}/dependentSchemas`;if(ee in e){const ce=validate(e,X[ee],r,n,o,a,s,`${Y}/${encodePointer(ee)}`,l);ce.valid||Q.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:Y,error:`Instance has "${ee}" but does not match dependant schema.`},...ce.errors)}}if(ue!==void 0){const ee=`${i}/dependencies`;for(const Y in ue)if(Y in e){const ce=ue[Y];if(Array.isArray(ce))for(const le of ce)le in e||Q.push({instanceLocation:s,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${Y}" but does not have "${le}".`});else{const le=validate(e,ce,r,n,o,a,s,`${ee}/${encodePointer(Y)}`);le.valid||Q.push({instanceLocation:s,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${Y}" but does not match dependant schema.`},...le.errors)}}}const ne=Object.create(null);let ae=!1;if(x!==void 0){const ee=`${i}/properties`;for(const Y in x){if(!(Y in e))continue;const ce=`${s}/${encodePointer(Y)}`,le=validate(e[Y],x[Y],r,n,o,a,ce,`${ee}/${encodePointer(Y)}`);if(le.valid)l[Y]=ne[Y]=!0;else if(ae=o,Q.push({instanceLocation:s,keyword:"properties",keywordLocation:ee,error:`Property "${Y}" does not match schema.`},...le.errors),ae)break}}if(!ae&&E!==void 0){const ee=`${i}/patternProperties`;for(const Y in E){const ce=new RegExp(Y,"u"),le=E[Y];for(const P in e){if(!ce.test(P))continue;const W=`${s}/${encodePointer(P)}`,he=validate(e[P],le,r,n,o,a,W,`${ee}/${encodePointer(Y)}`);he.valid?l[P]=ne[P]=!0:(ae=o,Q.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:ee,error:`Property "${P}" matches pattern "${Y}" but does not match associated schema.`},...he.errors))}}}if(!ae&&A!==void 0){const ee=`${i}/additionalProperties`;for(const Y in e){if(ne[Y])continue;const ce=`${s}/${encodePointer(Y)}`,le=validate(e[Y],A,r,n,o,a,ce,ee);le.valid?l[Y]=!0:(ae=o,Q.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:ee,error:`Property "${Y}" does not match additional properties schema.`},...le.errors))}}else if(!ae&&D!==void 0){const ee=`${i}/unevaluatedProperties`;for(const Y in e)if(!l[Y]){const ce=`${s}/${encodePointer(Y)}`,le=validate(e[Y],D,r,n,o,a,ce,ee);le.valid?l[Y]=!0:Q.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:ee,error:`Property "${Y}" does not match unevaluated properties schema.`},...le.errors)}}}else if(u==="array"){B!==void 0&&e.length>B&&Q.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${B}).`}),q!==void 0&&e.length<q&&Q.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${q}).`});const de=e.length;let ne=0,ae=!1;if(V!==void 0){const ee=`${i}/prefixItems`,Y=Math.min(V.length,de);for(;ne<Y;ne++){const ce=validate(e[ne],V[ne],r,n,o,a,`${s}/${ne}`,`${ee}/${ne}`);if(l[ne]=!0,!ce.valid&&(ae=o,Q.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:ee,error:"Items did not match schema."},...ce.errors),ae))break}}if(C!==void 0){const ee=`${i}/items`;if(Array.isArray(C)){const Y=Math.min(C.length,de);for(;ne<Y;ne++){const ce=validate(e[ne],C[ne],r,n,o,a,`${s}/${ne}`,`${ee}/${ne}`);if(l[ne]=!0,!ce.valid&&(ae=o,Q.push({instanceLocation:s,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...ce.errors),ae))break}}else for(;ne<de;ne++){const Y=validate(e[ne],C,r,n,o,a,`${s}/${ne}`,ee);if(l[ne]=!0,!Y.valid&&(ae=o,Q.push({instanceLocation:s,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...Y.errors),ae))break}if(!ae&&N!==void 0){const Y=`${i}/additionalItems`;for(;ne<de;ne++){const ce=validate(e[ne],N,r,n,o,a,`${s}/${ne}`,Y);l[ne]=!0,ce.valid||(ae=o,Q.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:Y,error:"Items did not match additional items schema."},...ce.errors))}}}if(I!==void 0)if(de===0&&k===void 0)Q.push({instanceLocation:s,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(k!==void 0&&de<k)Q.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${de}) than minContains (${k}).`});else{const ee=`${i}/contains`,Y=Q.length;let ce=0;for(let le=0;le<de;le++){const P=validate(e[le],I,r,n,o,a,`${s}/${le}`,ee);P.valid?(l[le]=!0,ce++):Q.push(...P.errors)}ce>=(k||0)&&(Q.length=Y),k===void 0&&O===void 0&&ce===0?Q.splice(Y,0,{instanceLocation:s,keyword:"contains",keywordLocation:ee,error:"Array does not contain item matching schema."}):k!==void 0&&ce<k?Q.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${k} items matching schema. Only ${ce} items were found.`}):O!==void 0&&ce>O&&Q.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${O} items matching schema. ${ce} items were found.`})}if(!ae&&L!==void 0){const ee=`${i}/unevaluatedItems`;for(ne;ne<de;ne++){if(l[ne])continue;const Y=validate(e[ne],L,r,n,o,a,`${s}/${ne}`,ee);l[ne]=!0,Y.valid||Q.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:ee,error:"Items did not match unevaluated items schema."},...Y.errors)}}if(F)for(let ee=0;ee<de;ee++){const Y=e[ee],ce=typeof Y=="object"&&Y!==null;for(let le=0;le<de;le++){if(ee===le)continue;const P=e[le];(Y===P||ce&&(typeof P=="object"&&P!==null)&&deepCompareStrict(Y,P))&&(Q.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${ee} and ${le}.`}),ee=Number.MAX_SAFE_INTEGER,le=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(j!==void 0&&(Z===!0&&e<=j||e<j)&&Q.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${Z?"or equal to ":""} ${j}.`}),M!==void 0&&(H===!0&&e>=M||e>M)&&Q.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${H?"or equal to ":""} ${M}.`})):(j!==void 0&&e<j&&Q.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${j}.`}),M!==void 0&&e>M&&Q.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${M}.`}),Z!==void 0&&e<=Z&&Q.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${Z}.`}),H!==void 0&&e>=H&&Q.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${H}.`})),J!==void 0){const de=e%J;Math.abs(0-de)>=11920929e-14&&Math.abs(J-de)>=11920929e-14&&Q.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${J}.`})}}else if(u==="string"){const de=oe===void 0&&se===void 0?0:ucs2length(e);oe!==void 0&&de<oe&&Q.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${de} < ${oe}).`}),se!==void 0&&de>se&&Q.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${de} > ${se}).`}),_e!==void 0&&!new RegExp(_e,"u").test(e)&&Q.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),R!==void 0&&format[R]&&!format[R](e)&&Q.push({instanceLocation:s,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${R}".`})}return{valid:Q.length===0,errors:Q}}class Validator{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=dereference(t)}validate(t){return validate(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),dereference(t,this.lookup)}}const FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE="Failed to parse input arguments",TOOL_INVOCATION_FAILED_MESSAGE="Tool was executed but the invocation failed. For example, the script function threw an error",TOOL_CANCELLED_MESSAGE="Tool was cancelled",DEFAULT_INPUT_SCHEMA={type:"object",properties:{}},STANDARD_JSON_SCHEMA_TARGETS=["draft-2020-12","draft-07"],POLYFILL_MARKER_PROPERTY="__isWebMCPPolyfill",STANDARD_VALIDATOR_SYMBOL=Symbol("standardValidator"),installState={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var StrictWebMCPContext=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,t){const r=t?.signal;if(r?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const n=normalizeToolDescriptor(e,this.tools);this.tools.set(n.name,n),this.notifyToolsChanged(),r&&r.addEventListener("abort",()=>{this.tools.delete(n.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();const t=getToolNameForUnregister(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,t,r){return this.executeToolByName(e.name,t,r,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:"object"})}catch{t='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:t}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{const t=this.tools.get(e.name);return{...e,title:t?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(e,t,r){return this.executeToolByName(e,t,r,!0)}async executeToolByName(e,t,r,n){if(r?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const o=this.tools.get(e);if(!o)throw createUnknownError(`Tool not found: ${e}`);const a=parseInputArgsJson(t),s=await validateArgsForTool(a,o);if(s)throw createUnknownError(s);let i=!0;const l={requestUserInteraction:async c=>{if(!i)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof c!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return c()}};try{const c=o.execute(a,l),u=await withAbortSignal(Promise.resolve(c),r?.signal);if(n)return toSerializedTestingResult(normalizeToolResponse(u));const d=JSON.stringify(u);return d===void 0?null:d}catch(c){throw createUnknownError(c instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${c.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{i=!1}}notifyToolsChanged(){queueMicrotask(()=>{const e=new Event("toolchange");try{this._ontoolchange?.call(this,e)}catch(t){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",t)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister."))}},PolyfillTestingShim=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,r){return this.context.executeToolForTesting(e,t,r)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){const e=new Event("toolchange");try{this._ontoolchange?.call(this,e)}catch(t){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",t)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(e){try{return new DOMException(e,"UnknownError")}catch{const t=new Error(e);return t.name="UnknownError",t}}function parseInputArgsJson(e){let t;try{t=JSON.parse(e)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!t||typeof t!="object"||Array.isArray(t))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return t}function getToolNameForUnregister(e){if(typeof e=="string")return e;if(isPlainObject(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function isPlainObject(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function getStandardProps(e){if(!isPlainObject(e))return null;const t=e["~standard"];return isPlainObject(t)?t:null}function isStandardInputValidatorSchema(e){const t=getStandardProps(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function isStandardInputJsonSchema(e){const t=getStandardProps(e);return!t||t.version!==1||!isPlainObject(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!isPlainObject(t))return{issues:[{message:"expected object arguments"}]};const r=validateArgsWithSchema(t,e);return r?{issues:[r]}:{value:t}}}}}function convertStandardInputSchema(e){for(const t of STANDARD_JSON_SCHEMA_TARGETS)try{const r=e["~standard"].jsonSchema.input({target:t});return validateInputSchema(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(e){if(e===void 0){const r=DEFAULT_INPUT_SCHEMA;return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputJsonSchema(e)){const r=convertStandardInputSchema(e);return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputValidatorSchema(e))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:e};if(validateInputSchema(e),Object.keys(e).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:createStandardValidatorFromJsonSchema(t)}}function validateInputSchema(e){if(!isPlainObject(e))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(e,"$")}function validateJsonSchemaNode(e,t){const r=e.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);const n=e.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);const o=e.properties;if(o!==void 0){if(!isPlainObject(o))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(const[i,l]of Object.entries(o)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${t}.properties.${i}: expected object schema`);validateJsonSchemaNode(l,`${t}.properties.${i}`)}}const a=e.items;if(a!==void 0)if(Array.isArray(a))for(const[i,l]of a.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${t}.items[${i}]: expected object schema`);validateJsonSchemaNode(l,`${t}.items[${i}]`)}else if(isPlainObject(a))validateJsonSchemaNode(a,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(const i of["allOf","anyOf","oneOf"]){const l=e[i];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${t}: "${i}" must be an array`);for(const[c,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${t}.${i}[${c}]: expected object schema`);validateJsonSchemaNode(u,`${t}.${i}[${c}]`)}}}const s=e.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);validateJsonSchemaNode(s,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof e.description!="string"||e.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);const r=normalizeInputSchema(e.inputSchema),n=e.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...o?{annotations:o}:{},inputSchema:r.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:r.standardValidator}}function validateArgsWithSchema(e,t){const r=new Validator(t,"2020-12",!0).validate(e);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function formatStandardIssuePath(e){if(!e||e.length===0)return null;const t=e.map(r=>isPlainObject(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return t.length===0?null:t.join(".")}async function validateArgsWithStandardSchema(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(a){const s=a instanceof Error?`: ${a.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",a),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const o=formatStandardIssuePath(n?.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function validateArgsForTool(e,t){return validateArgsWithStandardSchema(e,t[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(e){return isPlainObject(e)&&Array.isArray(e.content)}function isJsonPrimitive(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function isJsonValue(e){return isJsonPrimitive(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>isJsonValue(t)):isPlainObject(e)?Object.values(e).every(t=>isJsonValue(t)):!1}function toStructuredContent(e){if(!(!isPlainObject(e)||!isJsonValue(e)))return e}function serializeTextContent(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function normalizeToolResponse(e){if(isCallToolResult(e))return e;const t=toStructuredContent(e);return{content:[{type:"text",text:serializeTextContent(e)}],...t?{structuredContent:t}:{},isError:!1}}function getFirstTextBlock(e){for(const t of e.content??[])if(t.type==="text"&&"text"in t&&typeof t.text=="string")return t.text;return null}function toSerializedTestingResult(e){if(e.isError)throw createUnknownError(getFirstTextBlock(e)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(e,t){return t?t.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((r,n)=>{const o=()=>{a(),n(createUnknownError(TOOL_CANCELLED_MESSAGE))},a=()=>{t.removeEventListener("abort",o)};t.addEventListener("abort",o,{once:!0}),e.then(s=>{a(),r(s)},s=>{a(),n(s)})}):e}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function defineDocumentModelContextProperty(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return navigatorModelContextDeprecationWarned||(navigatorModelContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function initializeWebMCPPolyfill(e){const t=getNavigator(),r=getDocument();if(!t&&!r||r?.modelContext)return;const o=t?.modelContext,a=!!o;if(installState.installed&&cleanupWebMCPPolyfill(),r&&o){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,o),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(a)return;const s=new StrictWebMCPContext,i=s;if(i[POLYFILL_MARKER_PROPERTY]=!0,r&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,i),installState.installedDocumentModelContext=!0),t){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(t,i),installState.installedNavigatorModelContext=!0;const l=e?.installTestingShim??"if-missing",c=!!t.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!c)&&(defineNavigatorProperty(t,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const e=(n,o,a)=>{if(a){Object.defineProperty(n,o,a);return}delete n[o]},t=getNavigator(),r=getDocument();r&&installState.installedDocumentModelContext&&e(r,"modelContext",installState.previousDocumentModelContextDescriptor),t&&installState.installedNavigatorModelContext&&e(t,"modelContext",installState.previousNavigatorModelContextDescriptor),t&&installState.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",installState.previousNavigatorModelContextTestingDescriptor),installState.installed=!1,installState.previousDocumentModelContextDescriptor=void 0,installState.previousNavigatorModelContextDescriptor=void 0,installState.previousNavigatorModelContextTestingDescriptor=void 0,installState.installedDocumentModelContext=!1,installState.installedNavigatorModelContext=!1,installState.installedNavigatorModelContextTesting=!1,navigatorModelContextDeprecationWarned=!1}if(typeof window<"u"&&typeof document<"u"){const e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{initializeWebMCPPolyfill(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(e){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",e)}},pageAgentPrompt=`## 角色
|
|
823
|
-
|
|
824
|
-
你是浏览器页面的操作工具,你拥有识别网页内容,点击,填写,选择下拉框和滚动页面等功能。
|
|
825
|
-
|
|
826
|
-
在执行页面操作之前,你必须先调用\`browserState\`工具一次,根据最新的网页状态,再调用操作动作,比如 'click','fill','select' 等动作。
|
|
827
|
-
|
|
828
|
-
<intro>
|
|
829
|
-
你擅长以下任务:
|
|
830
|
-
1. 导航复杂网站并提取精确信息
|
|
831
|
-
2. 自动化表单提交和交互式网页操作
|
|
832
|
-
3. 收集和保存信息
|
|
833
|
-
4. 在代理循环中有效运行
|
|
834
|
-
5. 高效执行多样化的网页任务
|
|
835
|
-
</intro>
|
|
836
|
-
|
|
837
|
-
<input>
|
|
838
|
-
在每一步,你的输入将包括:
|
|
839
|
-
1. <agent_history>:一个按时间顺序排列的事件流,包括你之前的操作及其结果。
|
|
840
|
-
2. <agent_state>:当前的 <user_request> 和 <step_info>。
|
|
841
|
-
3. <browser_state>:当前 URL、页面标题、可交互元素总数以及语义化 YAML 树。
|
|
842
|
-
</input>
|
|
843
|
-
|
|
844
|
-
<browser_state>
|
|
845
|
-
|
|
846
|
-
浏览器状态包含以下内容:
|
|
847
|
-
|
|
848
|
-
- url: 当前查看页面的 URL。
|
|
849
|
-
- title: 当前查看页面的标题。
|
|
850
|
-
- 可交互元素总数:带有 \`[ref=N]\` 标记的元素数量。
|
|
851
|
-
- YAML 树:页面的语义化结构,格式如下:
|
|
852
|
-
|
|
853
|
-
\`\`\`yaml
|
|
854
|
-
- region:
|
|
855
|
-
- main:
|
|
856
|
-
- button [cursor=pointer] [ref=9]: 产品文档
|
|
857
|
-
- button [selected] [cursor=pointer] [ref=47]: 40元/月 2核CPU 2GB内存
|
|
858
|
-
- radio [checked] [cursor=pointer] [ref=53]: 自动生成密码
|
|
859
|
-
- button [cursor=pointer] [ref=74]: 立即购买
|
|
860
|
-
\`\`\`
|
|
861
|
-
|
|
862
|
-
节点格式说明:
|
|
863
|
-
- \`- role [state1] [state2] [ref=N]: accessible name\`
|
|
864
|
-
- \`role\`:ARIA 语义角色(如 button/link/radio/heading/list/listitem 等)
|
|
865
|
-
- \`[state]\`:可选状态标记,如 \`[checked]\` \`[selected]\` \`[disabled]\` \`[expanded]\` \`[cursor=pointer]\`
|
|
866
|
-
- \`[ref=N]\`:可交互元素的唯一操作索引,**只有带 ref 的节点才能被操作**
|
|
867
|
-
- \`accessible name\`:元素的语义化名称(通过 aria-label/aria-labelledby/innerText 等计算得出)
|
|
868
|
-
- 缩进表示父子关系
|
|
869
|
-
|
|
870
|
-
</browser_state>
|
|
871
|
-
|
|
872
|
-
<browser_state_diff>
|
|
873
|
-
|
|
874
|
-
在交互过程中,为了提高效率和减少上下文占用,工具会生成页面的增量差异(Diff)信息。
|
|
875
|
-
Diff 格式示例如下:
|
|
876
|
-
\`\`\`diff
|
|
877
|
-
- button [ref=9]: 产品文档
|
|
878
|
-
+ button [ref=9]: 产品文档 (已点击)
|
|
879
|
-
\`\`\`
|
|
880
|
-
或者,当页面结构发生改变时,会展示新增或移除的节点差异。
|
|
881
|
-
|
|
882
|
-
### 页面状态获取四原则(重要,请严格遵守):
|
|
883
|
-
|
|
884
|
-
> 与业界 AI 编辑器(Cursor / Windsurf)按需读取文件而非全量加载的理念完全一致——**先精准搜索,再按需拉取全量**,将发送给大模型的 token 降至最低。
|
|
885
|
-
|
|
886
|
-
1. **按关键词精准搜索(最高优先级)**:当你已知要找什么类型的元素(如按钮、输入框、特定名称的链接)时,**优先使用 \`searchTree\` 动作**,传入 role 名称、元素文本或状态关键词搜索。它只返回命中行和上下文,token 消耗比全量树减少 80%+ 。
|
|
887
|
-
- 示例:查找所有按钮 → \`{"action": "searchTree", "query": "button"}\`
|
|
888
|
-
- 示例:查找含"提交"文本的节点 → \`{"action": "searchTree", "query": "提交"}\`
|
|
889
|
-
- 示例:查找已勾选的复选框 → \`{"action": "searchTree", "query": "checked"}\`
|
|
890
|
-
- 示例:精确定位某个 ref → \`{"action": "searchTree", "query": "#5"}\`
|
|
891
|
-
2. **首次获取全量**:首次进入页面、页面发生重大刷新、或 \`searchTree\` 无法找到所需信息时,调用 \`browserState\` 并指定 \`responseMode\` 为 \`full\` 或 \`both\` 获取完整 A11y 树。
|
|
892
|
-
3. **增量优先**:执行 \`click\`、\`fill\`、\`select\`、\`scroll\` 操作后,工具默认自动返回 \`diff\` 增量信息。优先阅读这些 Diff,以便快速确认操作是否生效。
|
|
893
|
-
4. **按需拉取全量**:如果增量 Diff 不足以支持下一步操作,或需要寻找不在 Diff 中的 \`[ref=N]\` 节点,且 \`searchTree\` 也无法定位时,再显式调用 \`browserState\` 拉取完整树。
|
|
894
|
-
|
|
895
|
-
</browser_state_diff>
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
<browser_rules>
|
|
900
|
-
在使用浏览器和浏览网页时严格遵守以下规则:
|
|
901
|
-
|
|
902
|
-
- 仅与分配有 \`[ref=N]\` 的元素进行交互。
|
|
903
|
-
- 仅使用明确提供的 ref 索引。
|
|
904
|
-
- 每次操作后 ref 索引会重新分配,不要使用旧的 ref 索引。
|
|
905
|
-
- 如果页面在执行操作后发生变化(例如输入文本操作),分析是否需要与新元素进行交互,例如从列表中选择正确的选项。
|
|
906
|
-
- 默认情况下,仅列出可见视口中的元素。如果你怀疑需要交互的相关内容在屏幕外,请使用滚动操作。仅在页面下方或上方还有更多像素时才滚动。
|
|
907
|
-
- 你可以使用 num_pages 参数滚动特定页数(例如,0.5 表示半页,2.0 表示两页)。
|
|
908
|
-
- 如果出现验证码,告诉用户你无法解决验证码。完成任务并请用户解决它。
|
|
909
|
-
- 如果缺少预期元素,尝试滚动或导航回退。
|
|
910
|
-
- 除非某些条件发生变化,否则不要重复同一操作超过 3 次。
|
|
911
|
-
- 如果你向输入字段填充文本且操作序列被中断,通常意味着某些内容发生了变化,例如下拉建议弹出。
|
|
912
|
-
- 如果 <user_request> 包含特定的页面信息,如产品类型、评分、价格、位置等,尝试应用过滤器以提高效率。
|
|
913
|
-
- <user_request> 是最终目标。如果用户指定了明确的步骤,它们始终具有最高优先级。
|
|
914
|
-
- 如果你向字段输入文本,可能需要按回车键、点击搜索按钮或从下拉列表中选择以完成操作。
|
|
915
|
-
- 如果不需要,不要登录页面。如果没有凭据,不要登录。
|
|
916
|
-
- 有两种类型的任务,首先思考你正在处理哪种类型的请求:
|
|
917
|
-
|
|
918
|
-
1. 非常具体的逐步说明:
|
|
919
|
-
|
|
920
|
-
- 非常精确地遵循它们,不要跳过步骤。尝试按要求完成所有内容。
|
|
921
|
-
|
|
922
|
-
2. 开放式任务。自己规划,在实现目标时保持创造性。
|
|
923
|
-
|
|
924
|
-
- 如果在开放式任务中陷入困境(例如登录或验证码),可以重新评估任务并尝试替代方法,例如有时即使页面的某些部分可访问或通过 Web 搜索获取一些信息,也会意外弹出登录框。
|
|
925
|
-
</browser_rules>
|
|
926
|
-
|
|
927
|
-
<capability>
|
|
928
|
-
- 你只能处理单页应用。不要跳出当前页面。
|
|
929
|
-
- 如果链接将在新页面中打开(例如,<a target="_blank">),不要点击该链接。
|
|
930
|
-
- 任务失败是可以接受的。
|
|
931
|
-
- 用户可能是错的。如果用户的请求无法实现、不适当,或者你没有足够的信息或工具来实现它。告诉用户提出更好的请求。
|
|
932
|
-
- 网页可能已损坏。所有网页或应用都有 bug。有些 bug 会使你的工作变得困难。鼓励你告诉用户当前页面的问题。你的反馈(包括失败)对用户很有价值。
|
|
933
|
-
- 过于努力可能有害。来回重复某些操作或在知识有限的情况下推动复杂程序可能导致不良结果和有害副作用。用户宁愿你以失败告终完成任务。
|
|
934
|
-
- 如果你对当前网页或任务没有相关知识。你必须要求用户提供具体说明和详细步骤。
|
|
935
|
-
</capability>
|
|
936
|
-
|
|
937
|
-
<task_completion_rules>
|
|
938
|
-
你必须在以下情况时结束任务:
|
|
939
|
-
|
|
940
|
-
- 当你完全完成用户请求时。
|
|
941
|
-
- 当你感到困惑或无法解决用户请求时。或者用户请求不清楚或包含不当内容。
|
|
942
|
-
- 如果绝对不可能继续。
|
|
943
|
-
|
|
944
|
-
</task_completion_rules>
|
|
945
|
-
`;function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName==="INPUT"}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName==="TEXTAREA"}function isSelectElement(e){return e?.nodeType===1&&e.tagName==="SELECT"}function isAnchorElement(e){return e?.nodeType===1&&e.tagName==="A"}function getIframeOffset(e){const t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};const r=t.getBoundingClientRect();return{x:r.left,y:r.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value").set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,r){const n=getIframeOffset(e);window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:t+n.x,y:r+n.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer"))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::EnablePassThrough"))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::DisablePassThrough"))}function getElementByIndex(e,t){const r=e.get(t);if(!r)throw new Error(`No interactive element found at index ${t}`);const n=r.ref;if(!n)throw new Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(n))throw new Error(`Element at index ${t} is not an HTMLElement`);return n}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.dispatchEvent(new PointerEvent("pointerout",{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent("pointerleave",{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent("mouseleave",{bubbles:!1})),lastClickedElement.blur(),lastClickedElement=null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);const t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);const r=e.getBoundingClientRect(),n=r.left+r.width/2,o=r.top+r.height/2;await movePointerToElement(e,n,o),await clickPointer(),await waitFor(.1);const a=e.ownerDocument;await enablePassThrough();const s=a.elementFromPoint(n,o);await disablePassThrough();const i=s instanceof HTMLElement&&e.contains(s)?s:e,l={bubbles:!0,cancelable:!0,clientX:n,clientY:o,pointerType:"mouse"},c={bubbles:!0,cancelable:!0,clientX:n,clientY:o,button:0};i.dispatchEvent(new PointerEvent("pointerover",l)),i.dispatchEvent(new PointerEvent("pointerenter",{...l,bubbles:!1})),i.dispatchEvent(new MouseEvent("mouseover",c)),i.dispatchEvent(new MouseEvent("mouseenter",{...c,bubbles:!1})),i.dispatchEvent(new PointerEvent("pointerdown",l)),i.dispatchEvent(new MouseEvent("mousedown",c)),e.focus({preventScroll:!0}),i.dispatchEvent(new PointerEvent("pointerup",l)),i.dispatchEvent(new MouseEvent("mouseup",c)),i.click(),await waitFor(.2)}async function inputTextElement(e,t){const r=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!r)throw new Error("Element is not an input, textarea, or contenteditable");if(await clickElement(e),r){if(e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(e.innerText="",e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))),e.innerText.trim()!==t.trim()){e.focus();const n=e.ownerDocument,o=(n.defaultView||window).getSelection(),a=n.createRange();a.selectNodeContents(e),o?.removeAllRanges(),o?.addRange(a),n.execCommand("delete",!1),n.execCommand("insertText",!1,t)}e.dispatchEvent(new Event("change",{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);r||e.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!isSelectElement(e))throw new Error("Element is not a select element");const r=Array.from(e.options).find(n=>n.textContent?.trim()===t.trim());if(!r)throw new Error(`Option with text "${t}" not found in select element`);e.value=r.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){const t=e;typeof t.scrollIntoViewIfNeeded=="function"?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(e,t){if(t){const s=t;let i=s,l=!1,c=null,u=0,d=0;const p=e;for(;i&&d<10;){const f=window.getComputedStyle(i),h=/(auto|scroll|overlay)/.test(f.overflowY)||f.scrollbarWidth&&f.scrollbarWidth!=="auto"||f.scrollbarGutter&&f.scrollbarGutter!=="auto",b=i.scrollHeight>i.clientHeight;if(h&&b){const y=i.scrollTop,w=i.scrollHeight-i.clientHeight;let g=p/3;g>0?g=Math.min(g,w-y):g=Math.max(g,-y),i.scrollTop=y+g;const m=i.scrollTop-y;if(Math.abs(m)>.5){l=!0,c=i,u=m;break}}if(i===document.body||i===document.documentElement)break;i=i.parentElement,d++}return l?`Scrolled container (${c?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const r=e,n=s=>s.clientHeight>=window.innerHeight*.5,o=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&n(s));let a=document.activeElement;for(;a&&!o(a)&&a!==document.body;)a=a.parentElement;if(a=o(a)?a:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){const s=window.scrollY,i=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const l=window.scrollY,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const u=r>0&&l>=i-1,d=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the bottom of the page.`:d?`✅ Scrolled page by ${c}px. Reached the top of the page.`:`✅ Scrolled page by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const i=a.scrollTop,l=a.scrollHeight-a.clientHeight;a.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const c=a.scrollTop,u=c-i;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${a.tagName}), cannot scroll up further.`;const d=r>0&&c>=l-1,p=r<0&&c<=1;return d?`✅ ${s} Scrolled container (${a.tagName}) by ${u}px. Reached the bottom.`:p?`✅ ${s} Scrolled container (${a.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${a.tagName}) by ${u}px.`}}async function scrollHorizontally(e,t){if(t){const s=t;let i=s,l=!1,c=null,u=0,d=0;const p=e;for(;i&&d<10;){const f=window.getComputedStyle(i),h=/(auto|scroll|overlay)/.test(f.overflowX)||f.scrollbarWidth&&f.scrollbarWidth!=="auto"||f.scrollbarGutter&&f.scrollbarGutter!=="auto",b=i.scrollWidth>i.clientWidth;if(h&&b){const y=i.scrollLeft,w=i.scrollWidth-i.clientWidth;let g=p/3;g>0?g=Math.min(g,w-y):g=Math.max(g,-y),i.scrollLeft=y+g;const m=i.scrollLeft-y;if(Math.abs(m)>.5){l=!0,c=i,u=m;break}}if(i===document.body||i===document.documentElement)break;i=i.parentElement,d++}return l?`Scrolled container (${c?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const r=e,n=s=>s.clientWidth>=window.innerWidth*.5,o=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&n(s));let a=document.activeElement;for(;a&&!o(a)&&a!==document.body;)a=a.parentElement;if(a=o(a)?a:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){const s=window.scrollX,i=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const l=window.scrollX,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const u=r>0&&l>=i-1,d=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the right edge of the page.`:d?`✅ Scrolled page by ${c}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const i=a.scrollLeft,l=a.scrollWidth-a.clientWidth;a.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const c=a.scrollLeft,u=c-i;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${a.tagName}), cannot scroll left further.`;const d=r>0&&c>=l-1,p=r<0&&c<=1;return d?`✅ ${s} Scrolled container (${a.tagName}) by ${u}px. Reached the right edge.`:p?`✅ ${s} Scrolled container (${a.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${a.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:r,highlightOpacity:n,highlightLabelOpacity:o}=e,{doHighlightElements:a,focusHighlightIndex:s,viewportExpansion:i,debugMode:l}=e;let c=0;const u=new WeakMap;function d(C,N){!C||C.nodeType!==Node.ELEMENT_NODE||u.set(C,{...u.get(C),...N})}const p={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{p.boundingRects=new WeakMap,p.clientRects=new WeakMap,p.computedStyles=new WeakMap}};function f(C){if(!C)return null;if(p.boundingRects.has(C))return p.boundingRects.get(C);const N=C.getBoundingClientRect();return N&&p.boundingRects.set(C,N),N}function h(C){if(!C)return null;if(p.computedStyles.has(C))return p.computedStyles.get(C);const N=window.getComputedStyle(C);return N&&p.computedStyles.set(C,N),N}function b(C){if(!C)return null;if(p.clientRects.has(C))return p.clientRects.get(C);const N=C.getClientRects();return N&&p.clientRects.set(C,N),N}const y={},w={current:0},g="playwright-highlight-container";function m(C,N,L=null){if(!C)return N;const I=[];let k=null,O=20,q=16,B=null;try{let F=document.getElementById(g);F||(F=document.createElement("div"),F.id=g,F.style.position="fixed",F.style.pointerEvents="none",F.style.top="0",F.style.left="0",F.style.width="100%",F.style.height="100%",F.style.zIndex="2147483640",F.style.backgroundColor="transparent",document.body.appendChild(F));const j=C.getClientRects();if(!j||j.length===0)return N;const M=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let Z=M[N%M.length];const H=Z+Math.floor(n*255).toString(16).padStart(2,"0");Z=Z+Math.floor(o*255).toString(16).padStart(2,"0");let J={x:0,y:0};if(L){const ae=L.getBoundingClientRect();J.x=ae.left,J.y=ae.top}const oe=document.createDocumentFragment();for(const ae of j){if(ae.width===0||ae.height===0)continue;const ee=document.createElement("div");ee.style.position="fixed",ee.style.border=`2px solid ${Z}`,ee.style.backgroundColor=H,ee.style.pointerEvents="none",ee.style.boxSizing="border-box";const Y=ae.top+J.y,ce=ae.left+J.x;ee.style.top=`${Y}px`,ee.style.left=`${ce}px`,ee.style.width=`${ae.width}px`,ee.style.height=`${ae.height}px`,oe.appendChild(ee),I.push({element:ee,initialRect:ae})}const se=j[0];k=document.createElement("div"),k.className="playwright-highlight-label",k.style.position="fixed",k.style.background=Z,k.style.color="white",k.style.padding="1px 4px",k.style.borderRadius="4px",k.style.fontSize=`${Math.min(12,Math.max(8,se.height/2))}px`,k.textContent=N.toString(),O=k.offsetWidth>0?k.offsetWidth:O,q=k.offsetHeight>0?k.offsetHeight:q;const _e=se.top+J.y,Te=se.left+J.x;let Se=_e+2,Q=Te+se.width-O-2;(se.width<O+4||se.height<q+4)&&(Se=_e-q-2,Q=Te+se.width-O,Q<J.x&&(Q=Te)),Se=Math.max(0,Math.min(Se,window.innerHeight-q)),Q=Math.max(0,Math.min(Q,window.innerWidth-O)),k.style.top=`${Se}px`,k.style.left=`${Q}px`,oe.appendChild(k);const ne=((ae,ee)=>{let Y=0;return(...ce)=>{const le=performance.now();if(!(le-Y<ee))return Y=le,ae(...ce)}})(()=>{const ae=C.getClientRects();let ee={x:0,y:0};if(L){const Y=L.getBoundingClientRect();ee.x=Y.left,ee.y=Y.top}if(I.forEach((Y,ce)=>{if(ce<ae.length){const le=ae[ce],P=le.top+ee.y,W=le.left+ee.x;Y.element.style.top=`${P}px`,Y.element.style.left=`${W}px`,Y.element.style.width=`${le.width}px`,Y.element.style.height=`${le.height}px`,Y.element.style.display=le.width===0||le.height===0?"none":"block"}else Y.element.style.display="none"}),ae.length<I.length)for(let Y=ae.length;Y<I.length;Y++)I[Y].element.style.display="none";if(k&&ae.length>0){const Y=ae[0],ce=Y.top+ee.y,le=Y.left+ee.x;let P=ce+2,W=le+Y.width-O-2;(Y.width<O+4||Y.height<q+4)&&(P=ce-q-2,W=le+Y.width-O,W<ee.x&&(W=le)),P=Math.max(0,Math.min(P,window.innerHeight-q)),W=Math.max(0,Math.min(W,window.innerWidth-O)),k.style.top=`${P}px`,k.style.left=`${W}px`,k.style.display="block"}else k&&(k.style.display="none")},16);return window.addEventListener("scroll",ne,!0),window.addEventListener("resize",ne),B=()=>{window.removeEventListener("scroll",ne,!0),window.removeEventListener("resize",ne),I.forEach(ae=>ae.element.remove()),k&&k.remove()},F.appendChild(oe),N+1}finally{B&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(B)}}function S(C){if(!C||C.nodeType!==Node.ELEMENT_NODE)return null;const N=h(C);if(!N)return null;const L=N.display;if(L==="inline"||L==="inline-block")return null;const I=N.overflowX,k=N.overflowY,O=N.scrollbarWidth&&N.scrollbarWidth!=="auto"||N.scrollbarGutter&&N.scrollbarGutter!=="auto",q=I==="auto"||I==="scroll",B=k==="auto"||k==="scroll";if(!q&&!B&&!O)return null;const F=C.scrollWidth-C.clientWidth,j=C.scrollHeight-C.clientHeight,M=4;if(F<M&&j<M||!B&&!O&&F<M||!q&&!O&&j<M)return null;const Z=C.scrollTop,H=C.scrollLeft,J={top:Z,right:C.scrollWidth-C.clientWidth-C.scrollLeft,bottom:C.scrollHeight-C.clientHeight-C.scrollTop,left:H};return d(C,{scrollable:!0,scrollData:J}),J}function v(C){try{if(i===-1){const q=C.parentElement;if(!q)return!1;try{return q.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const F=window.getComputedStyle(q);return F.display!=="none"&&F.visibility!=="hidden"&&F.opacity!=="0"}}const N=document.createRange();N.selectNodeContents(C);const L=N.getClientRects();if(!L||L.length===0)return!1;let I=!1,k=!1;for(const q of L)if(q.width>0&&q.height>0&&(I=!0,!(q.bottom<-i||q.top>window.innerHeight+i||q.right<-i||q.left>window.innerWidth+i))){k=!0;break}if(!I||!k)return!1;const O=C.parentElement;if(!O)return!1;try{return O.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const B=window.getComputedStyle(O);return B.display!=="none"&&B.visibility!=="hidden"&&B.opacity!=="0"}}catch(N){return console.warn("Error checking text node visibility:",N),!1}}function _(C){if(!C||!C.tagName)return!1;const N=new Set(["body","div","main","article","section","nav","header","footer"]),L=C.tagName.toLowerCase();return N.has(L)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(L)}function $(C){const N=h(C);return C.offsetWidth>0&&C.offsetHeight>0&&N?.visibility!=="hidden"&&N?.display!=="none"}function T(C){if(!C||C.nodeType!==Node.ELEMENT_NODE||t.includes(C))return!1;if(r.includes(C))return!0;const N=C.tagName.toLowerCase(),L=h(C),I=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),k=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function O(Z){return Z.tagName.toLowerCase()==="html"?!1:!!(L?.cursor&&I.has(L.cursor))}if(O(C))return!0;const q=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),B=new Set(["disabled","readonly"]);if(q.has(N)){if(L?.cursor&&k.has(L.cursor))return!1;for(const Z of B)if(C.hasAttribute(Z)||C.getAttribute(Z)==="true"||C.getAttribute(Z)==="")return!1;return!(C.disabled||C.readOnly||C.inert)}const F=C.getAttribute("role"),j=C.getAttribute("aria-role");if(C.getAttribute("contenteditable")==="true"||C.isContentEditable||C.classList&&(C.classList.contains("button")||C.classList.contains("dropdown-toggle")||C.getAttribute("data-index")||C.getAttribute("data-toggle")==="dropdown"||C.getAttribute("aria-haspopup")==="true"))return!0;const M=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(q.has(N)||F&&M.has(F)||j&&M.has(j))return!0;try{if(typeof getEventListeners=="function"){const H=getEventListeners(C);for(const J of["click","mousedown","mouseup","dblclick"])if(H[J]&&H[J].length>0)return!0}const Z=C?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof Z=="function"){const H=Z(C);for(const J of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const oe of H)if(oe.type===J)return!0}for(const H of["onclick","onmousedown","onmouseup","ondblclick"])if(C.hasAttribute(H)||typeof C[H]=="function")return!0}catch{}return!!S(C)}function R(C){if(i===-1)return!0;const N=b(C);if(!N||N.length===0)return!1;let L=!1;for(const q of N)if(q.width>0&&q.height>0&&!(q.bottom<-i||q.top>window.innerHeight+i||q.right<-i||q.left>window.innerWidth+i)){L=!0;break}if(!L)return!1;if(C.ownerDocument!==window.document)return!0;let I=Array.from(N).find(q=>q.width>0&&q.height>0);if(!I)return!1;const k=C.getRootNode();if(k instanceof ShadowRoot){const q=I.left+I.width/2,B=I.top+I.height/2;try{const F=k.elementFromPoint(q,B);if(!F)return!1;let j=F;for(;j&&j!==k;){if(j===C)return!0;j=j.parentElement}return!1}catch{return!0}}const O=5;return[{x:I.left+I.width/2,y:I.top+I.height/2},{x:I.left+O,y:I.top+O},{x:I.right-O,y:I.bottom-O}].some(({x:q,y:B})=>{try{const F=document.elementFromPoint(q,B);if(!F)return!1;let j=F;for(;j&&j!==document.documentElement;){if(j===C)return!0;j=j.parentElement}return!1}catch{return!0}})}function x(C,N){if(N===-1)return!0;const L=C.getClientRects();if(!L||L.length===0){const I=f(C);return!I||I.width===0||I.height===0?!1:!(I.bottom<-N||I.top>window.innerHeight+N||I.right<-N||I.left>window.innerWidth+N)}for(const I of L)if(!(I.width===0||I.height===0)&&!(I.bottom<-N||I.top>window.innerHeight+N||I.right<-N||I.left>window.innerWidth+N))return!0;return!1}const E=["aria-expanded","aria-checked","aria-selected","aria-pressed","aria-haspopup","aria-controls","aria-owns","aria-activedescendant","aria-valuenow","aria-valuetext","aria-valuemax","aria-valuemin","aria-autocomplete"];function A(C){for(let N=0;N<E.length;N++)if(C.hasAttribute(E[N]))return!0;return!1}function D(C){if(!C||C.nodeType!==Node.ELEMENT_NODE)return!1;const N=C.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(N)?!0:C.hasAttribute("onclick")||C.hasAttribute("role")||C.hasAttribute("tabindex")||A(C)||C.hasAttribute("data-action")||C.getAttribute("contenteditable")==="true"}const U=new Set(["a","button","input","select","textarea","summary","details","label","option","li"]),K=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","listitem","treeitem","row","option","scrollbar"]);function G(C){if(!C||C.nodeType!==Node.ELEMENT_NODE||!$(C))return!1;const N=C.hasAttribute("role")||C.hasAttribute("tabindex")||C.hasAttribute("onclick")||typeof C.onclick=="function",L=/\b(btn|clickable|menu|item|entry|link)\b/i.test(C.className||""),I=!!C.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),k=[...C.children].some($),O=C.parentElement&&C.parentElement.isSameNode(document.body);return(T(C)||N||L)&&k&&I&&!O}function te(C){if(!C||C.nodeType!==Node.ELEMENT_NODE)return!1;const N=C.tagName.toLowerCase(),L=C.getAttribute("role");if(N==="iframe"||U.has(N)||L&&K.has(L)||C.isContentEditable||C.getAttribute("contenteditable")==="true"||C.hasAttribute("data-testid")||C.hasAttribute("data-cy")||C.hasAttribute("data-test")||C.hasAttribute("onclick")||typeof C.onclick=="function"||A(C))return!0;try{const I=C?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof I=="function"){const k=I(C);for(const O of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const q of k)if(q.type===O)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(k=>C.hasAttribute(k)))return!0}catch{}return!!(G(C)||u.get(C)?.scrollable)}function X(C,N,L,I){if(!C.isInteractive)return!1;let k=!1;return I?te(N)?k=!0:k=!1:k=!0,k&&(C.isInViewport=x(N,i),(C.isInViewport||i===-1)&&(C.highlightIndex=c++,a))?(s>=0?s===C.highlightIndex&&m(N,C.highlightIndex,L):m(N,C.highlightIndex,L),!0):!1}function ue(C,N=null,L=!1){if(!C||C.id===g||C.nodeType!==Node.ELEMENT_NODE&&C.nodeType!==Node.TEXT_NODE||!C||C.id===g||C.dataset?.browserUseIgnore==="true"||C.dataset?.pageAgentIgnore==="true"||C.getAttribute&&C.getAttribute("aria-hidden")==="true")return null;if(C===document.body){const q={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const F of C.childNodes){const j=ue(F,N,!1);j&&q.children.push(j)}const B=`${w.current++}`;return y[B]=q,B}if(C.nodeType!==Node.ELEMENT_NODE&&C.nodeType!==Node.TEXT_NODE)return null;if(C.nodeType===Node.TEXT_NODE){const q=C.textContent?.trim();if(!q)return null;const B=C.parentElement;if(!B||B.tagName.toLowerCase()==="script")return null;const F=`${w.current++}`;return y[F]={type:"TEXT_NODE",text:q,isVisible:v(C)},F}if(C.nodeType===Node.ELEMENT_NODE&&!_(C))return null;if(i!==-1&&!C.shadowRoot){const q=f(C),B=h(C),F=B&&(B.position==="fixed"||B.position==="sticky"),j=C.offsetWidth>0||C.offsetHeight>0;if(!q||!F&&!j&&(q.bottom<-i||q.top>window.innerHeight+i||q.right<-i||q.left>window.innerWidth+i))return null}const I={tagName:C.tagName.toLowerCase(),attributes:{},children:[]};if(D(C)||C.tagName.toLowerCase()==="iframe"||C.tagName.toLowerCase()==="body"){const q=C.getAttributeNames?.()||[];for(const B of q){const F=C.getAttribute(B);I.attributes[B]=F}C.tagName.toLowerCase()==="input"&&(C.type==="checkbox"||C.type==="radio")&&(I.attributes.checked=C.checked?"true":"false")}let k=!1;if(C.nodeType===Node.ELEMENT_NODE&&(I.isVisible=$(C),I.isVisible)){I.isTopElement=R(C);const q=C.getAttribute("role"),B=q==="menu"||q==="menubar"||q==="listbox";if((I.isTopElement||B)&&(I.isInteractive=T(C),k=X(I,C,N,L),I.ref=C,I.isInteractive&&Object.keys(I.attributes).length===0)){const F=C.getAttributeNames?.()||[];for(const j of F){const M=C.getAttribute(j);I.attributes[j]=M}}}if(C.tagName){const q=C.tagName.toLowerCase();if(q==="iframe")try{const B=C.contentDocument||C.contentWindow?.document;if(B)for(const F of B.childNodes){const j=ue(F,C,!1);j&&I.children.push(j)}}catch(B){console.warn("Unable to access iframe:",B)}else if(C.isContentEditable||C.getAttribute("contenteditable")==="true"||C.id==="tinymce"||C.classList.contains("mce-content-body")||q==="body"&&C.getAttribute("data-id")?.startsWith("mce_"))for(const B of C.childNodes){const F=ue(B,N,k);F&&I.children.push(F)}else{if(C.shadowRoot){I.shadowRoot=!0;for(const B of C.shadowRoot.childNodes){const F=ue(B,N,k);F&&I.children.push(F)}}for(const B of C.childNodes){const F=ue(B,N,k||L);F&&I.children.push(F)}}}if(I.tagName==="a"&&I.children.length===0&&!I.attributes.href){const q=f(C);if(!(q&&q.width>0&&q.height>0||C.offsetWidth>0||C.offsetHeight>0))return null}I.extra=u.get(C)||null;const O=`${w.current++}`;return y[O]=I,O}const V=ue(document.body);return p.clearCache(),{rootId:V,map:y}},DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set(["nav","menu","header","footer","aside","dialog"]),newElementsCache=new WeakMap;function getFlatTree(e){const t=resolveViewportExpansion(e.viewportExpansion),r=[];for(const s of e.interactiveBlacklist||[])typeof s=="function"?r.push(s()):r.push(s);const n=[];for(const s of e.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const o=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:r,interactiveWhitelist:n,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(const s in o.map){const i=o.map[s];if(i.isInteractive&&i.ref){const l=i.ref;newElementsCache.has(l)||(newElementsCache.set(l,a),i.isNew=!0)}}return o}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${r.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){const r={};for(const n of t)if(n.includes("*")){const o=globToRegex(n);for(const a of Object.keys(e))o.test(a)&&e[a].trim()&&(r[a]=e[a].trim())}else{const o=e[n];o&&o.trim()&&(r[n]=o.trim())}return r}function flatTreeToString(e,t=[],r=!1){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],o=[...t,...n],a=(p,f)=>p.length>f?p.substring(0,f)+"...":p,s=p=>{const f=e.map[p];if(!f)return null;if(f.type==="TEXT_NODE"){const h=f;return{type:"text",text:h.text,isVisible:h.isVisible,parent:null,children:[]}}else{const h=f,b=[];if(h.children)for(const y of h.children){const w=s(y);w&&(w.parent=null,b.push(w))}return{type:"element",tagName:h.tagName,attributes:h.attributes??{},isVisible:h.isVisible??!1,isInteractive:h.isInteractive??!1,isTopElement:h.isTopElement??!1,isNew:h.isNew??!1,highlightIndex:h.highlightIndex,parent:null,children:b,extra:h.extra??{}}}},i=(p,f=null)=>{p.parent=f;for(const h of p.children)i(h,p)},l=s(e.rootId);if(!l)return"";i(l);const c=p=>{let f=p.parent;for(;f;){if(f.type==="element"&&f.highlightIndex!==void 0)return!0;f=f.parent}return!1},u=(p,f,h)=>{let b=f;const y=" ".repeat(f);if(p.type==="element"){const w=r&&p.tagName&&SEMANTIC_TAGS.has(p.tagName);if(p.highlightIndex!==void 0){b+=1;const S=getAllTextTillNextClickableElement(p);let v="";if(o.length>0&&p.attributes){const $=matchAttributes(p.attributes,o),T=Object.keys($);if(T.length>1){const R=new Set,x={};for(const E of T){const A=$[E];A.length>5&&(A in x?R.add(E):x[A]=E)}for(const E of R)delete $[E]}$.role===p.tagName&&delete $.role;for(const R of["aria-label","placeholder","title"])$[R]&&$[R].toLowerCase().trim()===S.toLowerCase().trim()&&delete $[R];Object.keys($).length>0&&(v=Object.entries($).map(([R,x])=>`${R}=${a(x,20)}`).join(" "))}let _=`${y}${p.isNew?`*[${p.highlightIndex}]`:`[${p.highlightIndex}]`}<${p.tagName??""}`;if(v&&(_+=` ${v}`),p.extra&&p.extra.scrollable){let $="";p.extra.scrollData?.left&&($+=`left=${p.extra.scrollData.left}, `),p.extra.scrollData?.top&&($+=`top=${p.extra.scrollData.top}, `),p.extra.scrollData?.right&&($+=`right=${p.extra.scrollData.right}, `),p.extra.scrollData?.bottom&&($+=`bottom=${p.extra.scrollData.bottom}`),_+=` data-scrollable="${$}"`}if(S){const $=S.trim();v||(_+=" "),_+=`>${$}`}else v||(_+=" ");_+=" />",h.push(_)}const g=w&&p.highlightIndex===void 0,m=g?h.length:-1;g&&(h.push(`${y}<${p.tagName}>`),b+=1);for(const S of p.children)u(S,b,h);g&&(h.length===m+1?h.pop():h.push(`${y}</${p.tagName}>`))}else if(p.type==="text"){if(c(p))return;p.parent&&p.parent.type==="element"&&p.parent.isVisible&&p.parent.isTopElement&&h.push(`${y}${p.text??""}`)}},d=[];return u(l,0,d),d.join(`
|
|
946
|
-
`)}var getAllTextTillNextClickableElement=(e,t=-1)=>{const r=[],n=(o,a)=>{if(!(t!==-1&&a>t)&&!(o.type==="element"&&o!==e&&o.highlightIndex!==void 0)){if(o.type==="text"&&o.text)r.push(o.text);else if(o.type==="element")for(const s of o.children)n(s,a+1)}};return n(e,0),r.join(`
|
|
947
|
-
`).trim()};function getSelectorMap(e){const t=new Map,r=Object.keys(e.map);for(const n of r){const o=e.map[n];o.isInteractive&&typeof o.highlightIndex=="number"&&t.set(o.highlightIndex,o)}return t}function getElementTextMap(e){const t=e.split(`
|
|
948
|
-
`).map(n=>n.trim()).filter(n=>n.length>0),r=new Map;for(const n of t){const o=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(n);if(o){const a=parseInt(o[1],10);r.set(a,n)}}return r}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const t of e)typeof t=="function"&&t();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()}),window.addEventListener("hashchange",()=>{cleanUpHighlights()}),window.addEventListener("beforeunload",()=>{cleanUpHighlights()});var navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const e=window.innerWidth,t=window.innerHeight,r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),n=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),o=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,a=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,n-(window.innerHeight+a)),i=Math.max(0,r-(window.innerWidth+o));return{viewport_width:e,viewport_height:t,page_width:r,page_height:n,scroll_x:o,scroll_y:a,pixels_above:a,pixels_below:s,pages_above:t>0?a/t:0,pages_below:t>0?s/t:0,total_pages:t>0?n/t:0,current_page_position:a/Math.max(1,n-t),pixels_left:o,pixels_right:i}}function patchReact(e){const t=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const r of t)r.setAttribute("data-page-agent-not-interactive","true")}var PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML="<EMPTY>";lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:e}=await Promise.resolve().then(()=>SimulatorMaskBHVXyogh);this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const e=window.location.href,t=document.title,r=getPageInfo(),n=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const o=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}
|
|
949
|
-
${`Page info: ${r.viewport_width}x${r.viewport_height}px viewport, ${r.page_width}x${r.page_height}px total page size, ${r.pages_above.toFixed(1)} pages above, ${r.pages_below.toFixed(1)} pages below, ${r.total_pages.toFixed(1)} total pages, at ${(r.current_page_position*100).toFixed(0)}% of page`}
|
|
950
|
-
|
|
951
|
-
${n===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:"}
|
|
952
|
-
|
|
953
|
-
${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]"}`,content:o,footer:r.pixels_below>4&&n!==-1?`... ${r.pixels_below} pixels below (${r.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]"}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){console.log("[PageController] cleanUpHighlights"),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(e){try{this.assertIndexed();const t=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${r??e}).`}}catch(t){return{success:!1,message:`❌ Failed to click element: ${t}`}}}async inputText(e,t){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await inputTextElement(r,t),{success:!0,message:`✅ Input text (${t}) into element (${n??e}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(e,t){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await selectOptionElement(r,t),{success:!0,message:`✅ Selected option (${t}) in element (${n??e}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(e){try{const{down:t,numPages:r,pixels:n,index:o}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((n??r*window.innerHeight)*(t?1:-1),o!==void 0?getElementByIndex(this.selectorMap,o):null)}}catch(t){return{success:!1,message:`❌ Failed to scroll: ${t}`}}}async scrollHorizontally(e){try{const{right:t,pixels:r,index:n}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(r*(t?1:-1),n!==void 0?getElementByIndex(this.selectorMap,n):null)}}catch(t){return{success:!1,message:`❌ Failed to scroll horizontally: ${t}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},toStr=Object.prototype.toString;function isCallable(e){return typeof e=="function"||toStr.call(e)==="[object Function]"}function toInteger(e){var t=Number(e);return isNaN(t)?0:t===0||!isFinite(t)?t:(t>0?1:-1)*Math.floor(Math.abs(t))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(e){var t=toInteger(e);return Math.min(Math.max(t,0),maxSafeInteger)}function arrayFrom(e,t){var r=Array,n=Object(e);if(e==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var o=toLength(n.length),a=isCallable(r)?Object(new r(o)):new Array(o),s=0,i;s<o;)i=n[s],a[s]=i,s+=1;return a.length=o,a}function _typeof$1(e){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof$1(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,_toPropertyKey(n.key),n)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,t,r){return t=_toPropertyKey(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return _typeof$1(t)==="symbol"?t:String(t)}function _toPrimitive(e,t){if(_typeof$1(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(_typeof$1(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var SetLike=(function(){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,e),_defineProperty(this,"items",void 0),this.items=t}return _createClass(e,[{key:"add",value:function(r){return this.has(r)===!1&&this.items.push(r),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(r){var n=this.items.length;return this.items=this.items.filter(function(o){return o!==r}),n!==this.items.length}},{key:"forEach",value:function(r){var n=this;this.items.forEach(function(o){r(o,o,n)})}},{key:"has",value:function(r){return this.items.indexOf(r)!==-1}},{key:"size",get:function(){return this.items.length}}]),e})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(e){var t;return(t=e.localName)!==null&&t!==void 0?t:e.tagName.toLowerCase()}var localNameToRoleMappings={article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",form:"form",footer:"contentinfo",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",html:"document",legend:"legend",li:"listitem",math:"math",main:"main",menu:"list",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",progress:"progressbar",section:"region",summary:"button",table:"table",tbody:"rowgroup",textarea:"textbox",tfoot:"rowgroup",td:"cell",th:"columnheader",thead:"rowgroup",tr:"row",ul:"list"},prohibitedAttributes={caption:new Set(["aria-label","aria-labelledby"]),code:new Set(["aria-label","aria-labelledby"]),deletion:new Set(["aria-label","aria-labelledby"]),emphasis:new Set(["aria-label","aria-labelledby"]),generic:new Set(["aria-label","aria-labelledby","aria-roledescription"]),insertion:new Set(["aria-label","aria-labelledby"]),none:new Set(["aria-label","aria-labelledby"]),paragraph:new Set(["aria-label","aria-labelledby"]),presentation:new Set(["aria-label","aria-labelledby"]),strong:new Set(["aria-label","aria-labelledby"]),subscript:new Set(["aria-label","aria-labelledby"]),superscript:new Set(["aria-label","aria-labelledby"])};function hasGlobalAriaAttributes(e,t){return["aria-atomic","aria-busy","aria-controls","aria-current","aria-description","aria-describedby","aria-details","aria-dropeffect","aria-flowto","aria-grabbed","aria-hidden","aria-keyshortcuts","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-roledescription"].some(function(r){var n;return e.hasAttribute(r)&&!((n=prohibitedAttributes[t])!==null&&n!==void 0&&n.has(r))})}function ignorePresentationalRole(e,t){return hasGlobalAriaAttributes(e,t)}function getRole(e){var t=getExplicitRole(e);if(t===null||presentationRoles.indexOf(t)!==-1){var r=getImplicitRole(e);if(presentationRoles.indexOf(t||"")===-1||ignorePresentationalRole(e,r||""))return r}return t}function getImplicitRole(e){var t=localNameToRoleMappings[getLocalName(e)];if(t!==void 0)return t;switch(getLocalName(e)){case"a":case"area":case"link":if(e.hasAttribute("href"))return"link";break;case"img":return e.getAttribute("alt")===""&&!ignorePresentationalRole(e,"img")?"presentation":"img";case"input":{var r=e,n=r.type;switch(n){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return n;case"range":return"slider";case"email":case"tel":case"text":case"url":return e.hasAttribute("list")?"combobox":"textbox";case"search":return e.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return e.hasAttribute("multiple")||e.size>1?"listbox":"combobox"}return null}function getExplicitRole(e){var t=e.getAttribute("role");if(t!==null){var r=t.trim().split(" ")[0];if(r.length>0)return r}return null}var presentationRoles=["presentation","none"];function isElement(e){return e!==null&&e.nodeType===e.ELEMENT_NODE}function isHTMLTableCaptionElement(e){return isElement(e)&&getLocalName(e)==="caption"}function isHTMLInputElement(e){return isElement(e)&&getLocalName(e)==="input"}function isHTMLOptGroupElement(e){return isElement(e)&&getLocalName(e)==="optgroup"}function isHTMLSelectElement(e){return isElement(e)&&getLocalName(e)==="select"}function isHTMLTableElement(e){return isElement(e)&&getLocalName(e)==="table"}function isHTMLTextAreaElement(e){return isElement(e)&&getLocalName(e)==="textarea"}function safeWindow(e){var t=e.ownerDocument===null?e:e.ownerDocument,r=t.defaultView;if(r===null)throw new TypeError("no window available");return r}function isHTMLFieldSetElement(e){return isElement(e)&&getLocalName(e)==="fieldset"}function isHTMLLegendElement(e){return isElement(e)&&getLocalName(e)==="legend"}function isHTMLSlotElement(e){return isElement(e)&&getLocalName(e)==="slot"}function isSVGElement(e){return isElement(e)&&e.ownerSVGElement!==void 0}function isSVGSVGElement(e){return isElement(e)&&getLocalName(e)==="svg"}function isSVGTitleElement(e){return isSVGElement(e)&&getLocalName(e)==="title"}function queryIdRefs(e,t){if(isElement(e)&&e.hasAttribute(t)){var r=e.getAttribute(t).split(" "),n=e.getRootNode?e.getRootNode():e.ownerDocument;return r.map(function(o){return n.getElementById(o)}).filter(function(o){return o!==null})}return[]}function hasAnyConcreteRoles(e,t){return isElement(e)?t.indexOf(getRole(e))!==-1:!1}function asFlatString(e){return e.trim().replace(/\s\s+/g," ")}function isHidden$2(e,t){if(!isElement(e))return!1;if(e.hasAttribute("hidden")||e.getAttribute("aria-hidden")==="true")return!0;var r=t(e);return r.getPropertyValue("display")==="none"||r.getPropertyValue("visibility")==="hidden"}function isControl(e){return hasAnyConcreteRoles(e,["button","combobox","listbox","textbox"])||hasAbstractRole(e,"range")}function hasAbstractRole(e,t){if(!isElement(e))return!1;switch(t){case"range":return hasAnyConcreteRoles(e,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(t,"'. This is likely a bug :("))}}function querySelectorAllSubtree(e,t){var r=arrayFrom(e.querySelectorAll(t));return queryIdRefs(e,"aria-owns").forEach(function(n){r.push.apply(r,arrayFrom(n.querySelectorAll(t)))}),r}function querySelectedOptions(e){return isHTMLSelectElement(e)?e.selectedOptions||querySelectorAllSubtree(e,"[selected]"):querySelectorAllSubtree(e,'[aria-selected="true"]')}function isMarkedPresentational(e){return hasAnyConcreteRoles(e,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(e){return isHTMLTableCaptionElement(e)}function allowsNameFromContent(e){return hasAnyConcreteRoles(e,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(e){return!1}function getValueOfTextbox(e){return isHTMLInputElement(e)||isHTMLTextAreaElement(e)?e.value:e.textContent||""}function getTextualContent(e){var t=e.getPropertyValue("content");return/^["'].*["']$/.test(t)?t.slice(1,-1):""}function isLabelableElement(e){var t=getLocalName(e);return t==="button"||t==="input"&&e.getAttribute("type")!=="hidden"||t==="meter"||t==="output"||t==="progress"||t==="select"||t==="textarea"}function findLabelableElement(e){if(isLabelableElement(e))return e;var t=null;return e.childNodes.forEach(function(r){if(t===null&&isElement(r)){var n=findLabelableElement(r);n!==null&&(t=n)}}),t}function getControlOfLabel(e){if(e.control!==void 0)return e.control;var t=e.getAttribute("for");return t!==null?e.ownerDocument.getElementById(t):findLabelableElement(e)}function getLabels(e){var t=e.labels;if(t===null)return t;if(t!==void 0)return arrayFrom(t);if(!isLabelableElement(e))return null;var r=e.ownerDocument;return arrayFrom(r.querySelectorAll("label")).filter(function(n){return getControlOfLabel(n)===e})}function getSlotContents(e){var t=e.assignedNodes();return t.length===0?arrayFrom(e.childNodes):t}function computeTextAlternative(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=new SetLike$1,n=safeWindow(e),o=t.compute,a=o===void 0?"name":o,s=t.computedStyleSupportsPseudoElements,i=s===void 0?t.getComputedStyle!==void 0:s,l=t.getComputedStyle,c=l===void 0?n.getComputedStyle.bind(n):l,u=t.hidden,d=u===void 0?!1:u;function p(w,g){var m="";if(isElement(w)&&i){var S=c(w,"::before"),v=getTextualContent(S);m="".concat(v," ").concat(m)}var _=isHTMLSlotElement(w)?getSlotContents(w):arrayFrom(w.childNodes).concat(queryIdRefs(w,"aria-owns"));if(_.forEach(function(R){var x=y(R,{isEmbeddedInLabel:g.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),E=isElement(R)?c(R).getPropertyValue("display"):"inline",A=E!=="inline"?" ":"";m+="".concat(A).concat(x).concat(A)}),isElement(w)&&i){var $=c(w,"::after"),T=getTextualContent($);m="".concat(m," ").concat(T)}return m.trim()}function f(w,g){var m=w.getAttributeNode(g);return m!==null&&!r.has(m)&&m.value.trim()!==""?(r.add(m),m.value):null}function h(w){return isElement(w)?f(w,"title"):null}function b(w){if(!isElement(w))return null;if(isHTMLFieldSetElement(w)){r.add(w);for(var g=arrayFrom(w.childNodes),m=0;m<g.length;m+=1){var S=g[m];if(isHTMLLegendElement(S))return y(S,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(w)){r.add(w);for(var v=arrayFrom(w.childNodes),_=0;_<v.length;_+=1){var $=v[_];if(isHTMLTableCaptionElement($))return y($,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(w)){r.add(w);for(var T=arrayFrom(w.childNodes),R=0;R<T.length;R+=1){var x=T[R];if(isSVGTitleElement(x))return x.textContent}return null}else if(getLocalName(w)==="img"||getLocalName(w)==="area"){var E=f(w,"alt");if(E!==null)return E}else if(isHTMLOptGroupElement(w)){var A=f(w,"label");if(A!==null)return A}if(isHTMLInputElement(w)&&(w.type==="button"||w.type==="submit"||w.type==="reset")){var D=f(w,"value");if(D!==null)return D;if(w.type==="submit")return"Submit";if(w.type==="reset")return"Reset"}var U=getLabels(w);if(U!==null&&U.length!==0)return r.add(w),arrayFrom(U).map(function(X){return y(X,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(X){return X.length>0}).join(" ");if(isHTMLInputElement(w)&&w.type==="image"){var K=f(w,"alt");if(K!==null)return K;var G=f(w,"title");return G!==null?G:"Submit Query"}if(hasAnyConcreteRoles(w,["button"])){var te=p(w,{isEmbeddedInLabel:!1});if(te!=="")return te}return null}function y(w,g){if(r.has(w))return"";if(!d&&isHidden$2(w,c)&&!g.isReferenced)return r.add(w),"";var m=isElement(w)?w.getAttributeNode("aria-labelledby"):null,S=m!==null&&!r.has(m)?queryIdRefs(w,"aria-labelledby"):[];if(a==="name"&&!g.isReferenced&&S.length>0)return r.add(m),S.map(function(E){return y(E,{isEmbeddedInLabel:g.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var v=g.recursion&&isControl(w)&&a==="name";if(!v){var _=(isElement(w)&&w.getAttribute("aria-label")||"").trim();if(_!==""&&a==="name")return r.add(w),_;if(!isMarkedPresentational(w)){var $=b(w);if($!==null)return r.add(w),$}}if(hasAnyConcreteRoles(w,["menu"]))return r.add(w),"";if(v||g.isEmbeddedInLabel||g.isReferenced){if(hasAnyConcreteRoles(w,["combobox","listbox"])){r.add(w);var T=querySelectedOptions(w);return T.length===0?isHTMLInputElement(w)?w.value:"":arrayFrom(T).map(function(E){return y(E,{isEmbeddedInLabel:g.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(w,"range"))return r.add(w),w.hasAttribute("aria-valuetext")?w.getAttribute("aria-valuetext"):w.hasAttribute("aria-valuenow")?w.getAttribute("aria-valuenow"):w.getAttribute("value")||"";if(hasAnyConcreteRoles(w,["textbox"]))return r.add(w),getValueOfTextbox(w)}if(allowsNameFromContent(w)||isElement(w)&&g.isReferenced||isNativeHostLanguageTextAlternativeElement(w)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var R=p(w,{isEmbeddedInLabel:g.isEmbeddedInLabel});if(R!=="")return r.add(w),R}if(w.nodeType===w.TEXT_NODE)return r.add(w),w.textContent||"";if(g.recursion)return r.add(w),p(w,{isEmbeddedInLabel:g.isEmbeddedInLabel});var x=h(w);return x!==null?(r.add(w),x):(r.add(w),"")}return asFlatString(y(e,{isEmbeddedInLabel:!1,isReferenced:a==="description",recursion:!1}))}function prohibitsNaming(e){return hasAnyConcreteRoles(e,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(e)?"":computeTextAlternative(e,t)}var candidateSelectors=["input:not([inert]):not([inert] *)","select:not([inert]):not([inert] *)","textarea:not([inert]):not([inert] *)","a[href]:not([inert]):not([inert] *)","area[href]:not([inert]):not([inert] *)","button:not([inert]):not([inert] *)","[tabindex]:not(slot):not([inert]):not([inert] *)","audio[controls]:not([inert]):not([inert] *)","video[controls]:not([inert]):not([inert] *)",'[contenteditable]:not([contenteditable="false"]):not([inert]):not([inert] *)',"details>summary:first-of-type:not([inert]):not([inert] *)","details:not([inert]):not([inert] *)"],NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e?.ownerDocument},isInput=function e(t){return t.tagName==="INPUT"},isHiddenInput=function e(t){return isInput(t)&&t.type==="hidden"},isDetailsWithSummary=function e(t){var r=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(n){return n.tagName==="SUMMARY"});return r},isNodeAttached=function e(t){var r,n=t&&getRootNode(t),o=(r=n)===null||r===void 0?void 0:r.host,a=!1;if(n&&n!==t){var s,i,l;for(a=!!((s=o)!==null&&s!==void 0&&(i=s.ownerDocument)!==null&&i!==void 0&&i.contains(o)||t!=null&&(l=t.ownerDocument)!==null&&l!==void 0&&l.contains(t));!a&&o;){var c,u,d;n=getRootNode(o),o=(c=n)===null||c===void 0?void 0:c.host,a=!!((u=o)!==null&&u!==void 0&&(d=u.ownerDocument)!==null&&d!==void 0&&d.contains(o))}}return a},isZeroArea=function e(t){var r=t.getBoundingClientRect(),n=r.width,o=r.height;return n===0&&o===0},isHidden$1=function e(t,r){var n=r.displayCheck,o=r.getShadowRoot;if(n==="full-native"&&"checkVisibility"in t){var a=t.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!a}var s=getComputedStyle(t),i=s.visibility;if(i==="hidden"||i==="collapse")return!0;var l=matches.call(t,"details>summary:first-of-type"),c=l?t.parentElement:t;if(matches.call(c,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="full-native"||n==="legacy-full"){if(typeof o=="function"){for(var u=t;t;){var d=t.parentElement,p=getRootNode(t);if(d&&!d.shadowRoot&&o(d)===!0)return isZeroArea(t);t.assignedSlot?t=t.assignedSlot:!d&&p!==t.ownerDocument?t=p.host:t=d}t=u}if(isNodeAttached(t))return!t.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return isZeroArea(t);return!1},isDisabledFromFieldset=function e(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var r=t.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var o=r.children.item(n);if(o.tagName==="LEGEND")return matches.call(r,"fieldset[disabled] *")?!0:!o.contains(t)}return!0}r=r.parentElement}return!1},isNodeMatchingSelectorFocusable=function e(t,r){return!(r.disabled||isHiddenInput(r)||isHidden$1(r,t)||isDetailsWithSummary(r)||isDisabledFromFieldset(r))},focusableCandidateSelector=candidateSelectors.concat("iframe:not([inert]):not([inert] *)").join(","),isFocusable=function e(t,r){if(r=r||{},!t)throw new Error("No node provided");return matches.call(t,focusableCandidateSelector)===!1?!1:isNodeMatchingSelectorFocusable(r,t)};const TAG_ROLE_MAP={a:"link",article:"article",aside:"complementary",button:"button",caption:"caption",cell:"cell",checkbox:"checkbox",code:"code",columnheader:"columnheader",combobox:"combobox",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",em:"emphasis",fieldset:"group",figure:"figure",footer:"contentinfo",form:"form",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",img:"img",input:"textbox",li:"listitem",link:"link",main:"main",mark:"mark",math:"math",menu:"list",menuitem:"menuitem",meter:"meter",nav:"navigation",ol:"list",option:"option",output:"status",p:"paragraph",progress:"progressbar",rowheader:"rowheader",search:"search",section:"region",select:"listbox",strong:"strong",summary:"button",table:"table",tbody:"rowgroup",td:"cell",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"},INPUT_TYPE_ROLE={button:"button",checkbox:"checkbox",color:"textbox",email:"textbox",file:"textbox",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"};function inferRole(e){const t=e.getAttribute("role");if(t&&t!=="presentation"&&t!=="none")return t;const r=e.tagName.toLowerCase();if(r==="input"){const n=e.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[n]??"textbox"}return TAG_ROLE_MAP[r]??"generic"}function getStateTokens(e){const t=[],r=u=>e.getAttribute(u),n=r("aria-checked");n==="true"?t.push("checked"):n==="false"&&t.push("unchecked"),r("aria-selected")==="true"&&t.push("selected"),(r("aria-disabled")==="true"||e.disabled)&&t.push("disabled");const a=r("aria-haspopup");a&&a!=="false"&&t.push("hasPopup"),r("aria-expanded")==="true"&&t.push("expanded");const s=e.tagName.match(/^H([1-6])$/);s&&t.push(`level=${s[1]}`);const i=r("aria-level");i&&!s&&t.push(`level=${i}`);try{window.getComputedStyle(e).cursor==="pointer"&&t.push("cursor=pointer")}catch{}const l=e.tagName.toLowerCase();if(l==="input"||l==="textarea"||l==="select"){const u=e.value;u!==void 0&&u!==""&&t.push(`value="${u}"`)}const c=e.getAttribute("aria-valuenow");return c&&t.push(`valuenow="${c}"`),t}function isHidden(e){if(e.getAttribute("aria-hidden")==="true"||e.hidden)return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0}catch{}return!1}function buildVNode(e,t,r,n,o){if(isHidden(e)||n.has(e))return null;const a=inferRole(e),s=getStateTokens(e),i=computeAccessibleName(e),l=isFocusable(e),c=s.includes("cursor=pointer"),u=o.has(e),d=l||u||c&&(a!=="generic"||i!=="");let p;d&&(p=t.value,r.set(p,e),t.value++);const f=[];for(const h of Array.from(e.children)){const b=buildVNode(h,t,r,n,o);b&&f.push(b)}return{role:a,name:i,tokens:s,ref:p,el:e,children:f}}function hasValue(e){return e.ref!==void 0||e.name.trim()!==""?!0:e.children.some(hasValue)}function shouldPassThrough(e,t){return!(!t.pruneUnnamed||t.preserveRoles.includes(e.role)||e.ref!==void 0||e.name.trim()!=="")}function serializeVNode(e,t,r){if(shouldPassThrough(e,r))return e.children.filter(c=>hasValue(c)).flatMap(c=>serializeVNode(c,t,r));const n=" ".repeat(t),o=e.ref!==void 0?` #${e.ref}`:"",a=e.tokens.length>0?` [${e.tokens.join(" ")}]`:"",s=e.name?` "${e.name}"`:"",i=`${n}- ${e.role}${o}${a}${s}`,l=e.children.flatMap(c=>serializeVNode(c,t+1,r));return[i,...l]}const DEFAULT_OPTIONS={pruneUnnamed:!0,preserveRoles:[]};function buildA11yTree(e=document.body,t=[],r=[],n){const o={...DEFAULT_OPTIONS,...n},a={value:0},s=new Map,i=new Set(t),l=new Set(r),c=[];for(const d of Array.from(e.children)){const p=buildVNode(d,a,s,i,l);p&&c.push(...serializeVNode(p,0,o))}return{yaml:"```yaml\n"+c.join(`
|
|
954
|
-
`)+"\n```",refMap:s,interactiveCount:s.size,lines:c}}function searchA11yTree(e,t=document.body,r=[],n=[],o){const{contextLines:a=2,caseInsensitive:s=!0,maxMatches:i=20,...l}=o??{},{lines:c}=buildA11yTree(t,r,n,l),u=s?e.toLowerCase():e,d=c.length,f=/^#\d+$/.test(e)?new RegExp(`\\s${e}(?:\\s|[\\[]|$)`):null,h=[];for(let m=0;m<c.length;m++){let S=!1;f?S=f.test(c[m]):S=(s?c[m].toLowerCase():c[m]).includes(u),S&&h.push(m)}const b=[];let y=!1;for(const m of h){const S=Math.max(0,m-a),v=Math.min(d-1,m+a),_=b[b.length-1];if(_&&S<=_.end+1)_.end=Math.max(_.end,v),_.hits.push(m);else{if(b.length>=i){y=!0;break}b.push({start:S,end:v,hits:[m]})}}const w=b.map(m=>({lineNumber:m.hits[0]+1,line:c[m.hits[0]],context:Array.from({length:m.end-m.start+1},(S,v)=>({lineNumber:m.start+v+1,line:c[m.start+v]}))})),g=[`无障碍树搜索结果 — 关键词: "${e}" | 总行数: ${d} | 命中: ${h.length} 行 | 返回分组: ${w.length}`,""];return w.length===0?g.push("(未找到匹配项)"):(w.forEach((m,S)=>{const v=b[S];g.push(`── 分组 ${S+1}(第 ${v.start+1}–${v.end+1} 行)──`),m.context.forEach(({lineNumber:_,line:$})=>{const T=v.hits.includes(_-1),R=String(_).padStart(4);g.push(T?`>>>${R} | ${$}`:` ${R} | ${$}`)}),g.push("")}),y&&g.push(`⚠️ 命中过多,已截断至前 ${i} 个分组,建议缩小搜索范围`),g.push("提示:如需操作命中元素,使用其 #N 索引;如需查看完整树,请使用 browserState。")),{text:g.join(`
|
|
955
|
-
`),matches:w,totalLines:d,matchCount:h.length}}function Diff(){}Diff.prototype={diff:function e(t,r){var n,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=o.callback;typeof o=="function"&&(a=o,o={});var s=this;function i(S){return S=s.postProcess(S,o),a?(setTimeout(function(){a(S)},0),!0):S}t=this.castInput(t,o),r=this.castInput(r,o),t=this.removeEmpty(this.tokenize(t,o)),r=this.removeEmpty(this.tokenize(r,o));var l=r.length,c=t.length,u=1,d=l+c;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var p=(n=o.timeout)!==null&&n!==void 0?n:1/0,f=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],b=this.extractCommon(h[0],r,t,0,o);if(h[0].oldPos+1>=c&&b+1>=l)return i(buildValues(s,h[0].lastComponent,r,t,s.useLongestToken));var y=-1/0,w=1/0;function g(){for(var S=Math.max(y,-u);S<=Math.min(w,u);S+=2){var v=void 0,_=h[S-1],$=h[S+1];_&&(h[S-1]=void 0);var T=!1;if($){var R=$.oldPos-S;T=$&&0<=R&&R<l}var x=_&&_.oldPos+1<c;if(!T&&!x){h[S]=void 0;continue}if(!x||T&&_.oldPos<$.oldPos?v=s.addToPath($,!0,!1,0,o):v=s.addToPath(_,!1,!0,1,o),b=s.extractCommon(v,r,t,S,o),v.oldPos+1>=c&&b+1>=l)return i(buildValues(s,v.lastComponent,r,t,s.useLongestToken));h[S]=v,v.oldPos+1>=c&&(w=Math.min(w,S-1)),b+1>=l&&(y=Math.max(y,S+1))}u++}if(a)(function S(){setTimeout(function(){if(u>d||Date.now()>f)return a();g()||S()},0)})();else for(;u<=d&&Date.now()<=f;){var m=g();if(m)return m}},addToPath:function e(t,r,n,o,a){var s=t.lastComponent;return s&&!a.oneChangePerToken&&s.added===r&&s.removed===n?{oldPos:t.oldPos+o,lastComponent:{count:s.count+1,added:r,removed:n,previousComponent:s.previousComponent}}:{oldPos:t.oldPos+o,lastComponent:{count:1,added:r,removed:n,previousComponent:s}}},extractCommon:function e(t,r,n,o,a){for(var s=r.length,i=n.length,l=t.oldPos,c=l-o,u=0;c+1<s&&l+1<i&&this.equals(n[l+1],r[c+1],a);)c++,l++,u++,a.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return u&&!a.oneChangePerToken&&(t.lastComponent={count:u,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,c},equals:function e(t,r,n){return n.comparator?n.comparator(t,r):t===r||n.ignoreCase&&t.toLowerCase()===r.toLowerCase()},removeEmpty:function e(t){for(var r=[],n=0;n<t.length;n++)t[n]&&r.push(t[n]);return r},castInput:function e(t){return t},tokenize:function e(t){return Array.from(t)},join:function e(t){return t.join("")},postProcess:function e(t){return t}};function buildValues(e,t,r,n,o){for(var a=[],s;t;)a.push(t),s=t.previousComponent,delete t.previousComponent,t=s;a.reverse();for(var i=0,l=a.length,c=0,u=0;i<l;i++){var d=a[i];if(d.removed)d.value=e.join(n.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&o){var p=r.slice(c,c+d.count);p=p.map(function(f,h){var b=n[u+h];return b.length>f.length?b:f}),d.value=e.join(p)}else d.value=e.join(r.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return a}function longestCommonPrefix(e,t){var r;for(r=0;r<e.length&&r<t.length;r++)if(e[r]!=t[r])return e.slice(0,r);return e.slice(0,r)}function longestCommonSuffix(e,t){var r;if(!e||!t||e[e.length-1]!=t[t.length-1])return"";for(r=0;r<e.length&&r<t.length;r++)if(e[e.length-(r+1)]!=t[t.length-(r+1)])return e.slice(-r);return e.slice(-r)}function replacePrefix(e,t,r){if(e.slice(0,t.length)!=t)throw Error("string ".concat(JSON.stringify(e)," doesn't start with prefix ").concat(JSON.stringify(t),"; this is a bug"));return r+e.slice(t.length)}function replaceSuffix(e,t,r){if(!t)return e+r;if(e.slice(-t.length)!=t)throw Error("string ".concat(JSON.stringify(e)," doesn't end with suffix ").concat(JSON.stringify(t),"; this is a bug"));return e.slice(0,-t.length)+r}function removePrefix(e,t){return replacePrefix(e,t,"")}function removeSuffix(e,t){return replaceSuffix(e,t,"")}function maximumOverlap(e,t){return t.slice(0,overlapCount(e,t))}function overlapCount(e,t){var r=0;e.length>t.length&&(r=e.length-t.length);var n=t.length;e.length<t.length&&(n=e.length);var o=Array(n),a=0;o[0]=0;for(var s=1;s<n;s++){for(t[s]==t[a]?o[s]=o[a]:o[s]=a;a>0&&t[s]!=t[a];)a=o[a];t[s]==t[a]&&a++}a=0;for(var i=r;i<e.length;i++){for(;a>0&&e[i]!=t[a];)a=o[a];e[i]==t[a]&&a++}return a}var extendedWordChars="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",tokenizeIncludingWhitespace=new RegExp("[".concat(extendedWordChars,"]+|\\s+|[^").concat(extendedWordChars,"]"),"ug"),wordDiff=new Diff;wordDiff.equals=function(e,t,r){return r.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},wordDiff.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');r=Array.from(t.intlSegmenter.segment(e),function(a){return a.segment})}else r=e.match(tokenizeIncludingWhitespace)||[];var n=[],o=null;return r.forEach(function(a){/\s/.test(a)?o==null?n.push(a):n.push(n.pop()+a):/\s/.test(o)?n[n.length-1]==o?n.push(n.pop()+a):n.push(o+a):n.push(a),o=a}),n},wordDiff.join=function(e){return e.map(function(t,r){return r==0?t:t.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var r=null,n=null,o=null;return e.forEach(function(a){a.added?n=a:a.removed?o=a:((n||o)&&dedupeWhitespaceInChangeObjects(r,o,n,a),r=a,n=null,o=null)}),(n||o)&&dedupeWhitespaceInChangeObjects(r,o,n,null),e};function dedupeWhitespaceInChangeObjects(e,t,r,n){if(t&&r){var o=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],s=r.value.match(/^\s*/)[0],i=r.value.match(/\s*$/)[0];if(e){var l=longestCommonPrefix(o,s);e.value=replaceSuffix(e.value,s,l),t.value=removePrefix(t.value,l),r.value=removePrefix(r.value,l)}if(n){var c=longestCommonSuffix(a,i);n.value=replacePrefix(n.value,i,c),t.value=removeSuffix(t.value,c),r.value=removeSuffix(r.value,c)}}else if(r)e&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(e&&n){var u=n.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],p=t.value.match(/\s*$/)[0],f=longestCommonPrefix(u,d);t.value=removePrefix(t.value,f);var h=longestCommonSuffix(removePrefix(u,f),p);t.value=removeSuffix(t.value,h),n.value=replacePrefix(n.value,u,h),e.value=replaceSuffix(e.value,u,u.slice(0,u.length-h.length))}else if(n){var b=n.value.match(/^\s*/)[0],y=t.value.match(/\s*$/)[0],w=maximumOverlap(y,b);t.value=removeSuffix(t.value,w)}else if(e){var g=e.value.match(/\s*$/)[0],m=t.value.match(/^\s*/)[0],S=maximumOverlap(g,m);t.value=removePrefix(t.value,S)}}var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(e){var t=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return e.match(t)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
956
|
-
`));var r=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var o=0;o<n.length;o++){var a=n[o];o%2&&!t.newlineIsToken?r[r.length-1]+=a:r.push(a)}return r},lineDiff.equals=function(e,t,r){return r.ignoreWhitespace?((!r.newlineIsToken||!e.includes(`
|
|
957
|
-
`))&&(e=e.trim()),(!r.newlineIsToken||!t.includes(`
|
|
958
|
-
`))&&(t=t.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(e.endsWith(`
|
|
959
|
-
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
960
|
-
`)&&(t=t.slice(0,-1))),Diff.prototype.equals.call(this,e,t,r)};function diffLines(e,t,r){return lineDiff.diff(e,t,r)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function _typeof(e){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(e)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(e,t){var r=t.undefinedReplacement,n=t.stringifyReplacer,o=n===void 0?function(a,s){return typeof s>"u"?r:s}:n;return typeof e=="string"?e:JSON.stringify(canonicalize(e,null,null,o),o," ")},jsonDiff.equals=function(e,t,r){return Diff.prototype.equals.call(jsonDiff,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"),r)};function canonicalize(e,t,r,n,o){t=t||[],r=r||[],n&&(e=n(o,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return r[a];var s;if(Object.prototype.toString.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),r.push(s),a=0;a<e.length;a+=1)s[a]=canonicalize(e[a],t,r,n,o);return t.pop(),r.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),_typeof(e)==="object"&&e!==null){t.push(e),s={},r.push(s);var i=[],l;for(l in e)Object.prototype.hasOwnProperty.call(e,l)&&i.push(l);for(i.sort(),a=0;a<i.length;a+=1)l=i[a],s[l]=canonicalize(e[l],t,r,n,l);t.pop(),r.pop()}else s=e;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(e){return e.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(e){return e};class PageStateCache{constructor(){this.prev=null}isFullRefresh(t){return!this.prev||this.prev.url!==t}update(t,r){const n=this.isFullRefresh(t),o=this.prev?.url??"";let a=0,s=0,i="";if(!n&&this.prev){const l=diffLines(this.prev.yaml,r),c=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const d=u.value.split(`
|
|
961
|
-
`).filter(Boolean);u.added?(a+=d.length,d.forEach(p=>c.push(`+ ${p}`))):(s+=d.length,d.forEach(p=>c.push(`- ${p}`)))}),i=c.join(`
|
|
962
|
-
`)}return this.prev={url:t,yaml:r},{isFullRefresh:n,prevUrl:o,addedLines:a,removedLines:s,diffText:i}}invalidate(){this.prev=null}}function registerPageAgentTool(){initializeBuiltinWebMCP(),window.__webmcpcli_interactiveWhitelist=[],window.__webmcpcli_interactiveBlacklist=[],window.__webmcpcli_beforeGetBrowserState=null;const e=new PageController({enableMask:!0}),t=new PageStateCache;let r=new Map;const n=objectType({action:enumType(["browserState","click","fill","select","scroll","executeJavascript","searchTree"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
|
|
963
|
-
browserState: '查询整个页面的浏览器状态;返回页面的标题、URL、YAML格式的语义化页面树',
|
|
964
|
-
click: '根据元素索引点击;',
|
|
965
|
-
fill: '根据元素索引填写文本;';
|
|
966
|
-
select: '根据元素索引选择下拉框选项;';
|
|
967
|
-
scroll: '滚动页面的动作,可以指定水平滚动还是上下滚动; 不带元素索引时:滚动整个文档。带元素索引时:滚动该索引处的容器(或其最近的可滚动祖先元素)'
|
|
968
|
-
executeJavascript: '执行javascript代码'
|
|
969
|
-
searchTree: '按关键词搜索无障碍树,返回带行号的匹配节点及上下文,无需获取全量树。适合快速定位特定元素(如所有按钮、特定名称的链接等),显著减少上下文消耗。必须提供 query 参数。'
|
|
970
|
-
`),index:numberType().min(0).optional().describe("执行动作 of the element index, 动作为 click,fill,select时,必须提供元素索引"),text:stringType().optional().describe("执行动作的文本内容, 动作为 fill,select 时,必须提供文本内容"),down:booleanType().optional().describe("执行上下滚动时,必须提供down参数"),right:booleanType().optional().describe("执行水平滚动方向, 必须提供right参数"),numPages:numberType().optional().describe("执行动作的滚动页数, 动作为 scroll时,可以提供滚动页数,建议每次滚动0.1页,该值不要大于5."),pixels:numberType().int().min(0).optional().describe("执行动作的滚动像素数,动作为 scroll时,可以提供滚动像素数"),script:stringType().optional().describe("执行的javascript代码,动作为 executeJavascript时,必须提供script参数"),query:stringType().optional().describe("搜索关键词,动作为 searchTree 时必须提供。支持按 role(如 button、link)、节点名称、状态(如 checked)或 ref 索引(如 #3)搜索"),contextLines:numberType().int().min(0).max(10).default(2).describe("searchTree 时每个命中行前后保留的上下文行数,默认 2"),maxMatches:numberType().int().min(1).max(50).default(20).describe("searchTree 时最大返回分组数,默认 20"),responseMode:enumType(["full","diff","both"]).optional().default("diff").describe("返回浏览器状态的模式。full: 仅返回当前全量 A11y 树;diff: 仅返回与上一次状态的增量差异;both: 同时返回全量 A11y 树与增量差异。默认值为 diff。")});async function o(s){return await e.hideMask(),{content:[{type:"text",text:s}]}}async function a(s="diff"){const i=window.location.href,l=document.title,c=window.__webmcpcli_interactiveBlacklist??[],u=window.__webmcpcli_interactiveWhitelist??[],{yaml:d,refMap:p}=buildA11yTree(document.body,c,u);r=p;const f=t.update(i,d);await e.hideMask();let h="";return s==="full"?h=d:s==="diff"?h=f.isFullRefresh?d:f.diffText:s==="both"&&(h=`【全量页面树】:
|
|
971
|
-
${d}
|
|
972
|
-
|
|
973
|
-
【增量差异】:
|
|
974
|
-
${f.isFullRefresh?"(首次/刷新,无增量差异)":f.diffText}`),{content:[{type:"text",text:`浏览器状态: ${JSON.stringify({url:i,title:l,content:h})}`}]}}document.modelContext.registerTool({name:"page-agent-tool",description:pageAgentPrompt,inputSchema:zodToJsonSchema(n),async execute(s){await e.showMask();const i=s.responseMode??"diff";try{if(s.action==="browserState")return window.__webmcpcli_beforeGetBrowserState&&window.__webmcpcli_beforeGetBrowserState(),a(i);if(s.action==="click"){if(s.index===void 0)return o("点击结果: 缺少元素索引");const l=r.get(s.index);return l?(await clickElement(l),a(i)):o(`点击结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`)}else if(s.action==="fill"){if(s.index===void 0||!s.text)return o("填写结果: 缺少元素索引或文本内容");const l=r.get(s.index);if(!l)return o(`填写结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`);let c=l;if(!(c instanceof HTMLInputElement)&&!(c instanceof HTMLTextAreaElement)){const u=l.querySelector("input, textarea");u&&(c=u)}return c instanceof HTMLInputElement&&c.readOnly?(c.value=s.text,c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0})),c.dispatchEvent(new Event("blur",{bubbles:!0}))):await inputTextElement(c,s.text),a(i)}else if(s.action==="select"){if(s.index===void 0||!s.text)return o("选择结果: 缺少元素索引或文本内容");const l=r.get(s.index);return l?(await selectOptionElement(l,s.text),a(i)):o(`选择结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`)}else if(s.action==="scroll"){if(!s.down&&!s.right)return o("滚动结果: 缺少滚动方向参数");const l=s.index!==void 0?r.get(s.index)??window:window;if(s.right){const c=s.pixels??300;l.scrollBy({left:s.right?c:-c,behavior:"smooth"})}else{const c=s.pixels??Math.round((s.numPages??1)*window.innerHeight);l.scrollBy({top:s.down?c:-c,behavior:"smooth"})}return await new Promise(c=>setTimeout(c,400)),a(i)}else if(s.action==="executeJavascript"){if(!s.script)return o("脚本执行异常: 缺少javascript代码");const l=await new Function(`return (async () => { ${s.script} })()`)();return await e.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(l)}`}]}}else if(s.action==="searchTree"){if(!s.query)return o("搜索失败: 缺少 query 参数");const l=window.__webmcpcli_interactiveBlacklist??[],c=window.__webmcpcli_interactiveWhitelist??[],{text:u}=searchA11yTree(s.query,document.body,l,c,{contextLines:s.contextLines,maxMatches:s.maxMatches});return await e.hideMask(),{content:[{type:"text",text:u}]}}}catch(l){return await e.hideMask(),{content:[{type:"text",text:`异常: ${String(l)}`}]}}}})}function computeBorderGeometry(e,t,r,n){const o=Math.max(1,Math.min(e,t)),a=Math.min(r,20),i=Math.min(a+n,o),l=Math.min(i,Math.floor(e/2)),c=Math.min(i,Math.floor(t/2)),u=N=>N/e*2-1,d=N=>N/t*2-1,p=0,f=e,h=0,b=t,y=l,w=e-l,g=c,m=t-c,S=u(p),v=u(f),_=d(h),$=d(b),T=u(y),R=u(w),x=d(g),E=d(m),A=0,D=0,U=1,K=1,G=l/e,te=1-l/e,X=c/t,ue=1-c/t,V=new Float32Array([S,_,v,_,S,x,S,x,v,_,v,x,S,E,v,E,S,$,S,$,v,E,v,$,S,x,T,x,S,E,S,E,T,x,T,E,R,x,v,x,R,E,R,E,v,x,v,E]),C=new Float32Array([A,D,U,D,A,X,A,X,U,D,U,X,A,ue,U,ue,A,K,A,K,U,ue,U,K,A,X,G,X,A,ue,A,ue,G,X,G,ue,te,X,U,X,te,ue,te,ue,U,X,U,ue]);return{positions:V,uvs:C}}function compileShader(e,t,r){const n=e.createShader(t);if(!n)throw new Error("Failed to create shader");if(e.shaderSource(n,r),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(n)||"Unknown shader error";throw e.deleteShader(n),new Error(o)}return n}function createProgram(e,t,r){const n=compileShader(e,e.VERTEX_SHADER,t),o=compileShader(e,e.FRAGMENT_SHADER,r),a=e.createProgram();if(!a)throw new Error("Failed to create program");if(e.attachShader(a,n),e.attachShader(a,o),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS)){const s=e.getProgramInfoLog(a)||"Unknown link error";throw e.deleteProgram(a),e.deleteShader(n),e.deleteShader(o),new Error(s)}return e.deleteShader(n),e.deleteShader(o),a}const fragmentShaderSource=`#version 300 es
|
|
975
|
-
precision lowp float;
|
|
976
|
-
in vec2 vUV;
|
|
977
|
-
out vec4 outColor;
|
|
978
|
-
uniform vec2 uResolution;
|
|
979
|
-
uniform float uTime;
|
|
980
|
-
uniform float uBorderWidth;
|
|
981
|
-
uniform float uGlowWidth;
|
|
982
|
-
uniform float uBorderRadius;
|
|
983
|
-
uniform vec3 uColors[4];
|
|
984
|
-
uniform float uGlowExponent;
|
|
985
|
-
uniform float uGlowFactor;
|
|
986
|
-
const float PI = 3.14159265359;
|
|
987
|
-
const float TWO_PI = 2.0 * PI;
|
|
988
|
-
const float HALF_PI = 0.5 * PI;
|
|
989
|
-
const vec4 startPositions = vec4(0.0, PI, HALF_PI, 1.5 * PI);
|
|
990
|
-
const vec4 speeds = vec4(-1.9, -1.9, -1.5, 2.1);
|
|
991
|
-
const vec4 innerRadius = vec4(PI * 0.8, PI * 0.7, PI * 0.3, PI * 0.1);
|
|
992
|
-
const vec4 outerRadius = vec4(PI * 1.2, PI * 0.9, PI * 0.6, PI * 0.4);
|
|
993
|
-
float random(vec2 st) {
|
|
994
|
-
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
|
|
995
|
-
}
|
|
996
|
-
vec2 random2(vec2 st) {
|
|
997
|
-
return vec2(random(st), random(st + 1.0));
|
|
998
|
-
}
|
|
999
|
-
float aaStep(float edge, float d) {
|
|
1000
|
-
float width = fwidth(d);
|
|
1001
|
-
return smoothstep(edge - width * 0.5, edge + width * 0.5, d);
|
|
1002
|
-
}
|
|
1003
|
-
float aaFract(float x) {
|
|
1004
|
-
float f = fract(x);
|
|
1005
|
-
float w = fwidth(x);
|
|
1006
|
-
float smooth_f = f * (1.0 - smoothstep(1.0 - w, 1.0, f));
|
|
1007
|
-
return smooth_f;
|
|
1008
|
-
}
|
|
1009
|
-
float sdRoundedBox(in vec2 p, in vec2 b, in float r) {
|
|
1010
|
-
vec2 q = abs(p) - b + r;
|
|
1011
|
-
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
|
|
1012
|
-
}
|
|
1013
|
-
float getInnerGlow(vec2 p, vec2 b, float radius) {
|
|
1014
|
-
float dist_x = b.x - abs(p.x);
|
|
1015
|
-
float dist_y = b.y - abs(p.y);
|
|
1016
|
-
float glow_x = smoothstep(radius, 0.0, dist_x);
|
|
1017
|
-
float glow_y = smoothstep(radius, 0.0, dist_y);
|
|
1018
|
-
return 1.0 - (1.0 - glow_x) * (1.0 - glow_y);
|
|
1019
|
-
}
|
|
1020
|
-
float getVignette(vec2 uv) {
|
|
1021
|
-
vec2 vignetteUv = uv;
|
|
1022
|
-
vignetteUv = vignetteUv * (1.0 - vignetteUv);
|
|
1023
|
-
float vignette = vignetteUv.x * vignetteUv.y * 25.0;
|
|
1024
|
-
vignette = pow(vignette, 0.16);
|
|
1025
|
-
vignette = 1.0 - vignette;
|
|
1026
|
-
return vignette;
|
|
1027
|
-
}
|
|
1028
|
-
float uvToAngle(vec2 uv) {
|
|
1029
|
-
vec2 center = vec2(0.5);
|
|
1030
|
-
vec2 dir = uv - center;
|
|
1031
|
-
return atan(dir.y, dir.x) + PI;
|
|
1032
|
-
}
|
|
1033
|
-
void main() {
|
|
1034
|
-
vec2 uv = vUV;
|
|
1035
|
-
vec2 pos = uv * uResolution;
|
|
1036
|
-
vec2 centeredPos = pos - uResolution * 0.5;
|
|
1037
|
-
vec2 size = uResolution - uBorderWidth;
|
|
1038
|
-
vec2 halfSize = size * 0.5;
|
|
1039
|
-
float dBorderBox = sdRoundedBox(centeredPos, halfSize, uBorderRadius);
|
|
1040
|
-
float border = aaStep(0.0, dBorderBox);
|
|
1041
|
-
float glow = getInnerGlow(centeredPos, halfSize, uGlowWidth);
|
|
1042
|
-
float vignette = getVignette(uv);
|
|
1043
|
-
glow *= vignette;
|
|
1044
|
-
float posAngle = uvToAngle(uv);
|
|
1045
|
-
vec4 lightCenter = mod(startPositions + speeds * uTime, TWO_PI);
|
|
1046
|
-
vec4 angleDist = abs(posAngle - lightCenter);
|
|
1047
|
-
vec4 disToLight = min(angleDist, TWO_PI - angleDist) / TWO_PI;
|
|
1048
|
-
float intensityBorder[4];
|
|
1049
|
-
intensityBorder[0] = 1.0;
|
|
1050
|
-
intensityBorder[1] = smoothstep(0.4, 0.0, disToLight.y);
|
|
1051
|
-
intensityBorder[2] = smoothstep(0.4, 0.0, disToLight.z);
|
|
1052
|
-
intensityBorder[3] = smoothstep(0.2, 0.0, disToLight.w) * 0.5;
|
|
1053
|
-
vec3 borderColor = vec3(0.0);
|
|
1054
|
-
for(int i = 0; i < 4; i++) {
|
|
1055
|
-
borderColor = mix(borderColor, uColors[i], intensityBorder[i]);
|
|
1056
|
-
}
|
|
1057
|
-
borderColor *= 1.1;
|
|
1058
|
-
borderColor = clamp(borderColor, 0.0, 1.0);
|
|
1059
|
-
float intensityGlow[4];
|
|
1060
|
-
intensityGlow[0] = smoothstep(0.9, 0.0, disToLight.x);
|
|
1061
|
-
intensityGlow[1] = smoothstep(0.7, 0.0, disToLight.y);
|
|
1062
|
-
intensityGlow[2] = smoothstep(0.4, 0.0, disToLight.z);
|
|
1063
|
-
intensityGlow[3] = smoothstep(0.1, 0.0, disToLight.w) * 0.7;
|
|
1064
|
-
vec4 breath = smoothstep(0.0, 1.0, sin(uTime * 1.0 + startPositions * PI) * 0.2 + 0.8);
|
|
1065
|
-
vec3 glowColor = vec3(0.0);
|
|
1066
|
-
glowColor += uColors[0] * intensityGlow[0] * breath.x;
|
|
1067
|
-
glowColor += uColors[1] * intensityGlow[1] * breath.y;
|
|
1068
|
-
glowColor += uColors[2] * intensityGlow[2] * breath.z;
|
|
1069
|
-
glowColor += uColors[3] * intensityGlow[3] * breath.w * glow;
|
|
1070
|
-
glow = pow(glow, uGlowExponent);
|
|
1071
|
-
glow *= random(pos + uTime) * 0.1 + 1.0;
|
|
1072
|
-
glowColor *= glow * uGlowFactor;
|
|
1073
|
-
glowColor = clamp(glowColor, 0.0, 1.0);
|
|
1074
|
-
vec3 color = mix(glowColor, borderColor + glowColor * 0.2, border);
|
|
1075
|
-
float alpha = mix(glow, 1.0, border);
|
|
1076
|
-
outColor = vec4(color, alpha);
|
|
1077
|
-
}`,vertexShaderSource=`#version 300 es
|
|
1078
|
-
in vec2 aPosition;
|
|
1079
|
-
in vec2 aUV;
|
|
1080
|
-
out vec2 vUV;
|
|
1081
|
-
void main() {
|
|
1082
|
-
vUV = aUV;
|
|
1083
|
-
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
1084
|
-
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error(`Invalid color format: ${e}`);const[,r,n,o]=t;return[parseInt(r)/255,parseInt(n)/255,parseInt(o)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(t={}){this.options={width:t.width??600,height:t.height??600,ratio:t.ratio??window.devicePixelRatio??1,borderWidth:t.borderWidth??8,glowWidth:t.glowWidth??200,borderRadius:t.borderRadius??8,mode:t.mode??"light",...t},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const t=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(t);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const o=(r-this.startTime)*.001;this.render(o)};this.rafId=requestAnimationFrame(t)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:t,vao:r,positionBuffer:n,uvBuffer:o,program:a}=this.glr;r&&t.deleteVertexArray(r),n&&t.deleteBuffer(n),o&&t.deleteBuffer(o),t.deleteProgram(a),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(t,r,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=t,this.options.height=r,n&&(this.options.ratio=n),!this.running)return;const{gl:o,program:a,vao:s,positionBuffer:i,uvBuffer:l,uResolution:c}=this.glr,u=n??this.options.ratio??window.devicePixelRatio??1,d=Math.max(1,Math.floor(t*u)),p=Math.max(1,Math.floor(r*u));this.canvas.style.width=`${t}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==d||this.canvas.height!==p)&&(this.canvas.width=d,this.canvas.height=p),o.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(o,"resize: after viewport setup");const{positions:f,uvs:h}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);o.bindVertexArray(s),o.bindBuffer(o.ARRAY_BUFFER,i),o.bufferData(o.ARRAY_BUFFER,f,o.STATIC_DRAW);const b=o.getAttribLocation(a,"aPosition");o.enableVertexAttribArray(b),o.vertexAttribPointer(b,2,o.FLOAT,!1,0,0),this.checkGLError(o,"resize: after position buffer update"),o.bindBuffer(o.ARRAY_BUFFER,l),o.bufferData(o.ARRAY_BUFFER,h,o.STATIC_DRAW);const y=o.getAttribLocation(a,"aUV");o.enableVertexAttribArray(y),o.vertexAttribPointer(y,2,o.FLOAT,!1,0,0),this.checkGLError(o,"resize: after UV buffer update"),o.useProgram(a),o.uniform2f(c,this.canvas.width,this.canvas.height),o.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),o.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),o.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(o,"resize: after uniform updates");const w=performance.now();this.lastTime=w;const g=(w-this.startTime)*.001;this.render(g)}autoResize(t){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=t.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(t)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,r)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>t(),n.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,r)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>t(),n.oncancel=()=>r("canceled")})}checkGLError(t,r){let n=t.getError();if(n!==t.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);n!==t.NO_ERROR;){const o=this.getGLErrorName(t,n);console.error(`${o} (0x${n.toString(16)})`),n=t.getError()}console.groupEnd()}}getGLErrorName(t,r){switch(r){case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const t=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!t)throw new Error("WebGL2 is required but not available.");const r=createProgram(t,vertexShaderSource,fragmentShaderSource);this.checkGLError(t,"setupGL: after createProgram");const n=t.createVertexArray();t.bindVertexArray(n),this.checkGLError(t,"setupGL: after VAO creation");const o=this.canvas.width||2,a=this.canvas.height||2,{positions:s,uvs:i}=computeBorderGeometry(o,a,this.options.borderWidth,this.options.glowWidth),l=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW);const c=t.getAttribLocation(r,"aPosition");t.enableVertexAttribArray(c),t.vertexAttribPointer(c,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after position buffer setup");const u=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW);const d=t.getAttribLocation(r,"aUV");t.enableVertexAttribArray(d),t.vertexAttribPointer(d,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after UV buffer setup");const p=t.getUniformLocation(r,"uResolution"),f=t.getUniformLocation(r,"uTime"),h=t.getUniformLocation(r,"uBorderWidth"),b=t.getUniformLocation(r,"uGlowWidth"),y=t.getUniformLocation(r,"uBorderRadius"),w=t.getUniformLocation(r,"uColors"),g=t.getUniformLocation(r,"uGlowExponent"),m=t.getUniformLocation(r,"uGlowFactor");t.useProgram(r),t.uniform1f(h,this.options.borderWidth),t.uniform1f(b,this.options.glowWidth),t.uniform1f(y,this.options.borderRadius),this.options.mode==="dark"?(t.uniform1f(g,2),t.uniform1f(m,1.8)):(t.uniform1f(g,1),t.uniform1f(m,1));const S=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let v=0;v<S.length;v++)t.uniform3f(t.getUniformLocation(r,`uColors[${v}]`),...S[v]);this.checkGLError(t,"setupGL: after uniform setup"),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this.glr={gl:t,program:r,vao:n,positionBuffer:l,uvBuffer:u,uResolution:p,uTime:f,uBorderWidth:h,uGlowWidth:b,uBorderRadius:y,uColors:w}}render(t){if(!this.glr)return;const{gl:r,program:n,vao:o,uTime:a}=this.glr;r.useProgram(n),r.bindVertexArray(o),r.uniform1f(a,t),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}}(function(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
|
|
1085
|
-
position: fixed;
|
|
1086
|
-
inset: 0;
|
|
1087
|
-
z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
|
|
1088
|
-
cursor: wait;
|
|
1089
|
-
overflow: hidden;
|
|
1090
|
-
|
|
1091
|
-
display: none;
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
._wrapper_1ooyb_1._visible_1ooyb_11 {
|
|
1095
|
-
display: block;
|
|
1096
|
-
}
|
|
1097
|
-
/* AI 光标样式 */
|
|
1098
|
-
._cursor_1dgwb_2 {
|
|
1099
|
-
position: absolute;
|
|
1100
|
-
width: var(--cursor-size, 75px);
|
|
1101
|
-
height: var(--cursor-size, 75px);
|
|
1102
|
-
pointer-events: none;
|
|
1103
|
-
z-index: 10000;
|
|
1104
|
-
}
|
|
1105
|
-
|
|
1106
|
-
._cursorBorder_1dgwb_10 {
|
|
1107
|
-
position: absolute;
|
|
1108
|
-
width: 100%;
|
|
1109
|
-
height: 100%;
|
|
1110
|
-
background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));
|
|
1111
|
-
mask-image: url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");
|
|
1112
|
-
mask-size: 100% 100%;
|
|
1113
|
-
mask-repeat: no-repeat;
|
|
1114
|
-
|
|
1115
|
-
transform-origin: center;
|
|
1116
|
-
transform: rotate(-135deg) scale(1.2);
|
|
1117
|
-
margin-left: -10px;
|
|
1118
|
-
margin-top: -18px;
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
._cursorFilling_1dgwb_25 {
|
|
1122
|
-
position: absolute;
|
|
1123
|
-
width: 100%;
|
|
1124
|
-
height: 100%;
|
|
1125
|
-
background: url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%3e%3cdefs%3e%3c/defs%3e%3cg%20xmlns='http://www.w3.org/2000/svg'%20style='filter:%20drop-shadow(light-dark(rgba(0,%200,%200,%200.4),%20rgba(237,%20237,%20237,%200.4))%203px%204px%204px);'%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='%23ffffff'%20stroke='none'%20style='fill:%20%23ffffff;'/%3e%3c/g%3e%3c/svg%3e");
|
|
1126
|
-
background-size: 100% 100%;
|
|
1127
|
-
background-repeat: no-repeat;
|
|
1128
|
-
|
|
1129
|
-
transform-origin: center;
|
|
1130
|
-
transform: rotate(-135deg) scale(1.2);
|
|
1131
|
-
margin-left: -10px;
|
|
1132
|
-
margin-top: -18px;
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
._cursorRipple_1dgwb_39 {
|
|
1136
|
-
position: absolute;
|
|
1137
|
-
width: 100%;
|
|
1138
|
-
height: 100%;
|
|
1139
|
-
pointer-events: none;
|
|
1140
|
-
margin-left: -50%;
|
|
1141
|
-
margin-top: -50%;
|
|
1142
|
-
|
|
1143
|
-
&::after {
|
|
1144
|
-
content: '';
|
|
1145
|
-
opacity: 0;
|
|
1146
|
-
position: absolute;
|
|
1147
|
-
inset: 0;
|
|
1148
|
-
border: 4px solid rgba(57, 182, 255, 1);
|
|
1149
|
-
border-radius: 50%;
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39::after {
|
|
1154
|
-
animation: _cursor-ripple_1dgwb_1 300ms ease-out forwards;
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
@keyframes _cursor-ripple_1dgwb_1 {
|
|
1158
|
-
0% {
|
|
1159
|
-
transform: scale(0);
|
|
1160
|
-
opacity: 1;
|
|
1161
|
-
}
|
|
1162
|
-
100% {
|
|
1163
|
-
transform: scale(2);
|
|
1164
|
-
opacity: 0;
|
|
1165
|
-
}
|
|
1166
|
-
}`)),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})(),(function(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
|
|
1167
|
-
position: fixed;
|
|
1168
|
-
inset: 0;
|
|
1169
|
-
z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
|
|
1170
|
-
cursor: wait;
|
|
1171
|
-
overflow: hidden;
|
|
1172
|
-
|
|
1173
|
-
display: none;
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
._wrapper_1ooyb_1._visible_1ooyb_11 {
|
|
1177
|
-
display: block;
|
|
1178
|
-
}
|
|
1179
|
-
/* AI 光标样式 */
|
|
1180
|
-
._cursor_1dgwb_2 {
|
|
1181
|
-
position: absolute;
|
|
1182
|
-
width: var(--cursor-size, 75px);
|
|
1183
|
-
height: var(--cursor-size, 75px);
|
|
1184
|
-
pointer-events: none;
|
|
1185
|
-
z-index: 10000;
|
|
1186
|
-
}
|
|
1187
|
-
|
|
1188
|
-
._cursorBorder_1dgwb_10 {
|
|
1189
|
-
position: absolute;
|
|
1190
|
-
width: 100%;
|
|
1191
|
-
height: 100%;
|
|
1192
|
-
background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));
|
|
1193
|
-
mask-image: url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");
|
|
1194
|
-
mask-size: 100% 100%;
|
|
1195
|
-
mask-repeat: no-repeat;
|
|
1196
|
-
|
|
1197
|
-
transform-origin: center;
|
|
1198
|
-
transform: rotate(-135deg) scale(1.2);
|
|
1199
|
-
margin-left: -10px;
|
|
1200
|
-
margin-top: -18px;
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
._cursorFilling_1dgwb_25 {
|
|
1204
|
-
position: absolute;
|
|
1205
|
-
width: 100%;
|
|
1206
|
-
height: 100%;
|
|
1207
|
-
background: url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%3e%3cdefs%3e%3c/defs%3e%3cg%20xmlns='http://www.w3.org/2000/svg'%20style='filter:%20drop-shadow(light-dark(rgba(0,%200,%200,%200.4),%20rgba(237,%20237,%20237,%200.4))%203px%204px%204px);'%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='%23ffffff'%20stroke='none'%20style='fill:%20%23ffffff;'/%3e%3c/g%3e%3c/svg%3e");
|
|
1208
|
-
background-size: 100% 100%;
|
|
1209
|
-
background-repeat: no-repeat;
|
|
1210
|
-
|
|
1211
|
-
transform-origin: center;
|
|
1212
|
-
transform: rotate(-135deg) scale(1.2);
|
|
1213
|
-
margin-left: -10px;
|
|
1214
|
-
margin-top: -18px;
|
|
1215
|
-
}
|
|
1216
|
-
|
|
1217
|
-
._cursorRipple_1dgwb_39 {
|
|
1218
|
-
position: absolute;
|
|
1219
|
-
width: 100%;
|
|
1220
|
-
height: 100%;
|
|
1221
|
-
pointer-events: none;
|
|
1222
|
-
margin-left: -50%;
|
|
1223
|
-
margin-top: -50%;
|
|
1224
|
-
|
|
1225
|
-
&::after {
|
|
1226
|
-
content: '';
|
|
1227
|
-
opacity: 0;
|
|
1228
|
-
position: absolute;
|
|
1229
|
-
inset: 0;
|
|
1230
|
-
border: 4px solid rgba(57, 182, 255, 1);
|
|
1231
|
-
border-radius: 50%;
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
|
|
1235
|
-
._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39::after {
|
|
1236
|
-
animation: _cursor-ripple_1dgwb_1 300ms ease-out forwards;
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
@keyframes _cursor-ripple_1dgwb_1 {
|
|
1240
|
-
0% {
|
|
1241
|
-
transform: scale(0);
|
|
1242
|
-
opacity: 1;
|
|
1243
|
-
}
|
|
1244
|
-
100% {
|
|
1245
|
-
transform: scale(2);
|
|
1246
|
-
opacity: 0;
|
|
1247
|
-
}
|
|
1248
|
-
}`)),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(e){return console.warn("Error determining if page is dark:",e),!1}}function hasDarkModeClass(){const e=["dark","dark-mode","theme-dark","night","night-mode"],t=document.documentElement,r=document.body||document.documentElement;for(const n of e)if(t.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute(){const e=document.documentElement,t=document.body||document.documentElement;for(const r of["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"]){const n=t?.getAttribute(r),o=e.getAttribute(r);if(n?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const t=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return t==="dark"||t==="only dark"}function isBackgroundDark(){const e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),r=e.backgroundColor,n=t.backgroundColor;return isColorDark(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark(r):!1}function isTextColorLight(){const t=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return t!==null&&t>200}function isMainContentBackgroundDark(){const{innerWidth:e,innerHeight:t}=window,r=e*t*.5;for(const n of["#app","#root","#__next"]){const o=document.querySelector(n);if(!o)continue;const a=o.getBoundingClientRect();if(!(a.width*a.height<r)&&isColorDark(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor(e){const t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function getLuminance(e){if(!e||e==="transparent"||e.startsWith("rgba(0, 0, 0, 0)"))return null;const t=parseRgbColor(e);return t?.299*t.r+.587*t.g+.114*t.b:null}function isColorDark(e,t=128){const r=getLuminance(e);return r!==null&&r<t}var SimulatorMask_module_default={wrapper:"_wrapper_1ooyb_1",visible:"_visible_1ooyb_11"},cursor_module_default={cursor:"_cursor_1dgwb_2",cursorBorder:"_cursorBorder_1dgwb_10",cursorFilling:"_cursorFilling_1dgwb_25",cursorRipple:"_cursorRipple_1dgwb_39",clicking:"_clicking_1dgwb_57"},SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement("div");motion=null;#n=!1;#e=document.createElement("div");#t=0;#r=0;#o=0;#a=0;constructor(){super(),this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const o=new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=o,this.wrapper.appendChild(o.element),o.autoResize(this.wrapper)}catch(o){console.warn("[SimulatorMask] Motion overlay unavailable:",o)}this.wrapper.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mousedown",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mouseup",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mousemove",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("wheel",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("keydown",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("keyup",o=>{o.stopPropagation(),o.preventDefault()}),this.#i(),document.body.appendChild(this.wrapper),this.#s();const e=o=>{const{x:a,y:s}=o.detail;this.setCursorPosition(a,s)},t=()=>{this.triggerClickAnimation()},r=()=>{this.wrapper.style.pointerEvents="none"},n=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",e),window.addEventListener("PageAgent::ClickPointer",t),window.addEventListener("PageAgent::EnablePassThrough",r),window.addEventListener("PageAgent::DisablePassThrough",n),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",e),window.removeEventListener("PageAgent::ClickPointer",t),window.removeEventListener("PageAgent::EnablePassThrough",r),window.removeEventListener("PageAgent::DisablePassThrough",n)})}#i(){this.#e.className=cursor_module_default.cursor;const e=document.createElement("div");e.className=cursor_module_default.cursorRipple,this.#e.appendChild(e);const t=document.createElement("div");t.className=cursor_module_default.cursorFilling,this.#e.appendChild(t);const r=document.createElement("div");r.className=cursor_module_default.cursorBorder,this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const e=this.#t+(this.#o-this.#t)*.2,t=this.#r+(this.#a-this.#r)*.2,r=Math.abs(e-this.#o);r>0&&(r<2?this.#t=this.#o:this.#t=e,this.#e.style.left=`${this.#t}px`);const n=Math.abs(t-this.#a);n>0&&(n<2?this.#r=this.#a:this.#r=t,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#n||(this.#o=e,this.#a=t)}triggerClickAnimation(){this.#n||(this.#e.classList.remove(cursor_module_default.clicking),this.#e.offsetHeight,this.#e.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#o=this.#t,this.#a=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#n=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}};const SimulatorMaskBHVXyogh=Object.freeze(Object.defineProperty({__proto__:null,SimulatorMask},Symbol.toStringTag,{value:"Module"}));exports.AgentModelProvider=AgentModelProvider,exports.Ajv=Ajv,exports.AuthClientProvider=AuthClientProvider,exports.ContentScriptServerTransport=ContentScriptServerTransport,exports.ExtensionClientTransport=ExtensionClientTransport,exports.ExtensionPageServerTransport=ExtensionPageServerTransport,exports.InMemoryTransport=InMemoryTransport,exports.MSG_REMOTER_READY=MSG_REMOTER_READY,exports.MSG_TOOL_REGISTERED=MSG_TOOL_REGISTERED,exports.MSG_TOOL_UNREGISTERED=MSG_TOOL_UNREGISTERED,exports.QrCode=QrCode,exports.ResourceTemplate=ResourceTemplate,exports.UriTemplate=UriTemplate,exports.WebMcpClient=WebMcpClient,exports.WebMcpServer=WebMcpServer,exports.cleanupWebMCPPolyfill=cleanupWebMCPPolyfill,exports.completable=completable,exports.createMessageChannelClientTransport=createMessageChannelClientTransport,exports.createMessageChannelPairTransport=createMessageChannelPairTransport,exports.createMessageChannelServerTransport=createMessageChannelServerTransport,exports.createRemoter=createRemoter,exports.createSSEClientTransport=createSSEClientTransport,exports.createSkillTools=createSkillTools,exports.createStreamableHTTPClientTransport=createStreamableHTTPClientTransport,exports.formatSkillsForSystemPrompt=formatSkillsForSystemPrompt,exports.getAISDKTools=getAISDKTools,exports.getDisplayName=getDisplayName,exports.getMainSkillPathByName=getMainSkillPathByName,exports.getMainSkillPaths=getMainSkillPaths,exports.getSkillMdContent=getSkillMdContent,exports.getSkillOverviews=getSkillOverviews,exports.initializeBuiltinWebMCP=initializeBuiltinWebMCP,exports.initializeWebMCPPolyfill=initializeWebMCPPolyfill,exports.initializeWebModelContextPolyfill=initializeWebMCPPolyfill,exports.isMcpClient=isMcpClient,exports.isMcpServer=isMcpServer,exports.isMessageChannelClientTransport=isMessageChannelClientTransport,exports.isMessageChannelServerTransport=isMessageChannelServerTransport,exports.isPlainObject=isPlainObject,exports.isSSEClientTransport=isSSEClientTransport,exports.isStreamableHTTPClientTransport=isStreamableHTTPClientTransport,exports.parseSkillFrontMatter=parseSkillFrontMatter,exports.registerNavigateTool=registerNavigateTool,exports.registerPageAgentTool=registerPageAgentTool,exports.registerPageTool=registerPageTool,exports.setNavigator=setNavigator,exports.setupModelContextBridge=setupModelContextBridge,exports.validateArgsWithSchema=validateArgsWithSchema,exports.withPageTools=withPageTools,exports.z=z,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
|