@cline/core 0.0.95 → 0.2.0-nightly.1793312794
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/dist/ClineCore.d.ts +6 -1
- package/dist/account/rpc.d.ts +3 -1
- package/dist/account/types.d.ts +2 -0
- package/dist/artifacts/cloud/fetch.d.ts +8 -0
- package/dist/artifacts/cloud/publish.d.ts +6 -0
- package/dist/artifacts/publish.d.ts +30 -0
- package/dist/cline-core/runtime-services.d.ts +4 -2
- package/dist/cloud/computer-use-prompt.d.ts +9 -0
- package/dist/cloud/controller.d.ts +26 -4
- package/dist/cloud/hub-client.d.ts +53 -0
- package/dist/cloud/hub-protocol.d.ts +32 -0
- package/dist/cloud/index.d.ts +5 -0
- package/dist/cloud/index.js +34 -17
- package/dist/cloud/types.d.ts +4 -1
- package/dist/extensions/context/compaction-shared.d.ts +1 -0
- package/dist/extensions/context/compaction.d.ts +7 -0
- package/dist/extensions/context/summarize-conversation.d.ts +7 -0
- package/dist/extensions/context/summary-generation.d.ts +14 -0
- package/dist/extensions/mcp/apps.d.ts +16 -0
- package/dist/extensions/mcp/client.d.ts +1 -0
- package/dist/extensions/mcp/index.d.ts +5 -1
- package/dist/extensions/mcp/manager.d.ts +2 -1
- package/dist/extensions/mcp/session-apps.d.ts +28 -0
- package/dist/extensions/mcp/types.d.ts +22 -0
- package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
- package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
- package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
- package/dist/hub/client/index.d.ts +6 -0
- package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
- package/dist/hub/client/plugin-commands.d.ts +4 -0
- package/dist/hub/client/session-client.d.ts +2 -0
- package/dist/hub/daemon/entry.js +248 -229
- package/dist/hub/daemon/index.d.ts +2 -0
- package/dist/hub/index.d.ts +1 -0
- package/dist/hub/index.js +238 -219
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
- package/dist/hub/server/cloud-session-service.d.ts +52 -0
- package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
- package/dist/hub/server/handlers/context.d.ts +13 -2
- package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
- package/dist/hub/server/handlers/session-handlers.d.ts +4 -0
- package/dist/hub/server/hub-server-options.d.ts +3 -0
- package/dist/hub/server/hub-server-transport.d.ts +2 -0
- package/dist/index.d.ts +10 -5
- package/dist/index.js +284 -258
- package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
- package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-bdvd54cj.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-d88t4w67.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-4rh6dw0e.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-dex049wz.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +38 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/community-adrseffv.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-vf44v1q1.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-np6pavev.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-1xg0n8py.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-2h2811k3.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-918h9zb6.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-9g9qz8kw.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-8p52y0t4.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-cr4wnstr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-aa72jh2v.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-k2y10eep.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-1hvm2h6v.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-7nqbajdc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/google-nqn5r579.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1166 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1153 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0ahmqye5.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1jwj53tz.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-3qy7846d.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-418gvd4a.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4etvmc8g.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4pm9q9we.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4tgv599k.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5hwscy9s.js +15 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6dpcn5cw.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-7ycwqbm0.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8qjtgvqw.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8zb5grad.js +1210 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-94jdgxt6.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9g67p34k.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-a9d2sjh0.js +85 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-agemt17a.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bhf7enwn.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bnwxdgvg.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-brjxtvsh.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bvb7f701.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bwet95hr.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cadyf2yp.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cxfnnrmh.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cyyvppz9.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d4pbedxj.js +137 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ddwn220p.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-edf1hmcw.js +62 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ejyd73x5.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f25bf131.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f4rfmj6q.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-fet3kwk6.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ffna8yzn.js +121 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-g2y6ptdc.js +213 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ge184xvn.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-gevnedsc.js +13 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkmarmve.js +190 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-kqacxn3s.js +39 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m3gtj35r.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-neczvge6.js +21 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-p5k5hnam.js +75 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sdvqs19c.js +20 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t75m2pgm.js +146 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-qqb2kabr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v6mehmme.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v80fh3x3.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vd605jwp.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vryppqt1.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w55v4n1n.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w9n2kgjk.js +140 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yjbp9r76.js +142 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ztb3cjfh.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-kj4rdeey.js +473 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-y9tt7gmq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-bg81k3qh.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-tkbfbx5w.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-mkw95amh.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-9z19cm6q.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-sjp09b7p.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-1eyn4hw0.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-f99c7syq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-19936r1a.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-eavx3zc3.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-04d0mwe8.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-mt7pvm61.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-6armtc3s.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
- package/dist/plugin-runtime/package.json +1 -0
- package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
- package/dist/remote/remote-environments.d.ts +1 -0
- package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
- package/dist/runtime/host/local-runtime-host.d.ts +10 -0
- package/dist/runtime/host/runtime-host.d.ts +6 -0
- package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
- package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
- package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
- package/dist/services/cloud-handoff/git-preparation.d.ts +22 -0
- package/dist/services/global-settings.d.ts +6 -0
- package/dist/services/llms/cline-recommended-models.d.ts +2 -0
- package/dist/services/local-runtime-bootstrap.d.ts +1 -0
- package/dist/services/plugin-command-api.d.ts +47 -0
- package/dist/services/plugin-commands.d.ts +25 -27
- package/dist/services/skills-cli.d.ts +2 -0
- package/dist/services/telemetry/core-events.d.ts +26 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/telemetry/run-health.d.ts +40 -0
- package/dist/services/telemetry/stall-signals.d.ts +12 -0
- package/dist/types/config.d.ts +1 -0
- package/dist/types/session.d.ts +7 -0
- package/package.json +6 -5
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import{R,Xm,Wr}from"./index-w9n2kgjk.js";import{Mr,fc,Ws}from"./index-a9d2sjh0.js";import{Vf,rp,Dr,lp,ty,fi,ry,sy,cy,ly,uy,ml,py,dy,hl}from"./index-hkmarmve.js";import{sf,cf,Gu,Vu}from"./index-ffna8yzn.js";import{oa,Vw,Kw}from"./index-bhf7enwn.js";import{v,i,Sl,Al,e,zp,n,r,Ht,L,m,o,t,ae,p,w,la,d,s,a,Le,J,je}from"./index-edf1hmcw.js";var br=i(function(Ei){Object.defineProperty(Ei,"__esModule",{value:!0});Ei.regexpCode=Ei.getEsmExportName=Ei.getProperty=Ei.safeStringify=Ei.stringify=Ei.strConcat=Ei.addCodeArg=Ei.str=Ei._=Ei.nil=Ei._Code=Ei.Name=Ei.IDENTIFIER=Ei._CodeOrName=void 0;class vn{}Ei._CodeOrName=vn;Ei.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class jt extends vn{constructor(c){super();if(!Ei.IDENTIFIER.test(c))throw Error("CodeGen: name must be a valid identifier");this.str=c}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}Ei.Name=jt;class Oe extends vn{constructor(c){super();this._items=typeof c==="string"?[c]:c}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let c=this._items[0];return c===""||c==='""'}get str(){var c;return(c=this._str)!==null&&c!==void 0?c:this._str=this._items.reduce((l,u)=>`${l}${u}`,"")}get names(){var c;return(c=this._names)!==null&&c!==void 0?c:this._names=this._items.reduce((l,u)=>{if(u instanceof jt)l[u.str]=(l[u.str]||0)+1;return l},{})}}Ei._Code=Oe;Ei.nil=new Oe("");function bi(c,...l){let u=[c[0]],g=0;while(g<l.length)ps(u,l[g]),u.push(c[++g]);return new Oe(u)}Ei._=bi;var ds=new Oe("+");function Ri(c,...l){let u=[Tr(c[0])],g=0;while(g<l.length)u.push(ds),ps(u,l[g]),u.push(ds,Tr(c[++g]));return dm(u),new Oe(u)}Ei.str=Ri;function ps(c,l){if(l instanceof Oe)c.push(...l._items);else if(l instanceof jt)c.push(l);else c.push(hm(l))}Ei.addCodeArg=ps;function dm(c){let l=1;while(l<c.length-1){if(c[l]===ds){let u=pm(c[l-1],c[l+1]);if(u!==void 0){c.splice(l-1,3,u);continue}c[l++]="+"}l++}}function pm(c,l){if(l==='""')return c;if(c==='""')return l;if(typeof c=="string"){if(l instanceof jt||c[c.length-1]!=='"')return;if(typeof l!="string")return`${c.slice(0,-1)}${l}"`;if(l[0]==='"')return c.slice(0,-1)+l.slice(1);return}if(typeof l=="string"&&l[0]==='"'&&!(c instanceof jt))return`"${c}${l.slice(1)}`;return}function fm(c,l){return l.emptyStr()?c:c.emptyStr()?l:Ri`${c}${l}`}Ei.strConcat=fm;function hm(c){return typeof c=="number"||typeof c=="boolean"||c===null?c:Tr(Array.isArray(c)?c.join(","):c)}function mm(c){return new Oe(Tr(c))}Ei.stringify=mm;function Tr(c){return JSON.stringify(c).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ei.safeStringify=Tr;function gm(c){return typeof c=="string"&&Ei.IDENTIFIER.test(c)?new Oe(`.${c}`):bi`[${c}]`}Ei.getProperty=gm;function _m(c){if(typeof c=="string"&&Ei.IDENTIFIER.test(c))return new Oe(`${c}`);throw Error(`CodeGen: invalid export name: ${c}, use explicit $id name mapping`)}Ei.getEsmExportName=_m;function ym(c){return new Oe(c.toString())}Ei.regexpCode=ym});var gs=i(function($i){Object.defineProperty($i,"__esModule",{value:!0});$i.ValueScope=$i.ValueScopeName=$i.Scope=$i.varKinds=$i.UsedValueState=void 0;var ve=br();class xi extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`);this.value=c.value}}var bn;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(bn||($i.UsedValueState=bn={}));$i.varKinds={const:new ve.Name("const"),let:new ve.Name("let"),var:new ve.Name("var")};class hs{constructor({prefixes:c,parent:l}={}){this._names={},this._prefixes=c,this._parent=l}toName(c){return c instanceof ve.Name?c:this.name(c)}name(c){return new ve.Name(this._newName(c))}_newName(c){let l=this._names[c]||this._nameGroup(c);return`${c}${l.index++}`}_nameGroup(c){var l,u;if(((u=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||u===void 0?void 0:u.has(c))||this._prefixes&&!this._prefixes.has(c))throw Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}$i.Scope=hs;class ms extends ve.Name{constructor(c,l){super(l);this.prefix=c}setValue(c,{property:l,itemIndex:u}){this.value=c,this.scopePath=ve._`.${new ve.Name(l)}[${u}]`}}$i.ValueScopeName=ms;var Cm=ve._`\n`;class ki extends hs{constructor(c){super(c);this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?Cm:ve.nil}}get(){return this._scope}name(c){return new ms(c,this._newName(c))}value(c,l){var u;if(l.ref===void 0)throw Error("CodeGen: ref must be passed in value");let g=this.toName(c),{prefix:_}=g,y=(u=l.key)!==null&&u!==void 0?u:l.ref,T=this._values[_];if(T){let S=T.get(y);if(S)return S}else T=this._values[_]=new Map;T.set(y,g);let b=this._scope[_]||(this._scope[_]=[]),E=b.length;return b[E]=l.ref,g.setValue(l,{property:_,itemIndex:E}),g}getValue(c,l){let u=this._values[c];if(!u)return;return u.get(l)}scopeRefs(c,l=this._values){return this._reduceValues(l,(u)=>{if(u.scopePath===void 0)throw Error(`CodeGen: name "${u}" has no value`);return ve._`${c}${u.scopePath}`})}scopeCode(c=this._values,l,u){return this._reduceValues(c,(g)=>{if(g.value===void 0)throw Error(`CodeGen: name "${g}" has no value`);return g.value.code},l,u)}_reduceValues(c,l,u={},g){let _=ve.nil;for(let y in c){let T=c[y];if(!T)continue;let b=u[y]=u[y]||new Map;T.forEach((E)=>{if(b.has(E))return;b.set(E,bn.Started);let S=l(E);if(S){let k=this.opts.es5?$i.varKinds.var:$i.varKinds.const;_=ve._`${_}${k} ${E} = ${S};${this.opts._n}`}else if(S=g===null||g===void 0?void 0:g(E))_=ve._`${_}${S}${this.opts._n}`;else throw new xi(E);b.set(E,bn.Completed)})}return _}}$i.ValueScope=ki});var B=i(function(Te){Object.defineProperty(Te,"__esModule",{value:!0});Te.or=Te.and=Te.not=Te.CodeGen=Te.operators=Te.varKinds=Te.ValueScopeName=Te.ValueScope=Te.Scope=Te.Name=Te.regexpCode=Te.stringify=Te.getProperty=Te.nil=Te.strConcat=Te.str=Te._=void 0;var Z=br(),Me=gs(),at=br();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return at._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return at.str}});Object.defineProperty(Te,"strConcat",{enumerable:!0,get:function(){return at.strConcat}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return at.nil}});Object.defineProperty(Te,"getProperty",{enumerable:!0,get:function(){return at.getProperty}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return at.stringify}});Object.defineProperty(Te,"regexpCode",{enumerable:!0,get:function(){return at.regexpCode}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return at.Name}});var $n=gs();Object.defineProperty(Te,"Scope",{enumerable:!0,get:function(){return $n.Scope}});Object.defineProperty(Te,"ValueScope",{enumerable:!0,get:function(){return $n.ValueScope}});Object.defineProperty(Te,"ValueScopeName",{enumerable:!0,get:function(){return $n.ValueScopeName}});Object.defineProperty(Te,"varKinds",{enumerable:!0,get:function(){return $n.varKinds}});Te.operators={GT:new Z._Code(">"),GTE:new Z._Code(">="),LT:new Z._Code("<"),LTE:new Z._Code("<="),EQ:new Z._Code("==="),NEQ:new Z._Code("!=="),NOT:new Z._Code("!"),OR:new Z._Code("||"),AND:new Z._Code("&&"),ADD:new Z._Code("+")};class it{optimizeNodes(){return this}optimizeNames(c,l){return this}}class Pi extends it{constructor(c,l,u){super();this.varKind=c,this.name=l,this.rhs=u}render({es5:c,_n:l}){let u=c?Me.varKinds.var:this.varKind,g=this.rhs===void 0?"":` = ${this.rhs}`;return`${u} ${this.name}${g};`+l}optimizeNames(c,l){if(!c[this.name.str])return;if(this.rhs)this.rhs=Ut(this.rhs,c,l);return this}get names(){return this.rhs instanceof Z._CodeOrName?this.rhs.names:{}}}class ws extends it{constructor(c,l,u){super();this.lhs=c,this.rhs=l,this.sideEffects=u}render({_n:c}){return`${this.lhs} = ${this.rhs};`+c}optimizeNames(c,l){if(this.lhs instanceof Z.Name&&!c[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Ut(this.rhs,c,l),this}get names(){let c=this.lhs instanceof Z.Name?{}:{...this.lhs.names};return kn(c,this.rhs)}}class Ci extends ws{constructor(c,l,u,g){super(c,u,g);this.op=l}render({_n:c}){return`${this.lhs} ${this.op}= ${this.rhs};`+c}}class Ii extends it{constructor(c){super();this.label=c,this.names={}}render({_n:c}){return`${this.label}:`+c}}class zi extends it{constructor(c){super();this.label=c,this.names={}}render({_n:c}){return`break${this.label?` ${this.label}`:""};`+c}}class Oi extends it{constructor(c){super();this.error=c}render({_n:c}){return`throw ${this.error};`+c}get names(){return this.error.names}}class Mi extends it{constructor(c){super();this.code=c}render({_n:c}){return`${this.code};`+c}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(c,l){return this.code=Ut(this.code,c,l),this}get names(){return this.code instanceof Z._CodeOrName?this.code.names:{}}}class An extends it{constructor(c=[]){super();this.nodes=c}render(c){return this.nodes.reduce((l,u)=>l+u.render(c),"")}optimizeNodes(){let{nodes:c}=this,l=c.length;while(l--){let u=c[l].optimizeNodes();if(Array.isArray(u))c.splice(l,1,...u);else if(u)c[l]=u;else c.splice(l,1)}return c.length>0?this:void 0}optimizeNames(c,l){let{nodes:u}=this,g=u.length;while(g--){let _=u[g];if(_.optimizeNames(c,l))continue;Mm(c,_.names),u.splice(g,1)}return u.length>0?this:void 0}get names(){return this.nodes.reduce((c,l)=>bt(c,l.names),{})}}class ct extends An{render(c){return"{"+c._n+super.render(c)+"}"+c._n}}class Ni extends An{}class Rr extends ct{}Rr.kind="else";class Ge extends ct{constructor(c,l){super(l);this.condition=c}render(c){let l=`if(${this.condition})`+super.render(c);if(this.else)l+="else "+this.else.render(c);return l}optimizeNodes(){super.optimizeNodes();let c=this.condition;if(c===!0)return this.nodes;let l=this.else;if(l){let u=l.optimizeNodes();l=this.else=Array.isArray(u)?new Rr(u):u}if(l){if(c===!1)return l instanceof Ge?l:l.nodes;if(this.nodes.length)return this;return new Ge(Ui(c),l instanceof Ge?[l]:l.nodes)}if(c===!1||!this.nodes.length)return;return this}optimizeNames(c,l){var u;if(this.else=(u=this.else)===null||u===void 0?void 0:u.optimizeNames(c,l),!(super.optimizeNames(c,l)||this.else))return;return this.condition=Ut(this.condition,c,l),this}get names(){let c=super.names;if(kn(c,this.condition),this.else)bt(c,this.else.names);return c}}Ge.kind="if";class Lt extends ct{}Lt.kind="for";class qi extends Lt{constructor(c){super();this.iteration=c}render(c){return`for(${this.iteration})`+super.render(c)}optimizeNames(c,l){if(!super.optimizeNames(c,l))return;return this.iteration=Ut(this.iteration,c,l),this}get names(){return bt(super.names,this.iteration.names)}}class Di extends Lt{constructor(c,l,u,g){super();this.varKind=c,this.name=l,this.from=u,this.to=g}render(c){let l=c.es5?Me.varKinds.var:this.varKind,{name:u,from:g,to:_}=this;return`for(${l} ${u}=${g}; ${u}<${_}; ${u}++)`+super.render(c)}get names(){let c=kn(super.names,this.from);return kn(c,this.to)}}class _s extends Lt{constructor(c,l,u,g){super();this.loop=c,this.varKind=l,this.name=u,this.iterable=g}render(c){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(c)}optimizeNames(c,l){if(!super.optimizeNames(c,l))return;return this.iterable=Ut(this.iterable,c,l),this}get names(){return bt(super.names,this.iterable.names)}}class Rn extends ct{constructor(c,l,u){super();this.name=c,this.args=l,this.async=u}render(c){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(c)}}Rn.kind="func";class En extends An{render(c){return"return "+super.render(c)}}En.kind="return";class ji extends ct{render(c){let l="try"+super.render(c);if(this.catch)l+=this.catch.render(c);if(this.finally)l+=this.finally.render(c);return l}optimizeNodes(){var c,l;return super.optimizeNodes(),(c=this.catch)===null||c===void 0||c.optimizeNodes(),(l=this.finally)===null||l===void 0||l.optimizeNodes(),this}optimizeNames(c,l){var u,g;return super.optimizeNames(c,l),(u=this.catch)===null||u===void 0||u.optimizeNames(c,l),(g=this.finally)===null||g===void 0||g.optimizeNames(c,l),this}get names(){let c=super.names;if(this.catch)bt(c,this.catch.names);if(this.finally)bt(c,this.finally.names);return c}}class Sn extends ct{constructor(c){super();this.error=c}render(c){return`catch(${this.error})`+super.render(c)}}Sn.kind="catch";class xn extends ct{render(c){return"finally"+super.render(c)}}xn.kind="finally";class Li{constructor(c,l={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...l,_n:l.lines?`
|
|
2
|
+
`:""},this._extScope=c,this._scope=new Me.Scope({parent:c}),this._nodes=[new Ni]}toString(){return this._root.render(this.opts)}name(c){return this._scope.name(c)}scopeName(c){return this._extScope.name(c)}scopeValue(c,l){let u=this._extScope.value(c,l);return(this._values[u.prefix]||(this._values[u.prefix]=new Set)).add(u),u}getScopeValue(c,l){return this._extScope.getValue(c,l)}scopeRefs(c){return this._extScope.scopeRefs(c,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(c,l,u,g){let _=this._scope.toName(l);if(u!==void 0&&g)this._constants[_.str]=u;return this._leafNode(new Pi(c,_,u)),_}const(c,l,u){return this._def(Me.varKinds.const,c,l,u)}let(c,l,u){return this._def(Me.varKinds.let,c,l,u)}var(c,l,u){return this._def(Me.varKinds.var,c,l,u)}assign(c,l,u){return this._leafNode(new ws(c,l,u))}add(c,l){return this._leafNode(new Ci(c,Te.operators.ADD,l))}code(c){if(typeof c=="function")c();else if(c!==Z.nil)this._leafNode(new Mi(c));return this}object(...c){let l=["{"];for(let[u,g]of c){if(l.length>1)l.push(",");if(l.push(u),u!==g||this.opts.es5)l.push(":"),Z.addCodeArg(l,g)}return l.push("}"),new Z._Code(l)}if(c,l,u){if(this._blockNode(new Ge(c)),l&&u)this.code(l).else().code(u).endIf();else if(l)this.code(l).endIf();else if(u)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(c){return this._elseNode(new Ge(c))}else(){return this._elseNode(new Rr)}endIf(){return this._endBlockNode(Ge,Rr)}_for(c,l){if(this._blockNode(c),l)this.code(l).endFor();return this}for(c,l){return this._for(new qi(c),l)}forRange(c,l,u,g,_=this.opts.es5?Me.varKinds.var:Me.varKinds.let){let y=this._scope.toName(c);return this._for(new Di(_,y,l,u),()=>g(y))}forOf(c,l,u,g=Me.varKinds.const){let _=this._scope.toName(c);if(this.opts.es5){let y=l instanceof Z.Name?l:this.var("_arr",l);return this.forRange("_i",0,Z._`${y}.length`,(T)=>{this.var(_,Z._`${y}[${T}]`),u(_)})}return this._for(new _s("of",g,_,l),()=>u(_))}forIn(c,l,u,g=this.opts.es5?Me.varKinds.var:Me.varKinds.const){if(this.opts.ownProperties)return this.forOf(c,Z._`Object.keys(${l})`,u);let _=this._scope.toName(c);return this._for(new _s("in",g,_,l),()=>u(_))}endFor(){return this._endBlockNode(Lt)}label(c){return this._leafNode(new Ii(c))}break(c){return this._leafNode(new zi(c))}return(c){let l=new En;if(this._blockNode(l),this.code(c),l.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(En)}try(c,l,u){if(!l&&!u)throw Error('CodeGen: "try" without "catch" and "finally"');let g=new ji;if(this._blockNode(g),this.code(c),l){let _=this.name("e");this._currNode=g.catch=new Sn(_),l(_)}if(u)this._currNode=g.finally=new xn,this.code(u);return this._endBlockNode(Sn,xn)}throw(c){return this._leafNode(new Oi(c))}block(c,l){if(this._blockStarts.push(this._nodes.length),c)this.code(c).endBlock(l);return this}endBlock(c){let l=this._blockStarts.pop();if(l===void 0)throw Error("CodeGen: not in self-balancing block");let u=this._nodes.length-l;if(u<0||c!==void 0&&u!==c)throw Error(`CodeGen: wrong number of nodes: ${u} vs ${c} expected`);return this._nodes.length=l,this}func(c,l=Z.nil,u,g){if(this._blockNode(new Rn(c,l,u)),g)this.code(g).endFunc();return this}endFunc(){return this._endBlockNode(Rn)}optimize(c=1){while(c-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(c){return this._currNode.nodes.push(c),this}_blockNode(c){this._currNode.nodes.push(c),this._nodes.push(c)}_endBlockNode(c,l){let u=this._currNode;if(u instanceof c||l&&u instanceof l)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${l?`${c.kind}/${l.kind}`:c.kind}"`)}_elseNode(c){let l=this._currNode;if(!(l instanceof Ge))throw Error('CodeGen: "else" without "if"');return this._currNode=l.else=c,this}get _root(){return this._nodes[0]}get _currNode(){let c=this._nodes;return c[c.length-1]}set _currNode(c){let l=this._nodes;l[l.length-1]=c}}Te.CodeGen=Li;function bt(c,l){for(let u in l)c[u]=(c[u]||0)+(l[u]||0);return c}function kn(c,l){return l instanceof Z._CodeOrName?bt(c,l.names):c}function Ut(c,l,u){if(c instanceof Z.Name)return g(c);if(!_(c))return c;return new Z._Code(c._items.reduce((y,T)=>{if(T instanceof Z.Name)T=g(T);if(T instanceof Z._Code)y.push(...T._items);else y.push(T);return y},[]));function g(y){let T=u[y.str];if(T===void 0||l[y.str]!==1)return y;return delete l[y.str],T}function _(y){return y instanceof Z._Code&&y._items.some((T)=>T instanceof Z.Name&&l[T.str]===1&&u[T.str]!==void 0)}}function Mm(c,l){for(let u in l)c[u]=(c[u]||0)-(l[u]||0)}function Ui(c){return typeof c=="boolean"||typeof c=="number"||c===null?!c:Z._`!${ys(c)}`}Te.not=Ui;var Nm=Fi(Te.operators.AND);function qm(...c){return c.reduce(Nm)}Te.and=qm;var Dm=Fi(Te.operators.OR);function jm(...c){return c.reduce(Dm)}Te.or=jm;function Fi(c){return(l,u)=>l===Z.nil?u:u===Z.nil?l:Z._`${ys(l)} ${c} ${ys(u)}`}function ys(c){return c instanceof Z.Name?c:Z._`(${c})`}});var X=i(function(Ji){Object.defineProperty(Ji,"__esModule",{value:!0});Ji.checkStrictMode=Ji.getErrorPath=Ji.Type=Ji.useFunc=Ji.setEvaluated=Ji.evaluatedPropsToName=Ji.mergeEvaluated=Ji.eachItem=Ji.unescapeJsonPointer=Ji.escapeJsonPointer=Ji.escapeFragment=Ji.unescapeFragment=Ji.schemaRefOrVal=Ji.schemaHasRulesButRef=Ji.schemaHasRules=Ji.checkUnknownRules=Ji.alwaysValidSchema=Ji.toHash=void 0;var te=B(),Hm=br();function Vm(c){let l={};for(let u of c)l[u]=!0;return l}Ji.toHash=Vm;function Wm(c,l){if(typeof l=="boolean")return l;if(Object.keys(l).length===0)return!0;return Ki(c,l),!Bi(l,c.self.RULES.all)}Ji.alwaysValidSchema=Wm;function Ki(c,l=c.schema){let{opts:u,self:g}=c;if(!u.strictSchema)return;if(typeof l==="boolean")return;let _=g.RULES.keywords;for(let y in l)if(!_[y])Xi(c,`unknown keyword: "${y}"`)}Ji.checkUnknownRules=Ki;function Bi(c,l){if(typeof c=="boolean")return!c;for(let u in c)if(l[u])return!0;return!1}Ji.schemaHasRules=Bi;function Km(c,l){if(typeof c=="boolean")return!c;for(let u in c)if(u!=="$ref"&&l.all[u])return!0;return!1}Ji.schemaHasRulesButRef=Km;function Bm({topSchemaRef:c,schemaPath:l},u,g,_){if(!_){if(typeof u=="number"||typeof u=="boolean")return u;if(typeof u=="string")return te._`${u}`}return te._`${c}${l}${te.getProperty(g)}`}Ji.schemaRefOrVal=Bm;function Gm(c){return Gi(decodeURIComponent(c))}Ji.unescapeFragment=Gm;function Zm(c){return encodeURIComponent(Ts(c))}Ji.escapeFragment=Zm;function Ts(c){if(typeof c=="number")return`${c}`;return c.replace(/~/g,"~0").replace(/\//g,"~1")}Ji.escapeJsonPointer=Ts;function Gi(c){return c.replace(/~1/g,"/").replace(/~0/g,"~")}Ji.unescapeJsonPointer=Gi;function Jm(c,l){if(Array.isArray(c))for(let u of c)l(u);else l(c)}Ji.eachItem=Jm;function Vi({mergeNames:c,mergeToName:l,mergeValues:u,resultToName:g}){return(_,y,T,b)=>{let E=T===void 0?y:T instanceof te.Name?(y instanceof te.Name?c(_,y,T):l(_,y,T),T):y instanceof te.Name?(l(_,T,y),y):u(y,T);return b===te.Name&&!(E instanceof te.Name)?g(_,E):E}}Ji.mergeEvaluated={props:Vi({mergeNames:(c,l,u)=>c.if(te._`${u} !== true && ${l} !== undefined`,()=>{c.if(te._`${l} === true`,()=>c.assign(u,!0),()=>c.assign(u,te._`${u} || {}`).code(te._`Object.assign(${u}, ${l})`))}),mergeToName:(c,l,u)=>c.if(te._`${u} !== true`,()=>{if(l===!0)c.assign(u,!0);else c.assign(u,te._`${u} || {}`),bs(c,u,l)}),mergeValues:(c,l)=>c===!0?!0:{...c,...l},resultToName:Zi}),items:Vi({mergeNames:(c,l,u)=>c.if(te._`${u} !== true && ${l} !== undefined`,()=>c.assign(u,te._`${l} === true ? true : ${u} > ${l} ? ${u} : ${l}`)),mergeToName:(c,l,u)=>c.if(te._`${u} !== true`,()=>c.assign(u,l===!0?!0:te._`${u} > ${l} ? ${u} : ${l}`)),mergeValues:(c,l)=>c===!0?!0:Math.max(c,l),resultToName:(c,l)=>c.var("items",l)})};function Zi(c,l){if(l===!0)return c.var("props",!0);let u=c.var("props",te._`{}`);if(l!==void 0)bs(c,u,l);return u}Ji.evaluatedPropsToName=Zi;function bs(c,l,u){Object.keys(u).forEach((g)=>c.assign(te._`${l}${te.getProperty(g)}`,!0))}Ji.setEvaluated=bs;var Wi={};function Ym(c,l){return c.scopeValue("func",{ref:l,code:Wi[l.code]||(Wi[l.code]=new Hm._Code(l.code))})}Ji.useFunc=Ym;var vs;(function(c){c[c.Num=0]="Num",c[c.Str=1]="Str"})(vs||(Ji.Type=vs={}));function Qm(c,l,u){if(c instanceof te.Name){let g=l===vs.Num;return u?g?te._`"[" + ${c} + "]"`:te._`"['" + ${c} + "']"`:g?te._`"/" + ${c}`:te._`"/" + ${c}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return u?te.getProperty(c).toString():"/"+Ts(c)}Ji.getErrorPath=Qm;function Xi(c,l,u=c.opts.strictSchema){if(!u)return;if(l=`strict mode: ${l}`,u===!0)throw Error(l);c.self.logger.warn(l)}Ji.checkStrictMode=Xi});var Ze=i(function(Qi){Object.defineProperty(Qi,"__esModule",{value:!0});var ge=B(),_g={data:new ge.Name("data"),valCxt:new ge.Name("valCxt"),instancePath:new ge.Name("instancePath"),parentData:new ge.Name("parentData"),parentDataProperty:new ge.Name("parentDataProperty"),rootData:new ge.Name("rootData"),dynamicAnchors:new ge.Name("dynamicAnchors"),vErrors:new ge.Name("vErrors"),errors:new ge.Name("errors"),this:new ge.Name("this"),self:new ge.Name("self"),scope:new ge.Name("scope"),json:new ge.Name("json"),jsonPos:new ge.Name("jsonPos"),jsonLen:new ge.Name("jsonLen"),jsonPart:new ge.Name("jsonPart")};Qi.default=_g});var Er=i(function(nc){Object.defineProperty(nc,"__esModule",{value:!0});nc.extendErrors=nc.resetErrorsCount=nc.reportExtraError=nc.reportError=nc.keyword$DataError=nc.keywordError=void 0;var Q=B(),In=X(),ye=Ze();nc.keywordError={message:({keyword:c})=>Q.str`must pass "${c}" keyword validation`};nc.keyword$DataError={message:({keyword:c,schemaType:l})=>l?Q.str`"${c}" keyword must be ${l} ($data)`:Q.str`"${c}" keyword is invalid ($data)`};function wg(c,l=nc.keywordError,u,g){let{it:_}=c,{gen:y,compositeRule:T,allErrors:b}=_,E=rc(c,l,u);if(g!==null&&g!==void 0?g:T||b)ec(y,E);else tc(_,Q._`[${E}]`)}nc.reportError=wg;function vg(c,l=nc.keywordError,u){let{it:g}=c,{gen:_,compositeRule:y,allErrors:T}=g,b=rc(c,l,u);if(ec(_,b),!(y||T))tc(g,ye.default.vErrors)}nc.reportExtraError=vg;function Tg(c,l){c.assign(ye.default.errors,l),c.if(Q._`${ye.default.vErrors} !== null`,()=>c.if(l,()=>c.assign(Q._`${ye.default.vErrors}.length`,l),()=>c.assign(ye.default.vErrors,null)))}nc.resetErrorsCount=Tg;function bg({gen:c,keyword:l,schemaValue:u,data:g,errsCount:_,it:y}){if(_===void 0)throw Error("ajv implementation error");let T=c.name("err");c.forRange("i",_,ye.default.errors,(b)=>{if(c.const(T,Q._`${ye.default.vErrors}[${b}]`),c.if(Q._`${T}.instancePath === undefined`,()=>c.assign(Q._`${T}.instancePath`,Q.strConcat(ye.default.instancePath,y.errorPath))),c.assign(Q._`${T}.schemaPath`,Q.str`${y.errSchemaPath}/${l}`),y.opts.verbose)c.assign(Q._`${T}.schema`,u),c.assign(Q._`${T}.data`,g)})}nc.extendErrors=bg;function ec(c,l){let u=c.const("err",l);c.if(Q._`${ye.default.vErrors} === null`,()=>c.assign(ye.default.vErrors,Q._`[${u}]`),Q._`${ye.default.vErrors}.push(${u})`),c.code(Q._`${ye.default.errors}++`)}function tc(c,l){let{gen:u,validateName:g,schemaEnv:_}=c;if(_.$async)u.throw(Q._`new ${c.ValidationError}(${l})`);else u.assign(Q._`${g}.errors`,l),u.return(!1)}var Rt={keyword:new Q.Name("keyword"),schemaPath:new Q.Name("schemaPath"),params:new Q.Name("params"),propertyName:new Q.Name("propertyName"),message:new Q.Name("message"),schema:new Q.Name("schema"),parentSchema:new Q.Name("parentSchema")};function rc(c,l,u){let{createErrors:g}=c.it;if(g===!1)return Q._`{}`;return Rg(c,l,u)}function Rg(c,l,u={}){let{gen:g,it:_}=c,y=[Eg(_,u),Sg(c,u)];return xg(c,l,y),g.object(...y)}function Eg({errorPath:c},{instancePath:l}){let u=l?Q.str`${c}${In.getErrorPath(l,In.Type.Str)}`:c;return[ye.default.instancePath,Q.strConcat(ye.default.instancePath,u)]}function Sg({keyword:c,it:{errSchemaPath:l}},{schemaPath:u,parentSchema:g}){let _=g?l:Q.str`${l}/${c}`;if(u)_=Q.str`${_}${In.getErrorPath(u,In.Type.Str)}`;return[Rt.schemaPath,_]}function xg(c,{params:l,message:u},g){let{keyword:_,data:y,schemaValue:T,it:b}=c,{opts:E,propertyName:S,topSchemaRef:k,schemaPath:A}=b;if(g.push([Rt.keyword,_],[Rt.params,typeof l=="function"?l(c):l||Q._`{}`]),E.messages)g.push([Rt.message,typeof u=="function"?u(c):u]);if(E.verbose)g.push([Rt.schema,T],[Rt.parentSchema,Q._`${k}${A}`],[ye.default.data,y]);if(S)g.push([Rt.propertyName,S])}});var cc=i(function(ac){Object.defineProperty(ac,"__esModule",{value:!0});ac.boolOrEmptySchema=ac.topBoolOrEmptySchema=void 0;var Cg=Er(),Ig=B(),zg=Ze(),Og={message:"boolean schema is false"};function Mg(c){let{gen:l,schema:u,validateName:g}=c;if(u===!1)sc(c,!1);else if(typeof u=="object"&&u.$async===!0)l.return(zg.default.data);else l.assign(Ig._`${g}.errors`,null),l.return(!0)}ac.topBoolOrEmptySchema=Mg;function Ng(c,l){let{gen:u,schema:g}=c;if(g===!1)u.var(l,!1),sc(c);else u.var(l,!0)}ac.boolOrEmptySchema=Ng;function sc(c,l){let{gen:u,data:g}=c;Cg.reportError({gen:u,keyword:"false schema",data:g,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c},Og,void 0,l)}});var Es=i(function(lc){Object.defineProperty(lc,"__esModule",{value:!0});lc.getRules=lc.isJSONType=void 0;var Dg=["string","number","integer","boolean","null","object","array"],jg=new Set(Dg);function Lg(c){return typeof c=="string"&&jg.has(c)}lc.isJSONType=Lg;function Ug(){let c={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...c,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},c.number,c.string,c.array,c.object],post:{rules:[]},all:{},keywords:{}}}lc.getRules=Ug});var Ss=i(function(mc){Object.defineProperty(mc,"__esModule",{value:!0});mc.shouldUseRule=mc.shouldUseGroup=mc.schemaHasRulesForType=void 0;function Hg({schema:c,self:l},u){let g=l.RULES.types[u];return g&&g!==!0&&dc(c,g)}mc.schemaHasRulesForType=Hg;function dc(c,l){return l.rules.some((u)=>hc(c,u))}mc.shouldUseGroup=dc;function hc(c,l){var u;return c[l.keyword]!==void 0||((u=l.definition.implements)===null||u===void 0?void 0:u.some((g)=>c[g]!==void 0))}mc.shouldUseRule=hc});var Sr=i(function(vc){Object.defineProperty(vc,"__esModule",{value:!0});vc.reportTypeError=vc.checkDataTypes=vc.checkDataType=vc.coerceAndCheckDataType=vc.getJSONTypes=vc.getSchemaTypes=vc.DataType=void 0;var Kg=Es(),Bg=Ss(),Gg=Er(),K=B(),_c=X(),Ft;(function(c){c[c.Correct=0]="Correct",c[c.Wrong=1]="Wrong"})(Ft||(vc.DataType=Ft={}));function Zg(c){let l=yc(c.type);if(l.includes("null")){if(c.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!l.length&&c.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(c.nullable===!0)l.push("null")}return l}vc.getSchemaTypes=Zg;function yc(c){let l=Array.isArray(c)?c:c?[c]:[];if(l.every(Kg.isJSONType))return l;throw Error("type must be JSONType or JSONType[]: "+l.join(","))}vc.getJSONTypes=yc;function Xg(c,l){let{gen:u,data:g,opts:_}=c,y=Jg(l,_.coerceTypes),T=l.length>0&&!(y.length===0&&l.length===1&&Bg.schemaHasRulesForType(c,l[0]));if(T){let b=ks(l,g,_.strictNumbers,Ft.Wrong);u.if(b,()=>{if(y.length)Yg(c,l,y);else $s(c)})}return T}vc.coerceAndCheckDataType=Xg;var wc=new Set(["string","number","integer","boolean","null"]);function Jg(c,l){return l?c.filter((u)=>wc.has(u)||l==="array"&&u==="array"):[]}function Yg(c,l,u){let{gen:g,data:_,opts:y}=c,T=g.let("dataType",K._`typeof ${_}`),b=g.let("coerced",K._`undefined`);if(y.coerceTypes==="array")g.if(K._`${T} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>g.assign(_,K._`${_}[0]`).assign(T,K._`typeof ${_}`).if(ks(l,_,y.strictNumbers),()=>g.assign(b,_)));g.if(K._`${b} !== undefined`);for(let S of u)if(wc.has(S)||S==="array"&&y.coerceTypes==="array")E(S);g.else(),$s(c),g.endIf(),g.if(K._`${b} !== undefined`,()=>{g.assign(_,b),Qg(c,b)});function E(S){switch(S){case"string":g.elseIf(K._`${T} == "number" || ${T} == "boolean"`).assign(b,K._`"" + ${_}`).elseIf(K._`${_} === null`).assign(b,K._`""`);return;case"number":g.elseIf(K._`${T} == "boolean" || ${_} === null
|
|
3
|
+
|| (${T} == "string" && ${_} && ${_} == +${_})`).assign(b,K._`+${_}`);return;case"integer":g.elseIf(K._`${T} === "boolean" || ${_} === null
|
|
4
|
+
|| (${T} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(b,K._`+${_}`);return;case"boolean":g.elseIf(K._`${_} === "false" || ${_} === 0 || ${_} === null`).assign(b,!1).elseIf(K._`${_} === "true" || ${_} === 1`).assign(b,!0);return;case"null":g.elseIf(K._`${_} === "" || ${_} === 0 || ${_} === false`),g.assign(b,null);return;case"array":g.elseIf(K._`${T} === "string" || ${T} === "number"
|
|
5
|
+
|| ${T} === "boolean" || ${_} === null`).assign(b,K._`[${_}]`)}}}function Qg({gen:c,parentData:l,parentDataProperty:u},g){c.if(K._`${l} !== undefined`,()=>c.assign(K._`${l}[${u}]`,g))}function xs(c,l,u,g=Ft.Correct){let _=g===Ft.Correct?K.operators.EQ:K.operators.NEQ,y;switch(c){case"null":return K._`${l} ${_} null`;case"array":y=K._`Array.isArray(${l})`;break;case"object":y=K._`${l} && typeof ${l} == "object" && !Array.isArray(${l})`;break;case"integer":y=T(K._`!(${l} % 1) && !isNaN(${l})`);break;case"number":y=T();break;default:return K._`typeof ${l} ${_} ${c}`}return g===Ft.Correct?y:K.not(y);function T(b=K.nil){return K.and(K._`typeof ${l} == "number"`,b,u?K._`isFinite(${l})`:K.nil)}}vc.checkDataType=xs;function ks(c,l,u,g){if(c.length===1)return xs(c[0],l,u,g);let _,y=_c.toHash(c);if(y.array&&y.object){let T=K._`typeof ${l} != "object"`;_=y.null?T:K._`!${l} || ${T}`,delete y.null,delete y.array,delete y.object}else _=K.nil;if(y.number)delete y.integer;for(let T in y)_=K.and(_,xs(T,l,u,g));return _}vc.checkDataTypes=ks;var e_={message:({schema:c})=>`must be ${c}`,params:({schema:c,schemaValue:l})=>typeof c=="string"?K._`{type: ${c}}`:K._`{type: ${l}}`};function $s(c){let l=t_(c);Gg.reportError(l,e_)}vc.reportTypeError=$s;function t_(c){let{gen:l,data:u,schema:g}=c,_=_c.schemaRefOrVal(c,g,"type");return{gen:l,keyword:"type",data:u,schema:g.type,schemaCode:_,schemaValue:_,parentSchema:g,params:{},it:c}}});var Sc=i(function(Rc){Object.defineProperty(Rc,"__esModule",{value:!0});Rc.assignDefaults=void 0;var Vt=B(),c_=X();function l_(c,l){let{properties:u,items:g}=c.schema;if(l==="object"&&u)for(let _ in u)bc(c,_,u[_].default);else if(l==="array"&&Array.isArray(g))g.forEach((_,y)=>bc(c,y,_.default))}Rc.assignDefaults=l_;function bc(c,l,u){let{gen:g,compositeRule:_,data:y,opts:T}=c;if(u===void 0)return;let b=Vt._`${y}${Vt.getProperty(l)}`;if(_){c_.checkStrictMode(c,`default is ignored for: ${b}`);return}let E=Vt._`${b} === undefined`;if(T.useDefaults==="empty")E=Vt._`${E} || ${b} === null || ${b} === ""`;g.if(E,Vt._`${b} = ${Vt.stringify(u)}`)}});var Pe=i(function($c){Object.defineProperty($c,"__esModule",{value:!0});$c.validateUnion=$c.validateArray=$c.usePattern=$c.callValidateCode=$c.schemaProperties=$c.allSchemaProperties=$c.noPropertyInData=$c.propertyInData=$c.isOwnProperty=$c.hasPropFunc=$c.reportMissingProp=$c.checkMissingProp=$c.checkReportMissingProp=void 0;var re=B(),As=X(),lt=Ze(),u_=X();function d_(c,l){let{gen:u,data:g,it:_}=c;u.if(Cs(u,g,l,_.opts.ownProperties),()=>{c.setParams({missingProperty:re._`${l}`},!0),c.error()})}$c.checkReportMissingProp=d_;function p_({gen:c,data:l,it:{opts:u}},g,_){return re.or(...g.map((y)=>re.and(Cs(c,l,y,u.ownProperties),re._`${_} = ${y}`)))}$c.checkMissingProp=p_;function f_(c,l){c.setParams({missingProperty:l},!0),c.error()}$c.reportMissingProp=f_;function xc(c){return c.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:re._`Object.prototype.hasOwnProperty`})}$c.hasPropFunc=xc;function Ps(c,l,u){return re._`${xc(c)}.call(${l}, ${u})`}$c.isOwnProperty=Ps;function h_(c,l,u,g){let _=re._`${l}${re.getProperty(u)} !== undefined`;return g?re._`${_} && ${Ps(c,l,u)}`:_}$c.propertyInData=h_;function Cs(c,l,u,g){let _=re._`${l}${re.getProperty(u)} === undefined`;return g?re.or(_,re.not(Ps(c,l,u))):_}$c.noPropertyInData=Cs;function kc(c){return c?Object.keys(c).filter((l)=>l!=="__proto__"):[]}$c.allSchemaProperties=kc;function m_(c,l){return kc(l).filter((u)=>!As.alwaysValidSchema(c,l[u]))}$c.schemaProperties=m_;function g_({schemaCode:c,data:l,it:{gen:u,topSchemaRef:g,schemaPath:_,errorPath:y},it:T},b,E,S){let k=S?re._`${c}, ${l}, ${g}${_}`:l,A=[[lt.default.instancePath,re.strConcat(lt.default.instancePath,y)],[lt.default.parentData,T.parentData],[lt.default.parentDataProperty,T.parentDataProperty],[lt.default.rootData,lt.default.rootData]];if(T.opts.dynamicRef)A.push([lt.default.dynamicAnchors,lt.default.dynamicAnchors]);let z=re._`${k}, ${u.object(...A)}`;return E!==re.nil?re._`${b}.call(${E}, ${z})`:re._`${b}(${z})`}$c.callValidateCode=g_;var __=re._`new RegExp`;function y_({gen:c,it:{opts:l}},u){let g=l.unicodeRegExp?"u":"",{regExp:_}=l.code,y=_(u,g);return c.scopeValue("pattern",{key:y.toString(),ref:y,code:re._`${_.code==="new RegExp"?__:u_.useFunc(c,_)}(${u}, ${g})`})}$c.usePattern=y_;function w_(c){let{gen:l,data:u,keyword:g,it:_}=c,y=l.name("valid");if(_.allErrors){let b=l.let("valid",!0);return T(()=>l.assign(b,!1)),b}return l.var(y,!0),T(()=>l.break()),y;function T(b){let E=l.const("len",re._`${u}.length`);l.forRange("i",0,E,(S)=>{c.subschema({keyword:g,dataProp:S,dataPropType:As.Type.Num},y),l.if(re.not(y),b)})}}$c.validateArray=w_;function v_(c){let{gen:l,schema:u,keyword:g,it:_}=c;if(!Array.isArray(u))throw Error("ajv implementation error");if(u.some((E)=>As.alwaysValidSchema(_,E))&&!_.opts.unevaluated)return;let T=l.let("valid",!1),b=l.name("_valid");l.block(()=>u.forEach((E,S)=>{let k=c.subschema({keyword:g,schemaProp:S,compositeRule:!0},b);if(l.assign(T,re._`${T} || ${b}`),!c.mergeValidEvaluated(k,b))l.if(re.not(T))})),c.result(T,()=>c.reset(),()=>c.error(!0))}$c.validateUnion=v_});var Oc=i(function(Ic){Object.defineProperty(Ic,"__esModule",{value:!0});Ic.validateKeywordUsage=Ic.validSchemaType=Ic.funcKeywordCode=Ic.macroKeywordCode=void 0;var we=B(),Et=Ze(),z_=Pe(),O_=Er();function M_(c,l){let{gen:u,keyword:g,schema:_,parentSchema:y,it:T}=c,b=l.macro.call(T.self,_,y,T),E=Cc(u,g,b);if(T.opts.validateSchema!==!1)T.self.validateSchema(b,!0);let S=u.name("valid");c.subschema({schema:b,schemaPath:we.nil,errSchemaPath:`${T.errSchemaPath}/${g}`,topSchemaRef:E,compositeRule:!0},S),c.pass(S,()=>c.error(!0))}Ic.macroKeywordCode=M_;function N_(c,l){var u;let{gen:g,keyword:_,schema:y,parentSchema:T,$data:b,it:E}=c;D_(E,l);let S=!b&&l.compile?l.compile.call(E.self,y,T,E):l.validate,k=Cc(g,_,S),A=g.let("valid");c.block$data(A,z),c.ok((u=l.valid)!==null&&u!==void 0?u:A);function z(){if(l.errors===!1){if(I(),l.modifying)Pc(c);M(()=>c.error())}else{let N=l.async?C():P();if(l.modifying)Pc(c);M(()=>q_(c,N))}}function C(){let N=g.let("ruleErrs",null);return g.try(()=>I(we._`await `),(D)=>g.assign(A,!1).if(we._`${D} instanceof ${E.ValidationError}`,()=>g.assign(N,we._`${D}.errors`),()=>g.throw(D))),N}function P(){let N=we._`${k}.errors`;return g.assign(N,null),I(we.nil),N}function I(N=l.async?we._`await `:we.nil){let D=E.opts.passContext?Et.default.this:Et.default.self,U=!(("compile"in l)&&!b||l.schema===!1);g.assign(A,we._`${N}${z_.callValidateCode(c,k,D,U)}`,l.modifying)}function M(N){var D;g.if(we.not((D=l.valid)!==null&&D!==void 0?D:A),N)}}Ic.funcKeywordCode=N_;function Pc(c){let{gen:l,data:u,it:g}=c;l.if(g.parentData,()=>l.assign(u,we._`${g.parentData}[${g.parentDataProperty}]`))}function q_(c,l){let{gen:u}=c;u.if(we._`Array.isArray(${l})`,()=>{u.assign(Et.default.vErrors,we._`${Et.default.vErrors} === null ? ${l} : ${Et.default.vErrors}.concat(${l})`).assign(Et.default.errors,we._`${Et.default.vErrors}.length`),O_.extendErrors(c)},()=>c.error())}function D_({schemaEnv:c},l){if(l.async&&!c.$async)throw Error("async keyword in sync schema")}function Cc(c,l,u){if(u===void 0)throw Error(`keyword "${l}" failed to compile`);return c.scopeValue("keyword",typeof u=="function"?{ref:u}:{ref:u,code:we.stringify(u)})}function j_(c,l,u=!1){return!l.length||l.some((g)=>g==="array"?Array.isArray(c):g==="object"?c&&typeof c=="object"&&!Array.isArray(c):typeof c==g||u&&typeof c>"u")}Ic.validSchemaType=j_;function L_({schema:c,opts:l,self:u,errSchemaPath:g},_,y){if(Array.isArray(_.keyword)?!_.keyword.includes(y):_.keyword!==y)throw Error("ajv implementation error");let T=_.dependencies;if(T===null||T===void 0?void 0:T.some((b)=>!Object.prototype.hasOwnProperty.call(c,b)))throw Error(`parent schema must have dependencies of ${y}: ${T.join(",")}`);if(_.validateSchema){if(!_.validateSchema(c[y])){let E=`keyword "${y}" value is invalid at path "${g}": `+u.errorsText(_.validateSchema.errors);if(l.validateSchema==="log")u.logger.error(E);else throw Error(E)}}}Ic.validateKeywordUsage=L_});var Dc=i(function(Nc){Object.defineProperty(Nc,"__esModule",{value:!0});Nc.extendSubschemaMode=Nc.extendSubschemaData=Nc.getSubschema=void 0;var He=B(),Mc=X();function V_(c,{keyword:l,schemaProp:u,schema:g,schemaPath:_,errSchemaPath:y,topSchemaRef:T}){if(l!==void 0&&g!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(l!==void 0){let b=c.schema[l];return u===void 0?{schema:b,schemaPath:He._`${c.schemaPath}${He.getProperty(l)}`,errSchemaPath:`${c.errSchemaPath}/${l}`}:{schema:b[u],schemaPath:He._`${c.schemaPath}${He.getProperty(l)}${He.getProperty(u)}`,errSchemaPath:`${c.errSchemaPath}/${l}/${Mc.escapeFragment(u)}`}}if(g!==void 0){if(_===void 0||y===void 0||T===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:g,schemaPath:_,topSchemaRef:T,errSchemaPath:y}}throw Error('either "keyword" or "schema" must be passed')}Nc.getSubschema=V_;function W_(c,l,{dataProp:u,dataPropType:g,data:_,dataTypes:y,propertyName:T}){if(_!==void 0&&u!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:b}=l;if(u!==void 0){let{errorPath:S,dataPathArr:k,opts:A}=l,z=b.let("data",He._`${l.data}${He.getProperty(u)}`,!0);E(z),c.errorPath=He.str`${S}${Mc.getErrorPath(u,g,A.jsPropertySyntax)}`,c.parentDataProperty=He._`${u}`,c.dataPathArr=[...k,c.parentDataProperty]}if(_!==void 0){let S=_ instanceof He.Name?_:b.let("data",_,!0);if(E(S),T!==void 0)c.propertyName=T}if(y)c.dataTypes=y;function E(S){c.data=S,c.dataLevel=l.dataLevel+1,c.dataTypes=[],l.definedProperties=new Set,c.parentData=l.data,c.dataNames=[...l.dataNames,S]}}Nc.extendSubschemaData=W_;function K_(c,{jtdDiscriminator:l,jtdMetadata:u,compositeRule:g,createErrors:_,allErrors:y}){if(g!==void 0)c.compositeRule=g;if(_!==void 0)c.createErrors=_;if(y!==void 0)c.allErrors=y;c.jtdDiscriminator=l,c.jtdMetadata=u}Nc.extendSubschemaMode=K_});var Is=i(function(Xk,jc){jc.exports=function c(l,u){if(l===u)return!0;if(l&&u&&typeof l=="object"&&typeof u=="object"){if(l.constructor!==u.constructor)return!1;var g,_,y;if(Array.isArray(l)){if(g=l.length,g!=u.length)return!1;for(_=g;_--!==0;)if(!c(l[_],u[_]))return!1;return!0}if(l.constructor===RegExp)return l.source===u.source&&l.flags===u.flags;if(l.valueOf!==Object.prototype.valueOf)return l.valueOf()===u.valueOf();if(l.toString!==Object.prototype.toString)return l.toString()===u.toString();if(y=Object.keys(l),g=y.length,g!==Object.keys(u).length)return!1;for(_=g;_--!==0;)if(!Object.prototype.hasOwnProperty.call(u,y[_]))return!1;for(_=g;_--!==0;){var T=y[_];if(!c(l[T],u[T]))return!1}return!0}return l!==l&&u!==u}});var Uc=i(function(Jk,Lc){var ut=Lc.exports=function(c,l,u){if(typeof l=="function")u=l,l={};u=l.cb||u;var g=typeof u=="function"?u:u.pre||function(){},_=u.post||function(){};zn(l,g,_,c,"",c)};ut.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ut.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ut.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ut.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 zn(c,l,u,g,_,y,T,b,E,S){if(g&&typeof g=="object"&&!Array.isArray(g)){l(g,_,y,T,b,E,S);for(var k in g){var A=g[k];if(Array.isArray(A)){if(k in ut.arrayKeywords)for(var z=0;z<A.length;z++)zn(c,l,u,A[z],_+"/"+k+"/"+z,y,_,k,g,z)}else if(k in ut.propsKeywords){if(A&&typeof A=="object")for(var C in A)zn(c,l,u,A[C],_+"/"+k+"/"+Z_(C),y,_,k,g,C)}else if(k in ut.keywords||c.allKeys&&!(k in ut.skipKeywords))zn(c,l,u,A,_+"/"+k,y,_,k,g)}u(g,_,y,T,b,E,S)}}function Z_(c){return c.replace(/~/g,"~0").replace(/\//g,"~1")}});var xr=i(function(Wc){Object.defineProperty(Wc,"__esModule",{value:!0});Wc.getSchemaRefs=Wc.resolveUrl=Wc.normalizeId=Wc._getFullPath=Wc.getFullPath=Wc.inlineRef=void 0;var X_=X(),J_=Is(),Y_=Uc(),Q_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ey(c,l=!0){if(typeof c=="boolean")return!0;if(l===!0)return!zs(c);if(!l)return!1;return Fc(c)<=l}Wc.inlineRef=ey;var ny=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function zs(c){for(let l in c){if(ny.has(l))return!0;let u=c[l];if(Array.isArray(u)&&u.some(zs))return!0;if(typeof u=="object"&&zs(u))return!0}return!1}function Fc(c){let l=0;for(let u in c){if(u==="$ref")return 1/0;if(l++,Q_.has(u))continue;if(typeof c[u]=="object")X_.eachItem(c[u],(g)=>l+=Fc(g));if(l===1/0)return 1/0}return l}function Hc(c,l="",u){if(u!==!1)l=Wt(l);let g=c.parse(l);return Vc(c,g)}Wc.getFullPath=Hc;function Vc(c,l){return c.serialize(l).split("#")[0]+"#"}Wc._getFullPath=Vc;var oy=/#\/?$/;function Wt(c){return c?c.replace(oy,""):""}Wc.normalizeId=Wt;function ay(c,l,u){return u=Wt(u),c.resolve(l,u)}Wc.resolveUrl=ay;var iy=/^[a-z_][-a-z0-9._]*$/i;function fy(c,l){if(typeof c=="boolean")return{};let{schemaId:u,uriResolver:g}=this.opts,_=Wt(c[u]||l),y={"":_},T=Hc(g,_,!1),b={},E=new Set;return Y_(c,{allKeys:!0},(A,z,C,P)=>{if(P===void 0)return;let I=T+z,M=y[P];if(typeof A[u]=="string")M=N.call(this,A[u]);D.call(this,A.$anchor),D.call(this,A.$dynamicAnchor),y[z]=M;function N(U){let F=this.opts.uriResolver.resolve;if(U=Wt(M?F(M,U):U),E.has(U))throw k(U);E.add(U);let O=this.refs[U];if(typeof O=="string")O=this.refs[O];if(typeof O=="object")S(A,O.schema,U);else if(U!==Wt(I))if(U[0]==="#")S(A,b[U],U),b[U]=A;else this.refs[U]=I;return U}function D(U){if(typeof U=="string"){if(!iy.test(U))throw Error(`invalid anchor "${U}"`);N.call(this,`#${U}`)}}}),b;function S(A,z,C){if(z!==void 0&&!J_(A,z))throw k(C)}function k(A){return Error(`reference "${A}" resolves to more than one schema`)}}Wc.getSchemaRefs=fy});var Ar=i(function(il){Object.defineProperty(il,"__esModule",{value:!0});il.getData=il.KeywordCxt=il.validateFunctionCode=void 0;var Xc=cc(),Jc=Sr(),Os=Ss(),On=Sr(),wy=Sc(),kr=Oc(),Ms=Dc(),j=B(),W=Ze(),vy=xr(),Xe=X(),$r=Er();function Ty(c){if(el(c)){if(tl(c),Qc(c)){Ey(c);return}}Yc(c,()=>Xc.topBoolOrEmptySchema(c))}il.validateFunctionCode=Ty;function Yc({gen:c,validateName:l,schema:u,schemaEnv:g,opts:_},y){if(_.code.es5)c.func(l,j._`${W.default.data}, ${W.default.valCxt}`,g.$async,()=>{c.code(j._`"use strict"; ${Bc(u,_)}`),Ry(c,_),c.code(y)});else c.func(l,j._`${W.default.data}, ${by(_)}`,g.$async,()=>c.code(Bc(u,_)).code(y))}function by(c){return j._`{${W.default.instancePath}="", ${W.default.parentData}, ${W.default.parentDataProperty}, ${W.default.rootData}=${W.default.data}${c.dynamicRef?j._`, ${W.default.dynamicAnchors}={}`:j.nil}}={}`}function Ry(c,l){c.if(W.default.valCxt,()=>{if(c.var(W.default.instancePath,j._`${W.default.valCxt}.${W.default.instancePath}`),c.var(W.default.parentData,j._`${W.default.valCxt}.${W.default.parentData}`),c.var(W.default.parentDataProperty,j._`${W.default.valCxt}.${W.default.parentDataProperty}`),c.var(W.default.rootData,j._`${W.default.valCxt}.${W.default.rootData}`),l.dynamicRef)c.var(W.default.dynamicAnchors,j._`${W.default.valCxt}.${W.default.dynamicAnchors}`)},()=>{if(c.var(W.default.instancePath,j._`""`),c.var(W.default.parentData,j._`undefined`),c.var(W.default.parentDataProperty,j._`undefined`),c.var(W.default.rootData,W.default.data),l.dynamicRef)c.var(W.default.dynamicAnchors,j._`{}`)})}function Ey(c){let{schema:l,opts:u,gen:g}=c;Yc(c,()=>{if(u.$comment&&l.$comment)nl(c);if(Ay(c),g.let(W.default.vErrors,null),g.let(W.default.errors,0),u.unevaluated)Sy(c);rl(c),Iy(c)});return}function Sy(c){let{gen:l,validateName:u}=c;c.evaluated=l.const("evaluated",j._`${u}.evaluated`),l.if(j._`${c.evaluated}.dynamicProps`,()=>l.assign(j._`${c.evaluated}.props`,j._`undefined`)),l.if(j._`${c.evaluated}.dynamicItems`,()=>l.assign(j._`${c.evaluated}.items`,j._`undefined`))}function Bc(c,l){let u=typeof c=="object"&&c[l.schemaId];return u&&(l.code.source||l.code.process)?j._`/*# sourceURL=${u} */`:j.nil}function xy(c,l){if(el(c)){if(tl(c),Qc(c)){ky(c,l);return}}Xc.boolOrEmptySchema(c,l)}function Qc({schema:c,self:l}){if(typeof c=="boolean")return!c;for(let u in c)if(l.RULES.all[u])return!0;return!1}function el(c){return typeof c.schema!="boolean"}function ky(c,l){let{schema:u,gen:g,opts:_}=c;if(_.$comment&&u.$comment)nl(c);Py(c),Cy(c);let y=g.const("_errs",W.default.errors);rl(c,y),g.var(l,j._`${y} === ${W.default.errors}`)}function tl(c){Xe.checkUnknownRules(c),$y(c)}function rl(c,l){if(c.opts.jtd)return Gc(c,[],!1,l);let u=Jc.getSchemaTypes(c.schema),g=Jc.coerceAndCheckDataType(c,u);Gc(c,u,!g,l)}function $y(c){let{schema:l,errSchemaPath:u,opts:g,self:_}=c;if(l.$ref&&g.ignoreKeywordsWithRef&&Xe.schemaHasRulesButRef(l,_.RULES))_.logger.warn(`$ref: keywords ignored in schema at path "${u}"`)}function Ay(c){let{schema:l,opts:u}=c;if(l.default!==void 0&&u.useDefaults&&u.strictSchema)Xe.checkStrictMode(c,"default is ignored in the schema root")}function Py(c){let l=c.schema[c.opts.schemaId];if(l)c.baseId=vy.resolveUrl(c.opts.uriResolver,c.baseId,l)}function Cy(c){if(c.schema.$async&&!c.schemaEnv.$async)throw Error("async schema in sync schema")}function nl({gen:c,schemaEnv:l,schema:u,errSchemaPath:g,opts:_}){let y=u.$comment;if(_.$comment===!0)c.code(j._`${W.default.self}.logger.log(${y})`);else if(typeof _.$comment=="function"){let T=j.str`${g}/$comment`,b=c.scopeValue("root",{ref:l.root});c.code(j._`${W.default.self}.opts.$comment(${y}, ${T}, ${b}.schema)`)}}function Iy(c){let{gen:l,schemaEnv:u,validateName:g,ValidationError:_,opts:y}=c;if(u.$async)l.if(j._`${W.default.errors} === 0`,()=>l.return(W.default.data),()=>l.throw(j._`new ${_}(${W.default.vErrors})`));else{if(l.assign(j._`${g}.errors`,W.default.vErrors),y.unevaluated)zy(c);l.return(j._`${W.default.errors} === 0`)}}function zy({gen:c,evaluated:l,props:u,items:g}){if(u instanceof j.Name)c.assign(j._`${l}.props`,u);if(g instanceof j.Name)c.assign(j._`${l}.items`,g)}function Gc(c,l,u,g){let{gen:_,schema:y,data:T,allErrors:b,opts:E,self:S}=c,{RULES:k}=S;if(y.$ref&&(E.ignoreKeywordsWithRef||!Xe.schemaHasRulesButRef(y,k))){_.block(()=>sl(c,"$ref",k.all.$ref.definition));return}if(!E.jtd)Oy(c,l);_.block(()=>{for(let z of k.rules)A(z);A(k.post)});function A(z){if(!Os.shouldUseGroup(y,z))return;if(z.type){if(_.if(On.checkDataType(z.type,T,E.strictNumbers)),Zc(c,z),l.length===1&&l[0]===z.type&&u)_.else(),On.reportTypeError(c);_.endIf()}else Zc(c,z);if(!b)_.if(j._`${W.default.errors} === ${g||0}`)}}function Zc(c,l){let{gen:u,schema:g,opts:{useDefaults:_}}=c;if(_)wy.assignDefaults(c,l.type);u.block(()=>{for(let y of l.rules)if(Os.shouldUseRule(g,y))sl(c,y.keyword,y.definition,l.type)})}function Oy(c,l){if(c.schemaEnv.meta||!c.opts.strictTypes)return;if(My(c,l),!c.opts.allowUnionTypes)Ny(c,l);qy(c,c.dataTypes)}function My(c,l){if(!l.length)return;if(!c.dataTypes.length){c.dataTypes=l;return}l.forEach((u)=>{if(!ol(c.dataTypes,u))Ns(c,`type "${u}" not allowed by context "${c.dataTypes.join(",")}"`)}),jy(c,l)}function Ny(c,l){if(l.length>1&&!(l.length===2&&l.includes("null")))Ns(c,"use allowUnionTypes to allow union type keyword")}function qy(c,l){let u=c.self.RULES.all;for(let g in u){let _=u[g];if(typeof _=="object"&&Os.shouldUseRule(c.schema,_)){let{type:y}=_.definition;if(y.length&&!y.some((T)=>Dy(l,T)))Ns(c,`missing type "${y.join(",")}" for keyword "${g}"`)}}}function Dy(c,l){return c.includes(l)||l==="number"&&c.includes("integer")}function ol(c,l){return c.includes(l)||l==="integer"&&c.includes("number")}function jy(c,l){let u=[];for(let g of c.dataTypes)if(ol(l,g))u.push(g);else if(l.includes("integer")&&g==="number")u.push("integer");c.dataTypes=u}function Ns(c,l){let u=c.schemaEnv.baseId+c.errSchemaPath;l+=` at "${u}" (strictTypes)`,Xe.checkStrictMode(c,l,c.opts.strictTypes)}class qs{constructor(c,l,u){if(kr.validateKeywordUsage(c,l,u),this.gen=c.gen,this.allErrors=c.allErrors,this.keyword=u,this.data=c.data,this.schema=c.schema[u],this.$data=l.$data&&c.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=Xe.schemaRefOrVal(c,this.schema,u,this.$data),this.schemaType=l.schemaType,this.parentSchema=c.schema,this.params={},this.it=c,this.def=l,this.$data)this.schemaCode=c.gen.const("vSchema",al(this.$data,c));else if(this.schemaCode=this.schemaValue,!kr.validSchemaType(this.schema,l.schemaType,l.allowUndefined))throw Error(`${u} value must be ${JSON.stringify(l.schemaType)}`);if("code"in l?l.trackErrors:l.errors!==!1)this.errsCount=c.gen.const("_errs",W.default.errors)}result(c,l,u){this.failResult(j.not(c),l,u)}failResult(c,l,u){if(this.gen.if(c),u)u();else this.error();if(l){if(this.gen.else(),l(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(c,l){this.failResult(j.not(c),void 0,l)}fail(c){if(c===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(c),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(c){if(!this.$data)return this.fail(c);let{schemaCode:l}=this;this.fail(j._`${l} !== undefined && (${j.or(this.invalid$data(),c)})`)}error(c,l,u){if(l){this.setParams(l),this._error(c,u),this.setParams({});return}this._error(c,u)}_error(c,l){(c?$r.reportExtraError:$r.reportError)(this,this.def.error,l)}$dataError(){$r.reportError(this,this.def.$dataError||$r.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');$r.resetErrorsCount(this.gen,this.errsCount)}ok(c){if(!this.allErrors)this.gen.if(c)}setParams(c,l){if(l)Object.assign(this.params,c);else this.params=c}block$data(c,l,u=j.nil){this.gen.block(()=>{this.check$data(c,u),l()})}check$data(c=j.nil,l=j.nil){if(!this.$data)return;let{gen:u,schemaCode:g,schemaType:_,def:y}=this;if(u.if(j.or(j._`${g} === undefined`,l)),c!==j.nil)u.assign(c,!0);if(_.length||y.validateSchema){if(u.elseIf(this.invalid$data()),this.$dataError(),c!==j.nil)u.assign(c,!1)}u.else()}invalid$data(){let{gen:c,schemaCode:l,schemaType:u,def:g,it:_}=this;return j.or(y(),T());function y(){if(u.length){if(!(l instanceof j.Name))throw Error("ajv implementation error");let b=Array.isArray(u)?u:[u];return j._`${On.checkDataTypes(b,l,_.opts.strictNumbers,On.DataType.Wrong)}`}return j.nil}function T(){if(g.validateSchema){let b=c.scopeValue("validate$data",{ref:g.validateSchema});return j._`!${b}(${l})`}return j.nil}}subschema(c,l){let u=Ms.getSubschema(this.it,c);Ms.extendSubschemaData(u,this.it,c),Ms.extendSubschemaMode(u,c);let g={...this.it,...u,items:void 0,props:void 0};return xy(g,l),g}mergeEvaluated(c,l){let{it:u,gen:g}=this;if(!u.opts.unevaluated)return;if(u.props!==!0&&c.props!==void 0)u.props=Xe.mergeEvaluated.props(g,c.props,u.props,l);if(u.items!==!0&&c.items!==void 0)u.items=Xe.mergeEvaluated.items(g,c.items,u.items,l)}mergeValidEvaluated(c,l){let{it:u,gen:g}=this;if(u.opts.unevaluated&&(u.props!==!0||u.items!==!0))return g.if(l,()=>this.mergeEvaluated(c,j.Name)),!0}}il.KeywordCxt=qs;function sl(c,l,u,g){let _=new qs(c,u,l);if("code"in u)u.code(_,g);else if(_.$data&&u.validate)kr.funcKeywordCode(_,u);else if("macro"in u)kr.macroKeywordCode(_,u);else if(u.compile||u.validate)kr.funcKeywordCode(_,u)}var Ly=/^\/(?:[^~]|~0|~1)*$/,Uy=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function al(c,{dataLevel:l,dataNames:u,dataPathArr:g}){let _,y;if(c==="")return W.default.rootData;if(c[0]==="/"){if(!Ly.test(c))throw Error(`Invalid JSON-pointer: ${c}`);_=c,y=W.default.rootData}else{let S=Uy.exec(c);if(!S)throw Error(`Invalid JSON-pointer: ${c}`);let k=+S[1];if(_=S[2],_==="#"){if(k>=l)throw Error(E("property/index",k));return g[l-k]}if(k>l)throw Error(E("data",k));if(y=u[l-k],!_)return y}let T=y,b=_.split("/");for(let S of b)if(S)y=j._`${y}${j.getProperty(Xe.unescapeJsonPointer(S))}`,T=j._`${T} && ${y}`;return T;function E(S,k){return`Cannot access ${S} ${k} levels up, current level is ${l}`}}il.getData=al});var Mn=i(function(ul){Object.defineProperty(ul,"__esModule",{value:!0});class ll extends Error{constructor(c){super("validation failed");this.errors=c,this.ajv=this.validation=!0}}ul.default=ll});var Pr=i(function(pl){Object.defineProperty(pl,"__esModule",{value:!0});var Ds=xr();class dl extends Error{constructor(c,l,u,g){super(g||`can't resolve reference ${u} from id ${l}`);this.missingRef=Ds.resolveUrl(c,l,u),this.missingSchema=Ds.normalizeId(Ds.getFullPath(c,this.missingRef))}}pl.default=dl});var qn=i(function(_l){Object.defineProperty(_l,"__esModule",{value:!0});_l.resolveSchema=_l.getCompilingSchema=_l.resolveRef=_l.compileSchema=_l.SchemaEnv=void 0;var Ne=B(),Ky=Mn(),St=Ze(),qe=xr(),fl=X(),By=Ar();class Cr{constructor(c){var l;this.refs={},this.dynamicAnchors={};let u;if(typeof c.schema=="object")u=c.schema;this.schema=c.schema,this.schemaId=c.schemaId,this.root=c.root||this,this.baseId=(l=c.baseId)!==null&&l!==void 0?l:qe.normalizeId(u===null||u===void 0?void 0:u[c.schemaId||"$id"]),this.schemaPath=c.schemaPath,this.localRefs=c.localRefs,this.meta=c.meta,this.$async=u===null||u===void 0?void 0:u.$async,this.refs={}}}_l.SchemaEnv=Cr;function Ls(c){let l=gl.call(this,c);if(l)return l;let u=qe.getFullPath(this.opts.uriResolver,c.root.baseId),{es5:g,lines:_}=this.opts.code,{ownProperties:y}=this.opts,T=new Ne.CodeGen(this.scope,{es5:g,lines:_,ownProperties:y}),b;if(c.$async)b=T.scopeValue("Error",{ref:Ky.default,code:Ne._`require("ajv/dist/runtime/validation_error").default`});let E=T.scopeName("validate");c.validateName=E;let S={gen:T,allErrors:this.opts.allErrors,data:St.default.data,parentData:St.default.parentData,parentDataProperty:St.default.parentDataProperty,dataNames:[St.default.data],dataPathArr:[Ne.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:T.scopeValue("schema",this.opts.code.source===!0?{ref:c.schema,code:Ne.stringify(c.schema)}:{ref:c.schema}),validateName:E,ValidationError:b,schema:c.schema,schemaEnv:c,rootId:u,baseId:c.baseId||u,schemaPath:Ne.nil,errSchemaPath:c.schemaPath||(this.opts.jtd?"":"#"),errorPath:Ne._`""`,opts:this.opts,self:this},k;try{this._compilations.add(c),By.validateFunctionCode(S),T.optimize(this.opts.code.optimize);let A=T.toString();if(k=`${T.scopeRefs(St.default.scope)}return ${A}`,this.opts.code.process)k=this.opts.code.process(k,c);let C=Function(`${St.default.self}`,`${St.default.scope}`,k)(this,this.scope.get());if(this.scope.value(E,{ref:C}),C.errors=null,C.schema=c.schema,C.schemaEnv=c,c.$async)C.$async=!0;if(this.opts.code.source===!0)C.source={validateName:E,validateCode:A,scopeValues:T._values};if(this.opts.unevaluated){let{props:P,items:I}=S;if(C.evaluated={props:P instanceof Ne.Name?void 0:P,items:I instanceof Ne.Name?void 0:I,dynamicProps:P instanceof Ne.Name,dynamicItems:I instanceof Ne.Name},C.source)C.source.evaluated=Ne.stringify(C.evaluated)}return c.validate=C,c}catch(A){if(delete c.validate,delete c.validateName,k)this.logger.error("Error compiling schema, function code:",k);throw A}finally{this._compilations.delete(c)}}_l.compileSchema=Ls;function Gy(c,l,u){var g;u=qe.resolveUrl(this.opts.uriResolver,l,u);let _=c.refs[u];if(_)return _;let y=Jy.call(this,c,u);if(y===void 0){let T=(g=c.localRefs)===null||g===void 0?void 0:g[u],{schemaId:b}=this.opts;if(T)y=new Cr({schema:T,schemaId:b,root:c,baseId:l})}if(y===void 0)return;return c.refs[u]=Zy.call(this,y)}_l.resolveRef=Gy;function Zy(c){if(qe.inlineRef(c.schema,this.opts.inlineRefs))return c.schema;return c.validate?c:Ls.call(this,c)}function gl(c){for(let l of this._compilations)if(Xy(l,c))return l}_l.getCompilingSchema=gl;function Xy(c,l){return c.schema===l.schema&&c.root===l.root&&c.baseId===l.baseId}function Jy(c,l){let u;while(typeof(u=this.refs[l])=="string")l=u;return u||this.schemas[l]||Nn.call(this,c,l)}function Nn(c,l){let u=this.opts.uriResolver.parse(l),g=qe._getFullPath(this.opts.uriResolver,u),_=qe.getFullPath(this.opts.uriResolver,c.baseId,void 0);if(Object.keys(c.schema).length>0&&g===_)return js.call(this,u,c);let y=qe.normalizeId(g),T=this.refs[y]||this.schemas[y];if(typeof T=="string"){let b=Nn.call(this,c,T);if(typeof(b===null||b===void 0?void 0:b.schema)!=="object")return;return js.call(this,u,b)}if(typeof(T===null||T===void 0?void 0:T.schema)!=="object")return;if(!T.validate)Ls.call(this,T);if(y===qe.normalizeId(l)){let{schema:b}=T,{schemaId:E}=this.opts,S=b[E];if(S)_=qe.resolveUrl(this.opts.uriResolver,_,S);return new Cr({schema:b,schemaId:E,root:c,baseId:_})}return js.call(this,u,T)}_l.resolveSchema=Nn;var Yy=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function js(c,{baseId:l,schema:u,root:g}){var _;if(((_=c.fragment)===null||_===void 0?void 0:_[0])!=="/")return;for(let b of c.fragment.slice(1).split("/")){if(typeof u==="boolean")return;let E=u[fl.unescapeFragment(b)];if(E===void 0)return;u=E;let S=typeof u==="object"&&u[this.opts.schemaId];if(!Yy.has(b)&&S)l=qe.resolveUrl(this.opts.uriResolver,l,S)}let y;if(typeof u!="boolean"&&u.$ref&&!fl.schemaHasRulesButRef(u,this.RULES)){let b=qe.resolveUrl(this.opts.uriResolver,l,u.$ref);y=Nn.call(this,g,b)}let{schemaId:T}=this.opts;if(y=y||new Cr({schema:u,schemaId:T,root:g,baseId:l}),y.schema!==y.root.schema)return y;return}});var wl=i(function(n$,n0){n0.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ks=i(function(o$,$l){var o0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Us=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),s0=RegExp.prototype.test.bind(/^\d*$/u),xt=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Fs=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),bl=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Hs=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),a0=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),i0=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=]$/u),c0=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=]*$/u);function l0(c){let l="",u=0,g=0;for(g=0;g<c.length;g++){if(u=c[g].charCodeAt(0),u===48)continue;if(!(u>=48&&u<=57||u>=65&&u<=70||u>=97&&u<=102))return"";l+=c[g];break}for(g+=1;g<c.length;g++){if(u=c[g].charCodeAt(0),!(u>=48&&u<=57||u>=65&&u<=70||u>=97&&u<=102))return"";l+=c[g]}return l}var u0=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),d0=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),p0=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),f0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),h0=RegExp.prototype.test.bind(/[^\d!"$&'()*+,\-.;=_`a-z{}~]/u),m0=RegExp.prototype.test.bind(/(?:^|\.)\d+$/u);function g0(c){return h0(c)||m0(c)}function _0(c){if(c.length===0)return!1;for(let l=0;l<c.length;l++){if(p0(c[l]))continue;if(c[l]==="%"&&l+2<c.length&&xt(c.slice(l+1,l+3))){l+=2;continue}return!1}return!0}function vl(c){let l=-1,u=0,g=-1,_=0;for(let b=0;b<c.length;b++)if(c[b]==="0"){if(g===-1)g=b;if(_++,_>u)u=_,l=g}else g=-1,_=0;if(u<2)return c.join(":");let y=c.slice(0,l).join(":"),T=c.slice(l+u).join(":");return y+"::"+T}function y0(c){let l=c.indexOf("::");if(l!==-1&&c.indexOf("::",l+1)!==-1)return;let u=l===-1?c.split(":"):c.slice(0,l).split(":"),g=l===-1?[]:c.slice(l+2).split(":");if(l!==-1){if(u.length===1&&u[0]==="")u.length=0;if(g.length===1&&g[0]==="")g.length=0}let _=u.concat(g),y=0;for(let b=0;b<_.length;b++){let E=_[b];if(E==="")return;if(E.indexOf(".")!==-1){if(b!==_.length-1||l!==-1&&g.length===0||!Us(E))return;y+=2;continue}if(!u0(E))return;_[b]=parseInt(E,16).toString(16),y++}if(l===-1){if(y!==8)return;return vl(_)}if(y>=8)return;let T=_.slice(0,u.length);for(let b=y;b<8;b++)T.push("0");for(let b=u.length;b<_.length;b++)T.push(_[b]);return vl(T)}function Dn(c){let l=c[0]==="["&&c[c.length-1]==="]";if((c[0]==="["||c[c.length-1]==="]")&&!l)return{host:c,isIPV6:!1,error:!0};let g=l?c.slice(1,-1):c;if(l&&d0(g))return g=g.toLowerCase(),{host:`[${g}]`,escapedHost:g,isIPV6:!1,isIPVFuture:!0};if(w0(g,":")<2)return{host:c,isIPV6:!1,error:l};let _="",y=g.indexOf("%");if(y!==-1){let b=g.slice(y,y+3).toLowerCase()==="%25"?3:1;if(_=g.slice(y+b),!_0(_))return{host:c,isIPV6:!1,error:!0};g=g.slice(0,y)}let T=y0(g);if(T===void 0)return{host:c,isIPV6:!1,error:!0};return{host:T+(_?"%"+_:""),escapedHost:T+(_?"%25"+_:""),isIPV6:!0}}function w0(c,l){let u=0;for(let g=0;g<c.length;g++)if(c[g]===l)u++;return u}function Rl(c){let l=c,u=[],g=-1,_=0;while(_=l.length){if(_===1)if(l===".")break;else if(l==="/"){u.push("/");break}else{u.push(l);break}else if(_===2){if(l[0]==="."){if(l[1]===".")break;else if(l[1]==="/"){l=l.slice(2);continue}}else if(l[0]==="/"){if(l[1]==="."){u.push("/");break}}}else if(_===3){if(l==="/.."){if(u.length!==0)u.pop();u.push("/");break}}if(l[0]==="."){if(l[1]==="."){if(l[2]==="/"){l=l.slice(3);continue}}else if(l[1]==="/"){l=l.slice(2);continue}}else if(l[0]==="/"){if(l[1]==="."){if(l[2]==="/"){l=l.slice(2);continue}else if(l[2]==="."){if(l[3]==="/"){if(l=l.slice(3),u.length!==0)u.pop();continue}}}}if((g=l.indexOf("/",1))===-1){u.push(l);break}else u.push(l.slice(0,g)),l=l.slice(g)}return u.join("")}function v0(c){if(c===""||c[0]==="/")return Rl(c);let l=c.split("/"),u=l.length-1,g=[],_=!1;for(let y=0;y<=u;y++){let T=l[y];if(T==="."||T===".."){if(T==="..")if(g.length!==0&&g[g.length-1]!=="..")g.pop();else g.push("..");_=y===u}else g.push(T)}if(_&&g[g.length-1]!=="..")g.push("");if(g.length===0||g[0]===""||g[0].includes(":"))g.unshift(".");return g.join("/")}var T0={"@":"%40","/":"%2F","?":"%3F","#":"%23"},Tl=/[@/?#]/g;function El(c,l,u=!1){if(!l){if(c0(c))return c;return jn(c,i0,u)}return Tl.lastIndex=0,c.replace(Tl,(g)=>T0[g])}function xl(c,l=!1){if(c.indexOf("%")===-1)return c;let u="";for(let g=0;g<c.length;g++){if(c[g]==="%"&&g+2<c.length){let _=c.slice(g+1,g+3);if(xt(_)){let y=_.toUpperCase(),T=String.fromCharCode(parseInt(y,16));if(l&&Fs(T))u+=T;else u+="%"+y;g+=2;continue}}u+=c[g]}return u}var _e=Array(256);for(let l=0;l<256;l++)_e[l]="%"+"0123456789ABCDEF"[l>>4]+"0123456789ABCDEF"[l&15];function Vs(c){return c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||c===42||c===43||c===45||c===46||c===47||c===64||c===95}function oe(c){if(c<2048)return _e[192|c>>6]+_e[128|c&63];if(c<65536)return _e[224|c>>12]+_e[128|c>>6&63]+_e[128|c&63];return _e[240|c>>18]+_e[128|c>>12&63]+_e[128|c>>6&63]+_e[128|c&63]}function b0(c){let l="";for(let u=0;u<c.length;u++){let g=c[u];if(g==="%"&&u+2<c.length){let _=c.slice(u+1,u+3);if(xt(_)){let y=_.toUpperCase(),T=String.fromCharCode(parseInt(y,16));if(T!=="."&&Fs(T))l+=T;else l+="%"+y;u+=2;continue}}if(bl(g))l+=g;else{let _=c.charCodeAt(u);if(_<128)l+=Vs(_)?g:_e[_];else if(_<55296||_>57343)l+=oe(_);else if(_<=56319&&u+1<c.length){let y=c.charCodeAt(u+1);if(y>=56320&&y<=57343)l+=oe(65536+(_-55296<<10)+(y-56320)),u++;else l+=oe(65533)}else l+=oe(65533)}}return l}function R0(c,l=!1){let u="",g=l&&c[0]!=="/";for(let _=0;_<c.length;_++){let y=c[_];if(y==="%"&&_+2<c.length){let T=c.slice(_+1,_+3);if(xt(T)){u+="%"+T.toUpperCase(),_+=2;continue}}if(y==="/")g=!1;if(bl(y)&&(y!==":"||!g))u+=y;else{let T=c.charCodeAt(_);if(T<128)u+=_e[T];else if(T<55296||T>57343)u+=oe(T);else if(T<=56319&&_+1<c.length){let b=c.charCodeAt(_+1);if(b>=56320&&b<=57343)u+=oe(65536+(T-55296<<10)+(b-56320)),_++;else u+=oe(65533)}else u+=oe(65533)}}return u}function E0(c){let l="";for(let u=0;u<c.length;u++){let g=c[u];if(g==="%"&&u+2<c.length){let _=c.slice(u+1,u+3);if(xt(_)){let y=_.toUpperCase(),T=String.fromCharCode(parseInt(y,16));if(Fs(T))l+=T;else l+="%"+y;u+=2;continue}}if(Hs(g))l+=g;else{let _=c.charCodeAt(u);if(_<128)l+=Vs(_)?g:_e[_];else if(_<55296||_>57343)l+=oe(_);else if(_<=56319&&u+1<c.length){let y=c.charCodeAt(u+1);if(y>=56320&&y<=57343)l+=oe(65536+(_-55296<<10)+(y-56320)),u++;else l+=oe(65533)}else l+=oe(65533)}}return l}function jn(c,l,u=!1){let g="";for(let _=0;_<c.length;_++){let y=c[_];if(y==="%"&&_+2<c.length){let T=c.slice(_+1,_+3);if(xt(T)){g+="%"+T.toUpperCase(),_+=2;continue}}if(l(y))g+=y;else{let T=c.charCodeAt(_);if(T<128)g+=_e[T];else if(T<55296||T>57343)g+=u?y:oe(T);else if(T<=56319&&_+1<c.length){let b=c.charCodeAt(_+1);if(b>=56320&&b<=57343)g+=u?y+c[_+1]:oe(65536+(T-55296<<10)+(b-56320)),_++;else g+=u?"�":oe(65533)}else g+=u?"�":oe(65533)}}return g}function kl(c){return jn(c,a0)}function S0(c){return jn(c,Hs)}function x0(c){return jn(c,Hs)}function k0(c){let l="";for(let u=0;u<c.length;u++){let g=c[u];if(g==="%"&&u+2<c.length){let y=c.slice(u+1,u+3);if(xt(y)){l+="%"+y.toUpperCase(),u+=2;continue}}let _=c.charCodeAt(u);if(_<128)l+=Vs(_)?g:_e[_];else if(_<55296||_>57343)l+=oe(_);else if(_<=56319&&u+1<c.length){let y=c.charCodeAt(u+1);if(y>=56320&&y<=57343)l+=oe(65536+(_-55296<<10)+(y-56320)),u++;else l+=oe(65533)}else l+=oe(65533)}return l}function $0(c){let l=c.ipv6Zone;if(l===void 0)return;let u=c.host,g=u.indexOf("%");if(g===-1)return;let y=u.slice(0,g)+"%25"+l,T=Dn("["+y+"]");if(T.isIPV6===!0&&T.host===u)return"["+y+"]";return}function A0(c,l=!1){let u=[];if(c.userinfo!==void 0)u.push(kl(c.userinfo)),u.push("@");if(c.host!==void 0){let g=c.host;if(!Us(g)){let _=$0(c);if(_!==void 0)g=_;else{let y=Dn(g);if(y.isIPV6!==!0&&y.isIPVFuture!==!0)g=xl(g,!0),y=Dn(g);if(y.isIPV6===!0||y.isIPVFuture===!0)g=`[${y.escapedHost}]`;else g=El(g,!1,l)}}u.push(g)}if(typeof c.port==="number"||typeof c.port==="string"){let g=String(c.port);if(!s0(g))throw TypeError("URI port is malformed.");u.push(":"),u.push(g)}return u.length?u.join(""):void 0}$l.exports={BYTE_HEX:_e,percentEncodeNonAscii:oe,nonSimpleDomain:f0,nonSimpleMailtoDomain:g0,recomposeAuthority:A0,encodeHost:El,normalizePercentEncoding:xl,normalizePathEncoding:b0,serializePathEncoding:R0,normalizeQueryFragmentEncoding:E0,encodeUserinfo:kl,encodeQuery:S0,encodeFragment:x0,escapePreservingEscapes:k0,removeDotSegments:Rl,removeDotSegmentsRelative:v0,isIPv4:Us,isUUID:o0,normalizeIPv6:Dn,stringArrayToHexStripped:l0}});var jl=i(function(s$,Dl){var{isUUID:P0,BYTE_HEX:C0,percentEncodeNonAscii:Bs,nonSimpleMailtoDomain:I0}=Ks(),z0=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,O0=["http","https","ws","wss","urn","urn:uuid","mailto"];function M0(c){return O0.indexOf(c)!==-1}function Zs(c){if(c.secure===!0)return!0;else if(c.secure===!1)return!1;else if(c.scheme)return c.scheme.length===3&&(c.scheme[0]==="w"||c.scheme[0]==="W")&&(c.scheme[1]==="s"||c.scheme[1]==="S")&&(c.scheme[2]==="s"||c.scheme[2]==="S");else return!1}function Il(c){if(!c.host)c.error=c.error||"HTTP URIs must have a host.";return c}function zl(c){let l=String(c.scheme).toLowerCase()==="https";if(c.port===(l?443:80)||c.port==="")c.port=void 0;if(!c.path)c.path="/";return c}function N0(c){return c.secure=Zs(c),c.resourceName=(c.path||"/")+(c.query?"?"+c.query:""),c.path=void 0,c.query=void 0,c}function q0(c){if(c.port===(Zs(c)?443:80)||c.port==="")c.port=void 0;if(typeof c.secure==="boolean")c.scheme=c.secure?"wss":"ws",c.secure=void 0;if(c.resourceName){let l=c.resourceName.indexOf("?"),u=l===-1?c.resourceName:c.resourceName.slice(0,l);c.path=u&&u!=="/"?u:void 0,c.query=l===-1?void 0:c.resourceName.slice(l+1),c.resourceName=void 0}return c.fragment=void 0,c}function D0(c,l){if(!c.path)return c.error="URN can not be parsed",c;let u=c.path.match(z0);if(u&&u[0]===c.path){let g=l.scheme||c.scheme||"urn";c.nid=u[1].toLowerCase(),c.nss=u[2];let _=`${g}:${l.nid||c.nid}`,y=Xs(_);if(c.path=void 0,y)c=y.parse(c,l)}else c.error=c.error||"URN can not be parsed.";return c}function j0(c,l){if(c.nid===void 0)throw Error("URN without nid cannot be serialized");let u=l.scheme||c.scheme||"urn",g=c.nid.toLowerCase(),_=`${u}:${l.nid||g}`,y=Xs(_);if(y)c=y.serialize(c,l);let T=c,b=c.nss;return T.path=`${g||l.nid}:${b}`,l.skipEscape=!0,T}function L0(c,l){let u=c;if(u.uuid=u.nss,u.nss=void 0,!l.tolerant&&(!u.uuid||!P0(u.uuid)))u.error=u.error||"UUID is not valid.";return u}function U0(c){let l=c;return l.nss=(c.uuid||"").toLowerCase(),l}var Ol={scheme:"http",domainHost:!0,parse:Il,serialize:zl},F0={scheme:"https",domainHost:Ol.domainHost,parse:Il,serialize:zl},Ln={scheme:"ws",domainHost:!0,parse:N0,serialize:q0},H0={scheme:"wss",domainHost:Ln.domainHost,parse:Ln.parse,serialize:Ln.serialize},V0={scheme:"urn",parse:D0,serialize:j0,skipNormalize:!0,absolutePath:!0},W0={scheme:"urn:uuid",parse:L0,serialize:U0,skipNormalize:!0},K0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+=",B0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+,;:@",Ml="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+;:";function Fn(c,l=!1){let u=new Uint8Array(128);for(let y=0;y<c.length;y++)u[c.charCodeAt(y)]=1;let g=c.replace(/[\\\]^-]/gu,"\\$&"),_=l?`[${g}]|[^\\0-\\x7F\\uD800-\\uDFFF]`:`[${g}]`;return{all:new RegExp(`^(?:${_})*$`,"u"),table:u,allowNonAscii:l}}var G0=Fn(K0),Nl=Fn(B0),Z0=Fn(Ml),X0=Fn(Ml,!0),J0=/^[\da-f]{2}$/iu,Y0=/^\[[\x21-\x5A\x5E-\x7E]*\]$/u,Gs="URI mailto has an invalid recipient domain.",Q0="URI mailto must not have an authority component.",Pl=/[\uD800-\uDFFF]/u;function dt(c){if(typeof c!=="string"||c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function Cl(c){let l="";for(let u=0;u<c.length;u++){let g=c.charCodeAt(u);if(g>=55296&&g<=56319&&u+1<c.length){let _=c.charCodeAt(u+1);if(_>=56320&&_<=57343){l+=c[u]+c[u+1],u++;continue}}l+=g>=55296&&g<=57343?"�":c[u]}return l}function Ir(c,l){if(l.all.test(c))return c;let u=l.table,g="";for(let _=0;_<c.length;_++){let y=c.charCodeAt(_);if(y<128){if(u[y]===1)g+=c[_];else if(y===37&&_+2<c.length&&J0.test(c.slice(_+1,_+3)))g+="%"+c.slice(_+1,_+3).toUpperCase(),_+=2;else g+=C0[y];continue}if(y<55296||y>57343){g+=l.allowNonAscii?c[_]:Bs(y);continue}if(y<=56319&&_+1<c.length){let T=c.charCodeAt(_+1);if(T>=56320&&T<=57343){g+=l.allowNonAscii?c[_]+c[_+1]:Bs(65536+(y-55296<<10)+(T-56320)),_++;continue}}g+=l.allowNonAscii?"�":Bs(65533)}return g}function ql(c,l,u){let g=String(c).toLowerCase();if(Y0.test(g))return g;if(g!==""&&!I0(g))return g;try{let _=new URL("http://"+g);if(_.username||_.password||_.port||_.pathname!=="/"||_.search||_.hash||!_.hostname)throw Error(Gs);return l&&l.unicodeSupport?g:_.hostname}catch{if(u)u.error=u.error||Gs;return g}}function ew(c,l){let u=l&&l.unicodeSupport?X0:Z0;if(c.length>1&&c[0]==="["&&c[c.length-1]==="]")return"["+Ir(c.slice(1,-1),u)+"]";return Ir(c,u)}function tw(c,l){let u=c,{path:g,query:_}=u;if(g&&Pl.test(g))g=Cl(g);if(_&&Pl.test(_))_=Cl(_);let y=g?g.indexOf(",")===-1?[g]:g.split(","):[];if(u.path=void 0,_){let T=null,b=0;while(b<=_.length){let E=_.indexOf("&",b);if(E===-1)E=_.length;let S=_.slice(b,E);b=E+1;let k=S.indexOf("=");if(k!==S.lastIndexOf("=")){u.error=u.error||"URI mailto has malformed header fields.";continue}let A=dt(k===-1?S:S.slice(0,k)),z=A.toLowerCase(),C=k===-1?"":S.slice(k+1);if(z==="to"){let P=C.split(",");for(let I=0;I<P.length;I++)y.push(P[I]);continue}if(z==="subject"){u.subject=dt(C);continue}if(z==="body"){u.body=dt(C);continue}if(T===null)T=Object.create(null);T[A]=dt(C)}if(T!==null)u.headers=T}if(u.query=void 0,y.length>0&&(u.userinfo!==void 0||u.host!==void 0||u.port!==void 0))u.userinfo=void 0,u.host=void 0,u.port=void 0,u.error=u.error||Q0;for(let T=0;T<y.length;T++){let b=y[T],E=b.lastIndexOf("@");if(E<0){u.error=u.error||Gs,y[T]=dt(b);continue}let S=dt(b.slice(0,E)),k=ql(dt(b.slice(E+1)),l,u);y[T]=S+"@"+k}if(y.length)u.to=y;return u}function rw(c){return Ir(c.replace(/%/gu,"%25"),Nl)}function nw(c,l){let u=c,g=Array.isArray(u.to)?u.to.slice():[],_=u.headers&&typeof u.headers==="object"?Object.assign(Object.create(null),u.headers):Object.create(null),y=Object.create(null);for(let E in _){let S=E.toLowerCase();if(S==="to"){let k=String(_[E]).split(",");for(let A=0;A<k.length;A++)g.push(k[A])}else if(S==="subject"||S==="body")y[S]=_[E];else y[E]=_[E]}if(u.subject!==void 0)y.subject=u.subject;if(u.body!==void 0)y.body=u.body;if(u.headers=y,g.length){u.userinfo=void 0,u.host=void 0,u.port=void 0;for(let E=0;E<g.length;E++){let S=String(g[E]),k=S.lastIndexOf("@"),A=k>=0?S.slice(0,k):S,z=k>=0?S.slice(k+1):"",C=Ir(A,G0),P=dt(z),I=ql(P,l);g[E]=C+"@"+ew(I,l)}u.path=g.join(","),l.skipEscape=!0}else u.path=void 0;let T="",b=0;for(let E in y){if(b++!==0)T+="&";T+=rw(E)+"="+Ir(String(y[E]),Nl)}if(b!==0)u.query=T;else u.headers=void 0;return u}var ow={scheme:"mailto",parse:tw,serialize:nw,domainHost:!1,unicodeSupport:!0,skipNormalize:!0,absolutePath:!0},Un={http:Ol,https:F0,ws:Ln,wss:H0,urn:V0,"urn:uuid":W0,mailto:ow};Object.setPrototypeOf(Un,null);function Xs(c){return c&&(Un[c]||Un[c.toLowerCase()])||void 0}Dl.exports={wsIsSecure:Zs,SCHEMES:Un,isValidSchemeName:M0,getSchemeHandler:Xs}});var Ql=i(function(a$,Bn){var{normalizeIPv6:Vl,removeDotSegments:Or,removeDotSegmentsRelative:Wl,recomposeAuthority:sw,normalizePercentEncoding:Ys,normalizePathEncoding:aw,serializePathEncoding:Ll,normalizeQueryFragmentEncoding:Ul,encodeQuery:iw,encodeFragment:cw,encodeHost:lw,isIPv4:Kl,nonSimpleDomain:uw}=Ks(),{SCHEMES:Bl,getSchemeHandler:Wn}=jl(),Gl=/^[A-Za-z][A-Za-z0-9+.-]*$/u,dw=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function Fl(c){let l=String(c);if(!Gl.test(l))throw TypeError("URI scheme is malformed.");return l}function pw(c,l){if(typeof c==="string")c=Tw(c,l);else if(typeof c==="object")c=Vn(kt(c,l),l);return c}function fw(c,l,u){let g=u?Object.assign({scheme:"null"},u):{scheme:"null"},{parsed:_,malformedAuthorityOrPort:y,malformedReferenceEdge:T,malformedPercentEncoding:b,malformedSchemeSpecific:E,malformedHost:S,malformedScheme:k}=Hn(c,g),{parsed:A,malformedAuthorityOrPort:z,malformedReferenceEdge:C,malformedPercentEncoding:P,malformedSchemeSpecific:I,malformedHost:M,malformedScheme:N}=Hn(l,g);if(y||z||T||C||b||P||E||I||S||M||k||N)throw Error(_.error||A.error||"URI is malformed.");let D=Zl(_,A,g,!0),U=Wn(u&&u.scheme||D.scheme),F=D.host;if((D.scheme==="http"||D.scheme==="https")&&!F)throw Error("HTTP URIs must have a host.");let O=F!==void 0&&F!==""&&(Kl(F)||Vl(F).isIPV6);if(Jl(D,u||{},U,O))throw Error("URI host is malformed.");Xl(D,u||{},U,O);let H=F&&F.indexOf("%")!==-1&&!/\P{ASCII}/u.test(F);if(D.error&&!H)throw Error(D.error);if(g.skipEscape=!0,U&&U.absolutePath)g.absolutePath=!0;return kt(D,g)}function Js(c,l){if(c.host=l.host,l.ipv6Zone!==void 0)c.ipv6Zone=l.ipv6Zone}function Zl(c,l,u,g){let _={};if(!g)c=Vn(kt(c,u),u),l=Vn(kt(l,u),u);if(u=u||{},!u.tolerant&&l.scheme){_.scheme=l.scheme,_.userinfo=l.userinfo,Js(_,l),_.port=l.port;let y=Wn(l.scheme);_.path=y&&y.absolutePath?l.path||"":Or(l.path||""),_.query=l.query}else{if(l.userinfo!==void 0||l.host!==void 0||l.port!==void 0)_.userinfo=l.userinfo,Js(_,l),_.port=l.port,_.path=Or(l.path||""),_.query=l.query;else{if(!l.path)if(_.path=c.path,l.query!==void 0)_.query=l.query;else _.query=c.query;else{if(l.path[0]==="/")_.path=Or(l.path);else{let y=c.userinfo!==void 0||c.host!==void 0||c.port!==void 0;if(y&&!c.path)_.path="/"+l.path;else if(!c.path)_.path=l.path;else _.path=c.path.slice(0,c.path.lastIndexOf("/")+1)+l.path;_.path=c.scheme===void 0&&!y&&_.path[0]!=="/"?Wl(_.path):Or(_.path)}_.query=l.query}_.userinfo=c.userinfo,Js(_,c),_.port=c.port}_.scheme=c.scheme}return _.fragment=l.fragment,_}function hw(c,l,u){let g=Hl(c,u),_=Hl(l,u);return g!==void 0&&_!==void 0&&g===_}function kt(c,l){let u={host:c.host,ipv6Zone:c.ipv6Zone,scheme:c.scheme,userinfo:c.userinfo,port:c.port,path:c.path,query:c.query,nid:c.nid,nss:c.nss,uuid:c.uuid,fragment:c.fragment,reference:c.reference,resourceName:c.resourceName,secure:c.secure,to:c.to,subject:c.subject,body:c.body,headers:c.headers,error:""},g=Object.assign({},l),_=[];if(u.scheme)u.scheme=Fl(u.scheme);let y=Wn(g.scheme||u.scheme);if(y&&y.serialize)y.serialize(u,g);let T=u.userinfo!==void 0||u.host!==void 0||u.port!==void 0,b=(u.scheme===void 0||g.reference==="suffix")&&!T,E=!g.skipEscape&&b;if(u.path!==void 0)if(!g.skipEscape)u.path=Ll(u.path,E);else u.path=Ys(u.path);if(g.reference!=="suffix"&&u.scheme)u.scheme=Fl(u.scheme),_.push(u.scheme,":");let S=g.unicodeSupport===!0||Boolean(y&&y.unicodeSupport),k=sw(u,S);if(k!==void 0){if(g.reference!=="suffix")_.push("//");if(_.push(k),u.path&&u.path[0]!=="/")_.push("/")}if(u.path!==void 0){let A=u.path;if(!g.absolutePath&&(!y||!y.absolutePath))A=b&&A[0]!=="/"?Wl(A):Or(A);if(b)A=Ll(A,!0);if(k===void 0&&A[0]==="/"&&A[1]==="/")A="/%2F"+A.slice(2);_.push(A)}if(u.query!==void 0)_.push("?",iw(u.query));if(u.fragment!==void 0)_.push("#",cw(u.fragment));return _.join("")}var mw=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,_w=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function yw(c,l){if(l[2]!==void 0&&c.path&&c.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof c.port==="number"&&(c.port<0||c.port>65535))return"URI port is malformed.";return}function zr(c){if(c===void 0)return!1;let l=c.indexOf("%");while(l!==-1){if(l+2>=c.length||!/^[\da-f]{2}$/iu.test(c.slice(l+1,l+3)))return!0;l=c.indexOf("%",l+3)}return!1}function Kn(c){return c[0]==="["&&c[c.length-1]==="]"}function ww(c){let l=c[4];return zr(c[3])||l!==void 0&&!Kn(l)&&zr(l)||zr(c[6])||zr(c[7])||zr(c[8])}function Xl(c,l,u,g){let _=c.host&&c.host[0]==="["&&c.host[c.host.length-1]==="]";if(Jl(c,l,u,g))return c.error=c.error||"URI host is malformed.",!0;if(!l.unicodeSupport&&(!u||!u.unicodeSupport)&&c.host&&!Kn(c.host)&&(l.domainHost||u&&u.domainHost)&&g===!1&&!_&&uw(c.host)){let y;try{y=new URL("http://"+c.host)}catch(T){return c.error=c.error||"Host's domain name can not be converted to ASCII: "+T,!0}if(!vw(y))return c.error=c.error||"URI host is malformed.",!0;c.host=y.hostname}return!1}function Jl(c,l,u,g){return Boolean(c.host&&g===!1&&!Kn(c.host)&&(l.domainHost||u&&u.domainHost)&&dw.test(c.host))}function vw(c){return c.username===""&&c.password===""&&c.port===""&&c.pathname==="/"&&c.search===""&&c.hash===""&&c.hostname!==""}function Hn(c,l){let u=Object.assign({},l),g={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},_=!1,y=c.length!==0&&(c.charCodeAt(0)<=32||c.charCodeAt(c.length-1)<=32),T=!1,b=!1,E=!1,S=!1,k=!1,A=!1;if(u.reference==="suffix")if(u.scheme)c=u.scheme+":"+c;else c="//"+c;let z=c.match(gw);if(z!==null&&z[1].indexOf("\\")!==-1)g.error="URI authority must not contain a literal backslash.",_=!0;let C=c.match(_w);if(C!==null){let I=C[1],M=I.replace(/[\t\n\r]/g,"");if(M.length>=2){if(M.slice(0,2)!=="//")g.error=g.error||"URI authority must not contain a literal backslash.",_=!0;else if(I.length!==M.length)g.error=g.error||"URI authority introducer must not contain whitespace.",_=!0}}if(y)g.error=g.error||"URI must not contain leading or trailing C0 controls or spaces.";let P=c.match(mw);if(P){if(g.scheme=P[1],g.userinfo=P[3],g.host=P[4],g.port=parseInt(P[5],10),g.path=P[6]||"",g.query=P[7],g.fragment=P[8],g.scheme!==void 0)if(Gl.test(g.scheme))g.scheme=g.scheme.toLowerCase();else g.error=g.error||"URI scheme is malformed.",k=!0;if(T=ww(P),T)g.error=g.error||"URI contains malformed percent-encoding.";if(isNaN(g.port))g.port=P[5];let I=yw(g,P);if(I!==void 0)g.error=g.error||I,_=!0;if(g.host)if(Kl(g.host)===!1){let D=Kn(g.host),U=g.host.indexOf("[")!==-1||g.host.indexOf("]")!==-1,F=Vl(g.host);if(A=F.isIPV6||F.isIPVFuture===!0,S=U&&(!D||F.error===!0),g.host=A?F.host:F.host.toLowerCase(),A&&F.isIPV6===!0&&g.host.indexOf("%")!==-1)g.ipv6Zone=g.host.slice(g.host.indexOf("%")+1);if(S)g.error=g.error||"URI host is malformed.",_=!0}else A=!0;if(g.scheme===void 0&&g.userinfo===void 0&&g.host===void 0&&g.port===void 0&&g.query===void 0&&!g.path)g.reference="same-document";else if(g.scheme===void 0)g.reference="relative";else if(g.fragment===void 0)g.reference="absolute";else g.reference="uri";if(u.reference&&u.reference!=="suffix"&&u.reference!==g.reference)g.error=g.error||"URI is not a "+u.reference+" reference.";let M=Wn(u.scheme||g.scheme);if(!S)E=Xl(g,u,M,A);if(g.host!==void 0&&!S){let N=g.host;if(c.indexOf("%")!==-1&&!A)N=Ys(N,!0),N=Ys(N.toLowerCase());if(u.scheme!=="null"){let D=u.unicodeSupport===!0||Boolean(M&&M.unicodeSupport);g.host=lw(N,A,D)}else g.host=N}if(!M||M&&!M.skipNormalize){if(g.path)g.path=aw(g.path);if(g.query)g.query=Ul(g.query);if(g.fragment)g.fragment=Ul(g.fragment)}if(M&&M.parse){if(M.parse(g,u),M===Bl.urn&&g.nid===void 0)b=!0}}else g.error=g.error||"URI can not be parsed.";return{parsed:g,malformedAuthorityOrPort:_,malformedReferenceEdge:y,malformedPercentEncoding:T,malformedSchemeSpecific:b,malformedHost:E,malformedScheme:k}}function Vn(c,l){return Hn(c,l).parsed}function Tw(c,l){return Yl(c,l).normalized}function Yl(c,l){let{parsed:u,malformedAuthorityOrPort:g,malformedReferenceEdge:_,malformedPercentEncoding:y,malformedSchemeSpecific:T,malformedHost:b,malformedScheme:E}=Hn(c,l);return{normalized:g||_||y||T||b||E?c:kt(u,l),malformedAuthorityOrPort:g,malformedReferenceEdge:_,malformedPercentEncoding:y,malformedSchemeSpecific:T,malformedHost:b,malformedScheme:E}}function Hl(c,l){if(typeof c!=="string"&&typeof c!=="object")return;let u;try{u=typeof c==="string"?c:kt(c,l)}catch{return}let{normalized:g,malformedAuthorityOrPort:_,malformedReferenceEdge:y,malformedPercentEncoding:T,malformedSchemeSpecific:b,malformedHost:E,malformedScheme:S}=Yl(u,l);return _||y||T||b||E||S?void 0:g}var Qs={SCHEMES:Bl,normalize:pw,resolve:fw,resolveComponent:Zl,equal:hw,serialize:kt,parse:Vn};Bn.exports=Qs;Bn.exports.default=Qs;Bn.exports.fastUri=Qs});var ru=i(function(tu){Object.defineProperty(tu,"__esModule",{value:!0});var eu=Ql();eu.code='require("ajv/dist/runtime/uri").default';tu.default=eu});var uu=i(function(Ye){Object.defineProperty(Ye,"__esModule",{value:!0});Ye.CodeGen=Ye.Name=Ye.nil=Ye.stringify=Ye.str=Ye._=Ye.KeywordCxt=void 0;var Rw=Ar();Object.defineProperty(Ye,"KeywordCxt",{enumerable:!0,get:function(){return Rw.KeywordCxt}});var Kt=B();Object.defineProperty(Ye,"_",{enumerable:!0,get:function(){return Kt._}});Object.defineProperty(Ye,"str",{enumerable:!0,get:function(){return Kt.str}});Object.defineProperty(Ye,"stringify",{enumerable:!0,get:function(){return Kt.stringify}});Object.defineProperty(Ye,"nil",{enumerable:!0,get:function(){return Kt.nil}});Object.defineProperty(Ye,"Name",{enumerable:!0,get:function(){return Kt.Name}});Object.defineProperty(Ye,"CodeGen",{enumerable:!0,get:function(){return Kt.CodeGen}});var Ew=Mn(),iu=Pr(),Sw=Es(),qr=qn(),xw=B(),Nr=xr(),Gn=Sr(),ta=X(),nu=wl(),kw=ru(),cu=(c,l)=>new RegExp(c,l);cu.code="new RegExp";var $w=["removeAdditional","useDefaults","coerceTypes"],Aw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Pw={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."},Cw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ou=200;function Iw(c){var l,u,g,_,y,T,b,E,S,k,A,z,C,P,I,M,N,D,U,F,O,H,ee,Se,ue;let Ie=c.strict,Qr=(l=c.code)===null||l===void 0?void 0:l.optimize,Ao=Qr===!0||Qr===void 0?1:Qr||0,Za=(g=(u=c.code)===null||u===void 0?void 0:u.regExp)!==null&&g!==void 0?g:cu,lf=(_=c.uriResolver)!==null&&_!==void 0?_:kw.default;return{strictSchema:(T=(y=c.strictSchema)!==null&&y!==void 0?y:Ie)!==null&&T!==void 0?T:!0,strictNumbers:(E=(b=c.strictNumbers)!==null&&b!==void 0?b:Ie)!==null&&E!==void 0?E:!0,strictTypes:(k=(S=c.strictTypes)!==null&&S!==void 0?S:Ie)!==null&&k!==void 0?k:"log",strictTuples:(z=(A=c.strictTuples)!==null&&A!==void 0?A:Ie)!==null&&z!==void 0?z:"log",strictRequired:(P=(C=c.strictRequired)!==null&&C!==void 0?C:Ie)!==null&&P!==void 0?P:!1,code:c.code?{...c.code,optimize:Ao,regExp:Za}:{optimize:Ao,regExp:Za},loopRequired:(I=c.loopRequired)!==null&&I!==void 0?I:ou,loopEnum:(M=c.loopEnum)!==null&&M!==void 0?M:ou,meta:(N=c.meta)!==null&&N!==void 0?N:!0,messages:(D=c.messages)!==null&&D!==void 0?D:!0,inlineRefs:(U=c.inlineRefs)!==null&&U!==void 0?U:!0,schemaId:(F=c.schemaId)!==null&&F!==void 0?F:"$id",addUsedSchema:(O=c.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(H=c.validateSchema)!==null&&H!==void 0?H:!0,validateFormats:(ee=c.validateFormats)!==null&&ee!==void 0?ee:!0,unicodeRegExp:(Se=c.unicodeRegExp)!==null&&Se!==void 0?Se:!0,int32range:(ue=c.int32range)!==null&&ue!==void 0?ue:!0,uriResolver:lf}}class Zn{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,...Iw(c)};let{es5:l,lines:u}=this.opts.code;this.scope=new xw.ValueScope({scope:{},prefixes:Aw,es5:l,lines:u}),this.logger=Dw(c.logger);let g=c.validateFormats;if(c.validateFormats=!1,this.RULES=Sw.getRules(),su.call(this,Pw,c,"NOT SUPPORTED"),su.call(this,Cw,c,"DEPRECATED","warn"),this._metaOpts=Nw.call(this),c.formats)Ow.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),c.keywords)Mw.call(this,c.keywords);if(typeof c.meta=="object")this.addMetaSchema(c.meta);zw.call(this),c.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:c,meta:l,schemaId:u}=this.opts,g=nu;if(u==="id")g={...nu},g.id=g.$id,delete g.$id;if(l&&c)this.addMetaSchema(g,g[u],!1)}defaultMeta(){let{meta:c,schemaId:l}=this.opts;return this.opts.defaultMeta=typeof c=="object"?c[l]||c:void 0}validate(c,l){let u;if(typeof c=="string"){if(u=this.getSchema(c),!u)throw Error(`no schema with key or ref "${c}"`)}else u=this.compile(c);let g=u(l);if(!("$async"in u))this.errors=u.errors;return g}compile(c,l){let u=this._addSchema(c,l);return u.validate||this._compileSchemaEnv(u)}compileAsync(c,l){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:u}=this.opts;return g.call(this,c,l);async function g(S,k){await _.call(this,S.$schema);let A=this._addSchema(S,k);return A.validate||y.call(this,A)}async function _(S){if(S&&!this.getSchema(S))await g.call(this,{$ref:S},!0)}async function y(S){try{return this._compileSchemaEnv(S)}catch(k){if(!(k instanceof iu.default))throw k;return T.call(this,k),await b.call(this,k.missingSchema),y.call(this,S)}}function T({missingSchema:S,missingRef:k}){if(this.refs[S])throw Error(`AnySchema ${S} is loaded but ${k} cannot be resolved`)}async function b(S){let k=await E.call(this,S);if(!this.refs[S])await _.call(this,k.$schema);if(!this.refs[S])this.addSchema(k,S,l)}async function E(S){let k=this._loading[S];if(k)return k;try{return await(this._loading[S]=u(S))}finally{delete this._loading[S]}}}addSchema(c,l,u,g=this.opts.validateSchema){if(Array.isArray(c)){for(let y of c)this.addSchema(y,void 0,u,g);return this}let _;if(typeof c==="object"){let{schemaId:y}=this.opts;if(_=c[y],_!==void 0&&typeof _!="string")throw Error(`schema ${y} must be string`)}return l=Nr.normalizeId(l||_),this._checkUnique(l),this.schemas[l]=this._addSchema(c,u,l,g,!0),this}addMetaSchema(c,l,u=this.opts.validateSchema){return this.addSchema(c,l,!0,u),this}validateSchema(c,l){if(typeof c=="boolean")return!0;let u;if(u=c.$schema,u!==void 0&&typeof u!="string")throw Error("$schema must be a string");if(u=u||this.opts.defaultMeta||this.defaultMeta(),!u)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let g=this.validate(u,c);if(!g&&l){let _="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(_);else throw Error(_)}return g}getSchema(c){let l;while(typeof(l=au.call(this,c))=="string")c=l;if(l===void 0){let{schemaId:u}=this.opts,g=new qr.SchemaEnv({schema:{},schemaId:u});if(l=qr.resolveSchema.call(this,g,c),!l)return;this.refs[c]=l}return l.validate||this._compileSchemaEnv(l)}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":{let l=au.call(this,c);if(typeof l=="object")this._cache.delete(l.schema);return delete this.schemas[c],delete this.refs[c],this}case"object":{let l=c;this._cache.delete(l);let u=c[this.opts.schemaId];if(u)u=Nr.normalizeId(u),delete this.schemas[u],delete this.refs[u];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(c){for(let l of c)this.addKeyword(l);return this}addKeyword(c,l){let u;if(typeof c=="string"){if(u=c,typeof l=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),l.keyword=u}else if(typeof c=="object"&&l===void 0){if(l=c,u=l.keyword,Array.isArray(u)&&!u.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Lw.call(this,u,l),!l)return ta.eachItem(u,(_)=>ea.call(this,_)),this;Fw.call(this,l);let g={...l,type:Gn.getJSONTypes(l.type),schemaType:Gn.getJSONTypes(l.schemaType)};return ta.eachItem(u,g.type.length===0?(_)=>ea.call(this,_,g):(_)=>g.type.forEach((y)=>ea.call(this,_,g,y))),this}getKeyword(c){let l=this.RULES.all[c];return typeof l=="object"?l.definition:!!l}removeKeyword(c){let{RULES:l}=this;delete l.keywords[c],delete l.all[c];for(let u of l.rules){let g=u.rules.findIndex((_)=>_.keyword===c);if(g>=0)u.rules.splice(g,1)}return this}addFormat(c,l){if(typeof l=="string")l=new RegExp(l);return this.formats[c]=l,this}errorsText(c=this.errors,{separator:l=", ",dataVar:u="data"}={}){if(!c||c.length===0)return"No errors";return c.map((g)=>`${u}${g.instancePath} ${g.message}`).reduce((g,_)=>g+l+_)}$dataMetaSchema(c,l){let u=this.RULES.all;c=JSON.parse(JSON.stringify(c));for(let g of l){let _=g.split("/").slice(1),y=c;for(let T of _)y=y[T];for(let T in u){let b=u[T];if(typeof b!="object")continue;let{$data:E}=b.definition,S=y[T];if(E&&S)y[T]=lu(S)}}return c}_removeAllSchemas(c,l){for(let u in c){let g=c[u];if(!l||l.test(u)){if(typeof g=="string")delete c[u];else if(g&&!g.meta)this._cache.delete(g.schema),delete c[u]}}}_addSchema(c,l,u,g=this.opts.validateSchema,_=this.opts.addUsedSchema){let y,{schemaId:T}=this.opts;if(typeof c=="object")y=c[T];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof c!="boolean")throw Error("schema must be object or boolean");let b=this._cache.get(c);if(b!==void 0)return b;u=Nr.normalizeId(y||u);let E=Nr.getSchemaRefs.call(this,c,u);if(b=new qr.SchemaEnv({schema:c,schemaId:T,meta:l,baseId:u,localRefs:E}),this._cache.set(b.schema,b),_&&!u.startsWith("#")){if(u)this._checkUnique(u);this.refs[u]=b}if(g)this.validateSchema(c,!0);return b}_checkUnique(c){if(this.schemas[c]||this.refs[c])throw Error(`schema with key or id "${c}" already exists`)}_compileSchemaEnv(c){if(c.meta)this._compileMetaSchema(c);else qr.compileSchema.call(this,c);if(!c.validate)throw Error("ajv implementation error");return c.validate}_compileMetaSchema(c){let l=this.opts;this.opts=this._metaOpts;try{qr.compileSchema.call(this,c)}finally{this.opts=l}}}Zn.ValidationError=Ew.default;Zn.MissingRefError=iu.default;Ye.default=Zn;function su(c,l,u,g="error"){for(let _ in c){let y=_;if(y in l)this.logger[g](`${u}: option ${_}. ${c[y]}`)}}function au(c){return c=Nr.normalizeId(c),this.schemas[c]||this.refs[c]}function zw(){let c=this.opts.schemas;if(!c)return;if(Array.isArray(c))this.addSchema(c);else for(let l in c)this.addSchema(c[l],l)}function Ow(){for(let c in this.opts.formats){let l=this.opts.formats[c];if(l)this.addFormat(c,l)}}function Mw(c){if(Array.isArray(c)){this.addVocabulary(c);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let l in c){let u=c[l];if(!u.keyword)u.keyword=l;this.addKeyword(u)}}function Nw(){let c={...this.opts};for(let l of $w)delete c[l];return c}var qw={log(){},warn(){},error(){}};function Dw(c){if(c===!1)return qw;if(c===void 0)return console;if(c.log&&c.warn&&c.error)return c;throw Error("logger must implement log, warn and error methods")}var jw=/^[a-z_$][a-z0-9_$:-]*$/i;function Lw(c,l){let{RULES:u}=this;if(ta.eachItem(c,(g)=>{if(u.keywords[g])throw Error(`Keyword ${g} is already defined`);if(!jw.test(g))throw Error(`Keyword ${g} has invalid name`)}),!l)return;if(l.$data&&!(("code"in l)||("validate"in l)))throw Error('$data keyword must have "code" or "validate" function')}function ea(c,l,u){var g;let _=l===null||l===void 0?void 0:l.post;if(u&&_)throw Error('keyword with "post" flag cannot have "type"');let{RULES:y}=this,T=_?y.post:y.rules.find(({type:E})=>E===u);if(!T)T={type:u,rules:[]},y.rules.push(T);if(y.keywords[c]=!0,!l)return;let b={keyword:c,definition:{...l,type:Gn.getJSONTypes(l.type),schemaType:Gn.getJSONTypes(l.schemaType)}};if(l.before)Uw.call(this,T,b,l.before);else T.rules.push(b);y.all[c]=b,(g=l.implements)===null||g===void 0||g.forEach((E)=>this.addKeyword(E))}function Uw(c,l,u){let g=c.rules.findIndex((_)=>_.keyword===u);if(g>=0)c.rules.splice(g,0,l);else c.rules.push(l),this.logger.warn(`rule ${u} is not defined`)}function Fw(c){let{metaSchema:l}=c;if(l===void 0)return;if(c.$data&&this.opts.$data)l=lu(l);c.validateSchema=this.compile(l,!0)}var Hw={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function lu(c){return{anyOf:[c,Hw]}}});var pu=i(function(du){Object.defineProperty(du,"__esModule",{value:!0});var Gw={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};du.default=Gw});var yu=i(function(gu){Object.defineProperty(gu,"__esModule",{value:!0});gu.callRef=gu.getValidate=void 0;var Xw=Pr(),fu=Pe(),be=B(),Bt=Ze(),hu=qn(),Xn=X(),Jw={keyword:"$ref",schemaType:"string",code(c){let{gen:l,schema:u,it:g}=c,{baseId:_,schemaEnv:y,validateName:T,opts:b,self:E}=g,{root:S}=y;if((u==="#"||u==="#/")&&_===S.baseId)return A();let k=hu.resolveRef.call(E,S,_,u);if(k===void 0)throw new Xw.default(g.opts.uriResolver,_,u);if(k instanceof hu.SchemaEnv)return z(k);return C(k);function A(){if(y===S)return Jn(c,T,y,y.$async);let P=l.scopeValue("root",{ref:S});return Jn(c,be._`${P}.validate`,S,S.$async)}function z(P){let I=mu(c,P);Jn(c,I,P,P.$async)}function C(P){let I=l.scopeValue("schema",b.code.source===!0?{ref:P,code:be.stringify(P)}:{ref:P}),M=l.name("valid"),N=c.subschema({schema:P,dataTypes:[],schemaPath:be.nil,topSchemaRef:I,errSchemaPath:u},M);c.mergeEvaluated(N),c.ok(M)}}};function mu(c,l){let{gen:u}=c;return l.validate?u.scopeValue("validate",{ref:l.validate}):be._`${u.scopeValue("wrapper",{ref:l})}.validate`}gu.getValidate=mu;function Jn(c,l,u,g){let{gen:_,it:y}=c,{allErrors:T,schemaEnv:b,opts:E}=y,S=E.passContext?Bt.default.this:be.nil;if(g)k();else A();function k(){if(!b.$async)throw Error("async schema referenced by sync schema");let P=_.let("valid");_.try(()=>{if(_.code(be._`await ${fu.callValidateCode(c,l,S)}`),C(l),!T)_.assign(P,!0)},(I)=>{if(_.if(be._`!(${I} instanceof ${y.ValidationError})`,()=>_.throw(I)),z(I),!T)_.assign(P,!1)}),c.ok(P)}function A(){c.result(fu.callValidateCode(c,l,S),()=>C(l),()=>z(l))}function z(P){let I=be._`${P}.errors`;_.assign(Bt.default.vErrors,be._`${Bt.default.vErrors} === null ? ${I} : ${Bt.default.vErrors}.concat(${I})`),_.assign(Bt.default.errors,be._`${Bt.default.vErrors}.length`)}function C(P){var I;if(!y.opts.unevaluated)return;let M=(I=u===null||u===void 0?void 0:u.validate)===null||I===void 0?void 0:I.evaluated;if(y.props!==!0)if(M&&!M.dynamicProps){if(M.props!==void 0)y.props=Xn.mergeEvaluated.props(_,M.props,y.props)}else{let N=_.var("props",be._`${P}.evaluated.props`);y.props=Xn.mergeEvaluated.props(_,N,y.props,be.Name)}if(y.items!==!0)if(M&&!M.dynamicItems){if(M.items!==void 0)y.items=Xn.mergeEvaluated.items(_,M.items,y.items)}else{let N=_.var("items",be._`${P}.evaluated.items`);y.items=Xn.mergeEvaluated.items(_,N,y.items,be.Name)}}}gu.callRef=Jn;gu.default=Jw});var vu=i(function(wu){Object.defineProperty(wu,"__esModule",{value:!0});var ev=pu(),tv=yu(),rv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ev.default,tv.default];wu.default=rv});var bu=i(function(Tu){Object.defineProperty(Tu,"__esModule",{value:!0});var Qn=B(),pt=Qn.operators,Yn={maximum:{okStr:"<=",ok:pt.LTE,fail:pt.GT},minimum:{okStr:">=",ok:pt.GTE,fail:pt.LT},exclusiveMaximum:{okStr:"<",ok:pt.LT,fail:pt.GTE},exclusiveMinimum:{okStr:">",ok:pt.GT,fail:pt.LTE}},ov={message:({keyword:c,schemaCode:l})=>Qn.str`must be ${Yn[c].okStr} ${l}`,params:({keyword:c,schemaCode:l})=>Qn._`{comparison: ${Yn[c].okStr}, limit: ${l}}`},sv={keyword:Object.keys(Yn),type:"number",schemaType:"number",$data:!0,error:ov,code(c){let{keyword:l,data:u,schemaCode:g}=c;c.fail$data(Qn._`${u} ${Yn[l].fail} ${g} || isNaN(${u})`)}};Tu.default=sv});var Eu=i(function(Ru){Object.defineProperty(Ru,"__esModule",{value:!0});var jr=B(),iv={message:({schemaCode:c})=>jr.str`must be multiple of ${c}`,params:({schemaCode:c})=>jr._`{multipleOf: ${c}}`},cv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:iv,code(c){let{gen:l,data:u,schemaCode:g,it:_}=c,y=_.opts.multipleOfPrecision,T=l.let("res"),b=y?jr._`Math.abs(Math.round(${T}) - ${T}) > 1e-${y}`:jr._`${T} !== parseInt(${T})`;c.fail$data(jr._`(${g} === 0 || (${T} = ${u}/${g}, ${b}))`)}};Ru.default=cv});var ku=i(function(xu){Object.defineProperty(xu,"__esModule",{value:!0});function Su(c){let l=c.length,u=0,g=0,_;while(g<l)if(u++,_=c.charCodeAt(g++),_>=55296&&_<=56319&&g<l){if(_=c.charCodeAt(g),(_&64512)===56320)g++}return u}xu.default=Su;Su.code='require("ajv/dist/runtime/ucs2length").default'});var Au=i(function($u){Object.defineProperty($u,"__esModule",{value:!0});var $t=B(),dv=X(),pv=ku(),fv={message({keyword:c,schemaCode:l}){return $t.str`must NOT have ${c==="maxLength"?"more":"fewer"} than ${l} characters`},params:({schemaCode:c})=>$t._`{limit: ${c}}`},hv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fv,code(c){let{keyword:l,data:u,schemaCode:g,it:_}=c,y=l==="maxLength"?$t.operators.GT:$t.operators.LT,T=_.opts.unicode===!1?$t._`${u}.length`:$t._`${dv.useFunc(c.gen,pv.default)}(${u})`;c.fail$data($t._`${T} ${y} ${g}`)}};$u.default=hv});var Cu=i(function(Pu){Object.defineProperty(Pu,"__esModule",{value:!0});var gv=Pe(),_v=X(),Gt=B(),yv={message:({schemaCode:c})=>Gt.str`must match pattern "${c}"`,params:({schemaCode:c})=>Gt._`{pattern: ${c}}`},wv={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yv,code(c){let{gen:l,data:u,$data:g,schema:_,schemaCode:y,it:T}=c,b=T.opts.unicodeRegExp?"u":"";if(g){let{regExp:E}=T.opts.code,S=E.code==="new RegExp"?Gt._`new RegExp`:_v.useFunc(l,E),k=l.let("valid");l.try(()=>l.assign(k,Gt._`${S}(${y}, ${b}).test(${u})`),()=>l.assign(k,!1)),c.fail$data(Gt._`!${k}`)}else{let E=gv.usePattern(c,_);c.fail$data(Gt._`!${E}.test(${u})`)}}};Pu.default=wv});var zu=i(function(Iu){Object.defineProperty(Iu,"__esModule",{value:!0});var Lr=B(),Tv={message({keyword:c,schemaCode:l}){return Lr.str`must NOT have ${c==="maxProperties"?"more":"fewer"} than ${l} properties`},params:({schemaCode:c})=>Lr._`{limit: ${c}}`},bv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Tv,code(c){let{keyword:l,data:u,schemaCode:g}=c,_=l==="maxProperties"?Lr.operators.GT:Lr.operators.LT;c.fail$data(Lr._`Object.keys(${u}).length ${_} ${g}`)}};Iu.default=bv});var Mu=i(function(Ou){Object.defineProperty(Ou,"__esModule",{value:!0});var Fr=Pe(),Ur=B(),Ev=X(),Sv={message:({params:{missingProperty:c}})=>Ur.str`must have required property '${c}'`,params:({params:{missingProperty:c}})=>Ur._`{missingProperty: ${c}}`},xv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Sv,code(c){let{gen:l,schema:u,schemaCode:g,data:_,$data:y,it:T}=c,{opts:b}=T;if(!y&&u.length===0)return;let E=u.length>=b.loopRequired;if(T.allErrors)S();else k();if(b.strictRequired){let C=c.parentSchema.properties,{definedProperties:P}=c.it;for(let I of u)if((C===null||C===void 0?void 0:C[I])===void 0&&!P.has(I)){let M=T.schemaEnv.baseId+T.errSchemaPath,N=`required property "${I}" is not defined at "${M}" (strictRequired)`;Ev.checkStrictMode(T,N,T.opts.strictRequired)}}function S(){if(E||y)c.block$data(Ur.nil,A);else for(let C of u)Fr.checkReportMissingProp(c,C)}function k(){let C=l.let("missing");if(E||y){let P=l.let("valid",!0);c.block$data(P,()=>z(C,P)),c.ok(P)}else l.if(Fr.checkMissingProp(c,u,C)),Fr.reportMissingProp(c,C),l.else()}function A(){l.forOf("prop",g,(C)=>{c.setParams({missingProperty:C}),l.if(Fr.noPropertyInData(l,_,C,b.ownProperties),()=>c.error())})}function z(C,P){c.setParams({missingProperty:C}),l.forOf(C,g,()=>{l.assign(P,Fr.propertyInData(l,_,C,b.ownProperties)),l.if(Ur.not(P),()=>{c.error(),l.break()})},Ur.nil)}}};Ou.default=xv});var qu=i(function(Nu){Object.defineProperty(Nu,"__esModule",{value:!0});var Hr=B(),$v={message({keyword:c,schemaCode:l}){return Hr.str`must NOT have ${c==="maxItems"?"more":"fewer"} than ${l} items`},params:({schemaCode:c})=>Hr._`{limit: ${c}}`},Av={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$v,code(c){let{keyword:l,data:u,schemaCode:g}=c,_=l==="maxItems"?Hr.operators.GT:Hr.operators.LT;c.fail$data(Hr._`${u}.length ${_} ${g}`)}};Nu.default=Av});var eo=i(function(ju){Object.defineProperty(ju,"__esModule",{value:!0});var Du=Is();Du.code='require("ajv/dist/runtime/equal").default';ju.default=Du});var Uu=i(function(Lu){Object.defineProperty(Lu,"__esModule",{value:!0});var ra=Sr(),he=B(),Iv=X(),Ov=eo(),Mv={message:({params:{i:c,j:l}})=>he.str`must NOT have duplicate items (items ## ${l} and ${c} are identical)`,params:({params:{i:c,j:l}})=>he._`{i: ${c}, j: ${l}}`},Nv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Mv,code(c){let{gen:l,data:u,$data:g,schema:_,parentSchema:y,schemaCode:T,it:b}=c;if(!g&&!_)return;let E=l.let("valid"),S=y.items?ra.getSchemaTypes(y.items):[];c.block$data(E,k,he._`${T} === false`),c.ok(E);function k(){let P=l.let("i",he._`${u}.length`),I=l.let("j");c.setParams({i:P,j:I}),l.assign(E,!0),l.if(he._`${P} > 1`,()=>(A()?z:C)(P,I))}function A(){return S.length>0&&!S.some((P)=>P==="object"||P==="array")}function z(P,I){let M=l.name("item"),N=ra.checkDataTypes(S,M,b.opts.strictNumbers,ra.DataType.Wrong),D=l.const("indices",he._`{}`);l.for(he._`;${P}--;`,()=>{if(l.let(M,he._`${u}[${P}]`),l.if(N,he._`continue`),S.length>1)l.if(he._`typeof ${M} == "string"`,he._`${M} += "_"`);l.if(he._`typeof ${D}[${M}] == "number"`,()=>{l.assign(I,he._`${D}[${M}]`),c.error(),l.assign(E,!1).break()}).code(he._`${D}[${M}] = ${P}`)})}function C(P,I){let M=Iv.useFunc(l,Ov.default),N=l.name("outer");l.label(N).for(he._`;${P}--;`,()=>l.for(he._`${I} = ${P}; ${I}--;`,()=>l.if(he._`${M}(${u}[${P}], ${u}[${I}])`,()=>{c.error(),l.assign(E,!1).break(N)})))}}};Lu.default=Nv});var Hu=i(function(Fu){Object.defineProperty(Fu,"__esModule",{value:!0});var na=B(),Dv=X(),jv=eo(),Lv={message:"must be equal to constant",params:({schemaCode:c})=>na._`{allowedValue: ${c}}`},Uv={keyword:"const",$data:!0,error:Lv,code(c){let{gen:l,data:u,$data:g,schemaCode:_,schema:y}=c;if(g||y&&typeof y=="object")c.fail$data(na._`!${Dv.useFunc(l,jv.default)}(${u}, ${_})`);else c.fail(na._`${y} !== ${u}`)}};Fu.default=Uv});var Ku=i(function(Wu){Object.defineProperty(Wu,"__esModule",{value:!0});var Vr=B(),Hv=X(),Vv=eo(),Wv={message:"must be equal to one of the allowed values",params:({schemaCode:c})=>Vr._`{allowedValues: ${c}}`},Kv={keyword:"enum",schemaType:"array",$data:!0,error:Wv,code(c){let{gen:l,data:u,$data:g,schema:_,schemaCode:y,it:T}=c;if(!g&&_.length===0)throw Error("enum must have non-empty array");let b=_.length>=T.opts.loopEnum,E,S=()=>E!==null&&E!==void 0?E:E=Hv.useFunc(l,Vv.default),k;if(b||g)k=l.let("valid"),c.block$data(k,A);else{if(!Array.isArray(_))throw Error("ajv implementation error");let C=l.const("vSchema",y);k=Vr.or(..._.map((P,I)=>z(C,I)))}c.pass(k);function A(){l.assign(k,!1),l.forOf("v",y,(C)=>l.if(Vr._`${S()}(${u}, ${C})`,()=>l.assign(k,!0).break()))}function z(C,P){let I=_[P];return typeof I==="object"&&I!==null?Vr._`${S()}(${u}, ${C}[${P}])`:Vr._`${u} === ${I}`}}};Wu.default=Kv});var Zu=i(function(Bu){Object.defineProperty(Bu,"__esModule",{value:!0});var Gv=bu(),Zv=Eu(),Xv=Au(),Jv=Cu(),Yv=zu(),Qv=Mu(),eT=qu(),tT=Uu(),rT=Hu(),nT=Ku(),oT=[Gv.default,Zv.default,Xv.default,Jv.default,Yv.default,Qv.default,eT.default,tT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rT.default,nT.default];Bu.default=oT});var aa=i(function(Ju){Object.defineProperty(Ju,"__esModule",{value:!0});Ju.validateAdditionalItems=void 0;var At=B(),sa=X(),aT={message:({params:{len:c}})=>At.str`must NOT have more than ${c} items`,params:({params:{len:c}})=>At._`{limit: ${c}}`},iT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:aT,code(c){let{parentSchema:l,it:u}=c,{items:g}=l;if(!Array.isArray(g)){sa.checkStrictMode(u,'"additionalItems" is ignored when "items" is not an array of schemas');return}Xu(c,g)}};function Xu(c,l){let{gen:u,schema:g,data:_,keyword:y,it:T}=c;T.items=!0;let b=u.const("len",At._`${_}.length`);if(g===!1)c.setParams({len:l.length}),c.pass(At._`${b} <= ${l.length}`);else if(typeof g=="object"&&!sa.alwaysValidSchema(T,g)){let S=u.var("valid",At._`${b} <= ${l.length}`);u.if(At.not(S),()=>E(S)),c.ok(S)}function E(S){u.forRange("i",l.length,b,(k)=>{if(c.subschema({keyword:y,dataProp:k,dataPropType:sa.Type.Num},S),!T.allErrors)u.if(At.not(S),()=>u.break())})}}Ju.validateAdditionalItems=Xu;Ju.default=iT});var ia=i(function(td){Object.defineProperty(td,"__esModule",{value:!0});td.validateTuple=void 0;var Qu=B(),to=X(),lT=Pe(),uT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(c){let{schema:l,it:u}=c;if(Array.isArray(l))return ed(c,"additionalItems",l);if(u.items=!0,to.alwaysValidSchema(u,l))return;c.ok(lT.validateArray(c))}};function ed(c,l,u=c.schema){let{gen:g,parentSchema:_,data:y,keyword:T,it:b}=c;if(k(_),b.opts.unevaluated&&u.length&&b.items!==!0)b.items=to.mergeEvaluated.items(g,u.length,b.items);let E=g.name("valid"),S=g.const("len",Qu._`${y}.length`);u.forEach((A,z)=>{if(to.alwaysValidSchema(b,A))return;g.if(Qu._`${S} > ${z}`,()=>c.subschema({keyword:T,schemaProp:z,dataProp:z},E)),c.ok(E)});function k(A){let{opts:z,errSchemaPath:C}=b,P=u.length,I=P===A.minItems&&(P===A.maxItems||A[l]===!1);if(z.strictTuples&&!I){let M=`"${T}" is ${P}-tuple, but minItems or maxItems/${l} are not specified or different at path "${C}"`;to.checkStrictMode(b,M,z.strictTuples)}}}td.validateTuple=ed;td.default=uT});var od=i(function(nd){Object.defineProperty(nd,"__esModule",{value:!0});var pT=ia(),fT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(c)=>pT.validateTuple(c,"items")};nd.default=fT});var id=i(function(ad){Object.defineProperty(ad,"__esModule",{value:!0});var sd=B(),mT=X(),gT=Pe(),_T=aa(),yT={message:({params:{len:c}})=>sd.str`must NOT have more than ${c} items`,params:({params:{len:c}})=>sd._`{limit: ${c}}`},wT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:yT,code(c){let{schema:l,parentSchema:u,it:g}=c,{prefixItems:_}=u;if(g.items=!0,mT.alwaysValidSchema(g,l))return;if(_)_T.validateAdditionalItems(c,_);else c.ok(gT.validateArray(c))}};ad.default=wT});var ld=i(function(cd){Object.defineProperty(cd,"__esModule",{value:!0});var Ce=B(),ro=X(),TT={message:({params:{min:c,max:l}})=>l===void 0?Ce.str`must contain at least ${c} valid item(s)`:Ce.str`must contain at least ${c} and no more than ${l} valid item(s)`,params:({params:{min:c,max:l}})=>l===void 0?Ce._`{minContains: ${c}}`:Ce._`{minContains: ${c}, maxContains: ${l}}`},bT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:TT,code(c){let{gen:l,schema:u,parentSchema:g,data:_,it:y}=c,T,b,{minContains:E,maxContains:S}=g;if(y.opts.next)T=E===void 0?1:E,b=S;else T=1;let k=l.const("len",Ce._`${_}.length`);if(c.setParams({min:T,max:b}),b===void 0&&T===0){ro.checkStrictMode(y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(b!==void 0&&T>b){ro.checkStrictMode(y,'"minContains" > "maxContains" is always invalid'),c.fail();return}if(ro.alwaysValidSchema(y,u)){let I=Ce._`${k} >= ${T}`;if(b!==void 0)I=Ce._`${I} && ${k} <= ${b}`;c.pass(I);return}y.items=!0;let A=l.name("valid");if(b===void 0&&T===1)C(A,()=>l.if(A,()=>l.break()));else if(T===0){if(l.let(A,!0),b!==void 0)l.if(Ce._`${_}.length > 0`,z)}else l.let(A,!1),z();c.result(A,()=>c.reset());function z(){let I=l.name("_valid"),M=l.let("count",0);C(I,()=>l.if(I,()=>P(M)))}function C(I,M){l.forRange("i",0,k,(N)=>{c.subschema({keyword:"contains",dataProp:N,dataPropType:ro.Type.Num,compositeRule:!0},I),M()})}function P(I){if(l.code(Ce._`${I}++`),b===void 0)l.if(Ce._`${I} >= ${T}`,()=>l.assign(A,!0).break());else if(l.if(Ce._`${I} > ${b}`,()=>l.assign(A,!1).break()),T===1)l.assign(A,!0);else l.if(Ce._`${I} >= ${T}`,()=>l.assign(A,!0))}}};cd.default=bT});var md=i(function(pd){Object.defineProperty(pd,"__esModule",{value:!0});pd.validateSchemaDeps=pd.validatePropertyDeps=pd.error=void 0;var ca=B(),ET=X(),Kr=Pe();pd.error={message:({params:{property:c,depsCount:l,deps:u}})=>ca.str`must have ${l===1?"property":"properties"} ${u} when property ${c} is present`,params:({params:{property:c,depsCount:l,deps:u,missingProperty:g}})=>ca._`{property: ${c},
|
|
6
|
+
missingProperty: ${g},
|
|
7
|
+
depsCount: ${l},
|
|
8
|
+
deps: ${u}}`};var ST={keyword:"dependencies",type:"object",schemaType:"object",error:pd.error,code(c){let[l,u]=xT(c);ud(c,l),dd(c,u)}};function xT({schema:c}){let l={},u={};for(let g in c){if(g==="__proto__")continue;let _=Array.isArray(c[g])?l:u;_[g]=c[g]}return[l,u]}function ud(c,l=c.schema){let{gen:u,data:g,it:_}=c;if(Object.keys(l).length===0)return;let y=u.let("missing");for(let T in l){let b=l[T];if(b.length===0)continue;let E=Kr.propertyInData(u,g,T,_.opts.ownProperties);if(c.setParams({property:T,depsCount:b.length,deps:b.join(", ")}),_.allErrors)u.if(E,()=>{for(let S of b)Kr.checkReportMissingProp(c,S)});else u.if(ca._`${E} && (${Kr.checkMissingProp(c,b,y)})`),Kr.reportMissingProp(c,y),u.else()}}pd.validatePropertyDeps=ud;function dd(c,l=c.schema){let{gen:u,data:g,keyword:_,it:y}=c,T=u.name("valid");for(let b in l){if(ET.alwaysValidSchema(y,l[b]))continue;u.if(Kr.propertyInData(u,g,b,y.opts.ownProperties),()=>{let E=c.subschema({keyword:_,schemaProp:b},T);c.mergeValidEvaluated(E,T)},()=>u.var(T,!0)),c.ok(T)}}pd.validateSchemaDeps=dd;pd.default=ST});var yd=i(function(_d){Object.defineProperty(_d,"__esModule",{value:!0});var gd=B(),AT=X(),PT={message:"property name must be valid",params:({params:c})=>gd._`{propertyName: ${c.propertyName}}`},CT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:PT,code(c){let{gen:l,schema:u,data:g,it:_}=c;if(AT.alwaysValidSchema(_,u))return;let y=l.name("valid");l.forIn("key",g,(T)=>{c.setParams({propertyName:T}),c.subschema({keyword:"propertyNames",data:T,dataTypes:["string"],propertyName:T,compositeRule:!0},y),l.if(gd.not(y),()=>{if(c.error(!0),!_.allErrors)l.break()})}),c.ok(y)}};_d.default=CT});var ua=i(function(wd){Object.defineProperty(wd,"__esModule",{value:!0});var no=Pe(),De=B(),zT=Ze(),oo=X(),OT={message:"must NOT have additional properties",params:({params:c})=>De._`{additionalProperty: ${c.additionalProperty}}`},MT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:OT,code(c){let{gen:l,schema:u,parentSchema:g,data:_,errsCount:y,it:T}=c;if(!y)throw Error("ajv implementation error");let{allErrors:b,opts:E}=T;if(T.props=!0,E.removeAdditional!=="all"&&oo.alwaysValidSchema(T,u))return;let S=no.allSchemaProperties(g.properties),k=no.allSchemaProperties(g.patternProperties);A(),c.ok(De._`${y} === ${zT.default.errors}`);function A(){l.forIn("key",_,(M)=>{if(!S.length&&!k.length)P(M);else l.if(z(M),()=>P(M))})}function z(M){let N;if(S.length>8){let D=oo.schemaRefOrVal(T,g.properties,"properties");N=no.isOwnProperty(l,D,M)}else if(S.length)N=De.or(...S.map((D)=>De._`${M} === ${D}`));else N=De.nil;if(k.length)N=De.or(N,...k.map((D)=>De._`${no.usePattern(c,D)}.test(${M})`));return De.not(N)}function C(M){l.code(De._`delete ${_}[${M}]`)}function P(M){if(E.removeAdditional==="all"||E.removeAdditional&&u===!1){C(M);return}if(u===!1){if(c.setParams({additionalProperty:M}),c.error(),!b)l.break();return}if(typeof u=="object"&&!oo.alwaysValidSchema(T,u)){let N=l.name("valid");if(E.removeAdditional==="failing")I(M,N,!1),l.if(De.not(N),()=>{c.reset(),C(M)});else if(I(M,N),!b)l.if(De.not(N),()=>l.break())}}function I(M,N,D){let U={keyword:"additionalProperties",dataProp:M,dataPropType:oo.Type.Str};if(D===!1)Object.assign(U,{compositeRule:!0,createErrors:!1,allErrors:!1});c.subschema(U,N)}}};wd.default=MT});var Rd=i(function(bd){Object.defineProperty(bd,"__esModule",{value:!0});var qT=Ar(),Td=Pe(),da=X(),vd=ua(),DT={keyword:"properties",type:"object",schemaType:"object",code(c){let{gen:l,schema:u,parentSchema:g,data:_,it:y}=c;if(y.opts.removeAdditional==="all"&&g.additionalProperties===void 0)vd.default.code(new qT.KeywordCxt(y,vd.default,"additionalProperties"));let T=Td.allSchemaProperties(u);for(let A of T)y.definedProperties.add(A);if(y.opts.unevaluated&&T.length&&y.props!==!0)y.props=da.mergeEvaluated.props(l,da.toHash(T),y.props);let b=T.filter((A)=>!da.alwaysValidSchema(y,u[A]));if(b.length===0)return;let E=l.name("valid");for(let A of b){if(S(A))k(A);else{if(l.if(Td.propertyInData(l,_,A,y.opts.ownProperties)),k(A),!y.allErrors)l.else().var(E,!0);l.endIf()}c.it.definedProperties.add(A),c.ok(E)}function S(A){return y.opts.useDefaults&&!y.compositeRule&&u[A].default!==void 0}function k(A){c.subschema({keyword:"properties",schemaProp:A,dataProp:A},E)}}};bd.default=DT});var $d=i(function(kd){Object.defineProperty(kd,"__esModule",{value:!0});var Ed=Pe(),so=B(),Sd=X(),xd=X(),LT={keyword:"patternProperties",type:"object",schemaType:"object",code(c){let{gen:l,schema:u,data:g,parentSchema:_,it:y}=c,{opts:T}=y,b=Ed.allSchemaProperties(u),E=b.filter((I)=>Sd.alwaysValidSchema(y,u[I]));if(b.length===0||E.length===b.length&&(!y.opts.unevaluated||y.props===!0))return;let S=T.strictSchema&&!T.allowMatchingProperties&&_.properties,k=l.name("valid");if(y.props!==!0&&!(y.props instanceof so.Name))y.props=xd.evaluatedPropsToName(l,y.props);let{props:A}=y;z();function z(){for(let I of b){if(S)C(I);if(y.allErrors)P(I);else l.var(k,!0),P(I),l.if(k)}}function C(I){for(let M in S)if(new RegExp(I).test(M))Sd.checkStrictMode(y,`property ${M} matches pattern ${I} (use allowMatchingProperties)`)}function P(I){l.forIn("key",g,(M)=>{l.if(so._`${Ed.usePattern(c,I)}.test(${M})`,()=>{let N=E.includes(I);if(!N)c.subschema({keyword:"patternProperties",schemaProp:I,dataProp:M,dataPropType:xd.Type.Str},k);if(y.opts.unevaluated&&A!==!0)l.assign(so._`${A}[${M}]`,!0);else if(!N&&!y.allErrors)l.if(so.not(k),()=>l.break())})})}}};kd.default=LT});var Pd=i(function(Ad){Object.defineProperty(Ad,"__esModule",{value:!0});var FT=X(),HT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(c){let{gen:l,schema:u,it:g}=c;if(FT.alwaysValidSchema(g,u)){c.fail();return}let _=l.name("valid");c.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},_),c.failResult(_,()=>c.reset(),()=>c.error())},error:{message:"must NOT be valid"}};Ad.default=HT});var Id=i(function(Cd){Object.defineProperty(Cd,"__esModule",{value:!0});var WT=Pe(),KT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:WT.validateUnion,error:{message:"must match a schema in anyOf"}};Cd.default=KT});var Od=i(function(zd){Object.defineProperty(zd,"__esModule",{value:!0});var ao=B(),GT=X(),ZT={message:"must match exactly one schema in oneOf",params:({params:c})=>ao._`{passingSchemas: ${c.passing}}`},XT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ZT,code(c){let{gen:l,schema:u,parentSchema:g,it:_}=c;if(!Array.isArray(u))throw Error("ajv implementation error");if(_.opts.discriminator&&g.discriminator)return;let y=u,T=l.let("valid",!1),b=l.let("passing",null),E=l.name("_valid");c.setParams({passing:b}),l.block(S),c.result(T,()=>c.reset(),()=>c.error(!0));function S(){y.forEach((k,A)=>{let z;if(GT.alwaysValidSchema(_,k))l.var(E,!0);else z=c.subschema({keyword:"oneOf",schemaProp:A,compositeRule:!0},E);if(A>0)l.if(ao._`${E} && ${T}`).assign(T,!1).assign(b,ao._`[${b}, ${A}]`).else();l.if(E,()=>{if(l.assign(T,!0),l.assign(b,A),z)c.mergeEvaluated(z,ao.Name)})})}}};zd.default=XT});var Nd=i(function(Md){Object.defineProperty(Md,"__esModule",{value:!0});var YT=X(),QT={keyword:"allOf",schemaType:"array",code(c){let{gen:l,schema:u,it:g}=c;if(!Array.isArray(u))throw Error("ajv implementation error");let _=l.name("valid");u.forEach((y,T)=>{if(YT.alwaysValidSchema(g,y))return;let b=c.subschema({keyword:"allOf",schemaProp:T},_);c.ok(_),c.mergeEvaluated(b)})}};Md.default=QT});var Ld=i(function(jd){Object.defineProperty(jd,"__esModule",{value:!0});var io=B(),Dd=X(),tb={message:({params:c})=>io.str`must match "${c.ifClause}" schema`,params:({params:c})=>io._`{failingKeyword: ${c.ifClause}}`},rb={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:tb,code(c){let{gen:l,parentSchema:u,it:g}=c;if(u.then===void 0&&u.else===void 0)Dd.checkStrictMode(g,'"if" without "then" and "else" is ignored');let _=qd(g,"then"),y=qd(g,"else");if(!_&&!y)return;let T=l.let("valid",!0),b=l.name("_valid");if(E(),c.reset(),_&&y){let k=l.let("ifClause");c.setParams({ifClause:k}),l.if(b,S("then",k),S("else",k))}else if(_)l.if(b,S("then"));else l.if(io.not(b),S("else"));c.pass(T,()=>c.error(!0));function E(){let k=c.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},b);c.mergeEvaluated(k)}function S(k,A){return()=>{let z=c.subschema({keyword:k},b);if(l.assign(T,b),c.mergeValidEvaluated(z,T),A)l.assign(A,io._`${k}`);else c.setParams({ifClause:k})}}}};function qd(c,l){let u=c.schema[l];return u!==void 0&&!Dd.alwaysValidSchema(c,u)}jd.default=rb});var Fd=i(function(Ud){Object.defineProperty(Ud,"__esModule",{value:!0});var ob=X(),sb={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:c,parentSchema:l,it:u}){if(l.if===void 0)ob.checkStrictMode(u,`"${c}" without "if" is ignored`)}};Ud.default=sb});var Vd=i(function(Hd){Object.defineProperty(Hd,"__esModule",{value:!0});var ib=aa(),cb=od(),lb=ia(),ub=id(),db=ld(),pb=md(),fb=yd(),hb=ua(),mb=Rd(),gb=$d(),_b=Pd(),yb=Id(),wb=Od(),vb=Nd(),Tb=Ld(),bb=Fd();function Rb(c=!1){let l=[_b.default,yb.default,wb.default,vb.default,Tb.default,bb.default,fb.default,hb.default,pb.default,mb.default,gb.default];if(c)l.push(cb.default,ub.default);else l.push(ib.default,lb.default);return l.push(db.default),l}Hd.default=Rb});var Kd=i(function(Wd){Object.defineProperty(Wd,"__esModule",{value:!0});var se=B(),Sb={message:({schemaCode:c})=>se.str`must match format "${c}"`,params:({schemaCode:c})=>se._`{format: ${c}}`},xb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Sb,code(c,l){let{gen:u,data:g,$data:_,schema:y,schemaCode:T,it:b}=c,{opts:E,errSchemaPath:S,schemaEnv:k,self:A}=b;if(!E.validateFormats)return;if(_)z();else C();function z(){let P=u.scopeValue("formats",{ref:A.formats,code:E.code.formats}),I=u.const("fDef",se._`${P}[${T}]`),M=u.let("fType"),N=u.let("format");u.if(se._`typeof ${I} == "object" && !(${I} instanceof RegExp)`,()=>u.assign(M,se._`${I}.type || "string"`).assign(N,se._`${I}.validate`),()=>u.assign(M,se._`"string"`).assign(N,I)),c.fail$data(se.or(D(),U()));function D(){if(E.strictSchema===!1)return se.nil;return se._`${T} && !${N}`}function U(){let F=k.$async?se._`(${I}.async ? await ${N}(${g}) : ${N}(${g}))`:se._`${N}(${g})`,O=se._`(typeof ${N} == "function" ? ${F} : ${N}.test(${g}))`;return se._`${N} && ${N} !== true && ${M} === ${l} && !${O}`}}function C(){let P=A.formats[y];if(!P){D();return}if(P===!0)return;let[I,M,N]=U(P);if(I===l)c.pass(F());function D(){if(E.strictSchema===!1){A.logger.warn(O());return}throw Error(O());function O(){return`unknown format "${y}" ignored in schema at path "${S}"`}}function U(O){let H=O instanceof RegExp?se.regexpCode(O):E.code.formats?se._`${E.code.formats}${se.getProperty(y)}`:void 0,ee=u.scopeValue("formats",{key:y,ref:O,code:H});if(typeof O=="object"&&!(O instanceof RegExp))return[O.type||"string",O.validate,se._`${ee}.validate`];return["string",O,ee]}function F(){if(typeof P=="object"&&!(P instanceof RegExp)&&P.async){if(!k.$async)throw Error("async format in sync schema");return se._`await ${N}(${g})`}return typeof M=="function"?se._`${N}(${g})`:se._`${N}.test(${g})`}}}};Wd.default=xb});var Gd=i(function(Bd){Object.defineProperty(Bd,"__esModule",{value:!0});var $b=Kd(),Ab=[$b.default];Bd.default=Ab});var Jd=i(function(Zd){Object.defineProperty(Zd,"__esModule",{value:!0});Zd.contentVocabulary=Zd.metadataVocabulary=void 0;Zd.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zd.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ep=i(function(Qd){Object.defineProperty(Qd,"__esModule",{value:!0});var Ib=vu(),zb=Zu(),Ob=Vd(),Mb=Gd(),Yd=Jd(),Nb=[Ib.default,zb.default,(0,Ob.default)(),Mb.default,Yd.metadataVocabulary,Yd.contentVocabulary];Qd.default=Nb});var sp=i(function(np){Object.defineProperty(np,"__esModule",{value:!0});np.DiscrError=void 0;var tp;(function(c){c.Tag="tag",c.Mapping="mapping"})(tp||(np.DiscrError=tp={}))});var cp=i(function(ip){Object.defineProperty(ip,"__esModule",{value:!0});var Zt=B(),pa=sp(),ap=qn(),Db=Pr(),jb=X(),Lb={message:({params:{discrError:c,tagName:l}})=>c===pa.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:c,tag:l,tagName:u}})=>Zt._`{error: ${c}, tag: ${u}, tagValue: ${l}}`},Ub={keyword:"discriminator",type:"object",schemaType:"object",error:Lb,code(c){let{gen:l,data:u,schema:g,parentSchema:_,it:y}=c,{oneOf:T}=_;if(!y.opts.discriminator)throw Error("discriminator: requires discriminator option");let b=g.propertyName;if(typeof b!="string")throw Error("discriminator: requires propertyName");if(g.mapping)throw Error("discriminator: mapping is not supported");if(!T)throw Error("discriminator: requires oneOf keyword");let E=l.let("valid",!1),S=l.const("tag",Zt._`${u}${Zt.getProperty(b)}`);l.if(Zt._`typeof ${S} == "string"`,()=>k(),()=>c.error(!1,{discrError:pa.DiscrError.Tag,tag:S,tagName:b})),c.ok(E);function k(){let C=z();l.if(!1);for(let P in C)l.elseIf(Zt._`${S} === ${P}`),l.assign(E,A(C[P]));l.else(),c.error(!1,{discrError:pa.DiscrError.Mapping,tag:S,tagName:b}),l.endIf()}function A(C){let P=l.name("valid"),I=c.subschema({keyword:"oneOf",schemaProp:C},P);return c.mergeEvaluated(I,Zt.Name),P}function z(){var C;let P={},I=N(_),M=!0;for(let F=0;F<T.length;F++){let O=T[F];if((O===null||O===void 0?void 0:O.$ref)&&!jb.schemaHasRulesButRef(O,y.self.RULES)){let ee=O.$ref;if(O=ap.resolveRef.call(y.self,y.schemaEnv.root,y.baseId,ee),O instanceof ap.SchemaEnv)O=O.schema;if(O===void 0)throw new Db.default(y.opts.uriResolver,y.baseId,ee)}let H=(C=O===null||O===void 0?void 0:O.properties)===null||C===void 0?void 0:C[b];if(typeof H!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${b}"`);M=M&&(I||N(O)),D(H,F)}if(!M)throw Error(`discriminator: "${b}" must be required`);return P;function N({required:F}){return Array.isArray(F)&&F.includes(b)}function D(F,O){if(F.const)U(F.const,O);else if(F.enum)for(let H of F.enum)U(H,O);else throw Error(`discriminator: "properties/${b}" must have "const" or "enum"`)}function U(F,O){if(typeof F!="string"||F in P)throw Error(`discriminator: "${b}" values must be unique strings`);P[F]=O}}}};ip.default=Ub});var up=i(function(eA,Hb){Hb.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ha=i(function(Re,fa){Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var Vb=uu(),Wb=ep(),Kb=cp(),dp=up(),Bb=["/properties"],co="http://json-schema.org/draft-07/schema";class Br extends Vb.default{_addVocabularies(){if(super._addVocabularies(),Wb.default.forEach((c)=>this.addVocabulary(c)),this.opts.discriminator)this.addKeyword(Kb.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let c=this.opts.$data?this.$dataMetaSchema(dp,Bb):dp;this.addMetaSchema(c,co,!1),this.refs["http://json-schema.org/schema"]=co}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(co)?co:void 0)}}Re.Ajv=Br;fa.exports=Re=Br;fa.exports.Ajv=Br;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=Br;var Gb=Ar();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return Gb.KeywordCxt}});var Xt=B();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return Xt._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return Xt.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return Xt.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return Xt.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return Xt.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return Xt.CodeGen}});var Zb=Mn();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return Zb.default}});var Xb=Pr();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return Xb.default}})});var Tp=i(function(wp){Object.defineProperty(wp,"__esModule",{value:!0});wp.formatNames=wp.fastFormats=wp.fullFormats=void 0;function Ve(c,l){return{validate:c,compare:l}}wp.fullFormats={date:Ve(mp,wa),time:Ve(_a(!0),va),"date-time":Ve(pp(!0),_p),"iso-time":Ve(_a(),gp),"iso-date-time":Ve(pp(),yp),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:oR,"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:dR,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:sR,int32:{type:"number",validate:cR},int64:{type:"number",validate:lR},float:{type:"number",validate:hp},double:{type:"number",validate:hp},password:!0,binary:!0};wp.fastFormats={...wp.fullFormats,date:Ve(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,wa),time:Ve(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,va),"date-time":Ve(/^\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,_p),"iso-time":Ve(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gp),"iso-date-time":Ve(/^\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,yp),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};wp.formatNames=Object.keys(wp.fullFormats);function Qb(c){return c%4===0&&(c%100!==0||c%400===0)}var eR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function mp(c){let l=eR.exec(c);if(!l)return!1;let u=+l[1],g=+l[2],_=+l[3];return g>=1&&g<=12&&_>=1&&_<=(g===2&&Qb(u)?29:tR[g])}function wa(c,l){if(!(c&&l))return;if(c>l)return 1;if(c<l)return-1;return 0}var ma=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function _a(c){return function(u){let g=ma.exec(u);if(!g)return!1;let _=+g[1],y=+g[2],T=+g[3],b=g[4],E=g[5]==="-"?-1:1,S=+(g[6]||0),k=+(g[7]||0);if(S>23||k>59||c&&!b)return!1;if(_<=23&&y<=59&&T<60)return!0;let A=y-k*E,z=_-S*E-(A<0?1:0);return(z===23||z===-1)&&(A===59||A===-1)&&T<61}}function va(c,l){if(!(c&&l))return;let u=new Date("2020-01-01T"+c).valueOf(),g=new Date("2020-01-01T"+l).valueOf();if(!(u&&g))return;return u-g}function gp(c,l){if(!(c&&l))return;let u=ma.exec(c),g=ma.exec(l);if(!(u&&g))return;if(c=u[1]+u[2]+u[3],l=g[1]+g[2]+g[3],c>l)return 1;if(c<l)return-1;return 0}var ya=/t|\s/i;function pp(c){let l=_a(c);return function(g){let _=g.split(ya);return _.length===2&&mp(_[0])&&l(_[1])}}function _p(c,l){if(!(c&&l))return;let u=new Date(c).valueOf(),g=new Date(l).valueOf();if(!(u&&g))return;return u-g}function yp(c,l){if(!(c&&l))return;let[u,g]=c.split(ya),[_,y]=l.split(ya),T=wa(u,_);if(T===void 0)return;return T||va(g,y)}var rR=/\/|:/,nR=/^(?:[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 oR(c){return rR.test(c)&&nR.test(c)}var fp=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function sR(c){return fp.lastIndex=0,fp.test(c)}var aR=-2147483648,iR=2147483647;function cR(c){return Number.isInteger(c)&&c<=iR&&c>=aR}function lR(c){return Number.isInteger(c)}function hp(){return!0}var uR=/[^\\]\\Z/;function dR(c){if(uR.test(c))return!1;try{return new RegExp(c),!0}catch(l){return!1}}});var Rp=i(function(bp){Object.defineProperty(bp,"__esModule",{value:!0});bp.formatLimitDefinition=void 0;var fR=ha(),Ue=B(),ft=Ue.operators,lo={formatMaximum:{okStr:"<=",ok:ft.LTE,fail:ft.GT},formatMinimum:{okStr:">=",ok:ft.GTE,fail:ft.LT},formatExclusiveMaximum:{okStr:"<",ok:ft.LT,fail:ft.GTE},formatExclusiveMinimum:{okStr:">",ok:ft.GT,fail:ft.LTE}},hR={message:({keyword:c,schemaCode:l})=>Ue.str`should be ${lo[c].okStr} ${l}`,params:({keyword:c,schemaCode:l})=>Ue._`{comparison: ${lo[c].okStr}, limit: ${l}}`};bp.formatLimitDefinition={keyword:Object.keys(lo),type:"string",schemaType:"string",$data:!0,error:hR,code(c){let{gen:l,data:u,schemaCode:g,keyword:_,it:y}=c,{opts:T,self:b}=y;if(!T.validateFormats)return;let E=new fR.KeywordCxt(y,b.RULES.all.format.definition,"format");if(E.$data)S();else k();function S(){let z=l.scopeValue("formats",{ref:b.formats,code:T.code.formats}),C=l.const("fmt",Ue._`${z}[${E.schemaCode}]`);c.fail$data(Ue.or(Ue._`typeof ${C} != "object"`,Ue._`${C} instanceof RegExp`,Ue._`typeof ${C}.compare != "function"`,A(C)))}function k(){let z=E.schema,C=b.formats[z];if(!C||C===!0)return;if(typeof C!="object"||C instanceof RegExp||typeof C.compare!="function")throw Error(`"${_}": format "${z}" does not define "compare" function`);let P=l.scopeValue("formats",{key:z,ref:C,code:T.code.formats?Ue._`${T.code.formats}${Ue.getProperty(z)}`:void 0});c.fail$data(A(P))}function A(z){return Ue._`${z}.compare(${u}, ${g}) ${lo[_].fail} 0`}},dependencies:["format"]};var mR=(c)=>(c.addKeyword(bp.formatLimitDefinition),c);bp.default=mR});var kp=i(function(Gr,xp){Object.defineProperty(Gr,"__esModule",{value:!0});var Jt=Tp(),_R=Rp(),Ra=B(),Ep=new Ra.Name("fullFormats"),yR=new Ra.Name("fastFormats"),Ea=(c,l={keywords:!0})=>{if(Array.isArray(l))return Sp(c,l,Jt.fullFormats,Ep),c;let[u,g]=l.mode==="fast"?[Jt.fastFormats,yR]:[Jt.fullFormats,Ep],_=l.formats||Jt.formatNames;if(Sp(c,_,u,g),l.keywords)(0,_R.default)(c);return c};Ea.get=(c,l="full")=>{let g=(l==="fast"?Jt.fastFormats:Jt.fullFormats)[c];if(!g)throw Error(`Unknown format "${c}"`);return g};function Sp(c,l,u,g){var _,y;(_=(y=c.opts.code).formats)!==null&&_!==void 0||(y.formats=Ra._`require("ajv-formats/dist/formats").${g}`);for(let T of l)c.addFormat(T,u[T])}xp.exports=Gr=Ea;Object.defineProperty(Gr,"__esModule",{value:!0});Gr.default=Ea});var uf="Model reached the maximum output token limit before completing the turn",Po=3,df="Your previous response was cut off because it reached the model's output-token limit before finishing. Keep responses concise: take one small step at a time, avoid long explanations, and write large files or command output in smaller chunks across multiple tool calls.",Co=3,pf=1000,ff=15000,hf="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",mf="The request exceeds the model's context window and there is no conversation history to compact — the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.",gf="The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.",_f="The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";class zt extends Error{constructor(c,l){super(l?.trim()?`${c} (provider reported: ${l.trim()})`:c);this.name="ContextWindowOverflowError"}}function Ke(c,l=8){return`${c}_${R(l)}`}function yf(c){return c.model!==void 0}function wf(c){if(yf(c))return c;let{providerId:l,modelId:u,apiKey:g,baseUrl:_,headers:y,options:T,...b}=c,S=Ws({providerConfigs:[{providerId:l,apiKey:g,baseUrl:_,headers:y,options:T}],telemetry:b.telemetry}).createAgentModel({providerId:l,modelId:u}),k=b.messageModelInfo??{id:u,provider:l};return{...b,model:S,messageModelInfo:k}}function vf(c,l){return{...l?.["*"]??{},...l?.[c]??{}}}function zo(c){try{return JSON.stringify(c).length}catch{return String(c).length}}function Tf(c){if(typeof c==="string")return c.length;return zo(c)}function bf(c){let l=c.systemPrompt?.length??0,u=0,g=0,_=0;for(let y of c.messages)for(let T of y.content)switch(T.type){case"text":l+=T.text.length;break;case"reasoning":l+=T.text.length;break;case"file":l+=T.content.length;break;case"tool-call":l+=zo(T.input);break;case"tool-result":{let b=Tf(T.output);u+=1,g+=b,_=Math.max(_,b),l+=b;break}}return{messageCount:c.messages.length,toolSchemaCount:c.tools.length,systemPromptChars:c.systemPrompt?.length??0,requestJsonChars:zo({systemPrompt:c.systemPrompt,messages:c.messages,tools:c.tools,options:c.options}),visibleTextChars:l,estimatedTextTokens:Dr(l),toolResultCount:u,toolResultChars:g,maxToolResultChars:_}}class Oo extends Error{reason;constructor(c){super(c??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=c}}class pc extends Error{reason;constructor(c){let l=typeof c==="string"?c:c instanceof Error?c.message:c===void 0?"Run aborted":String(c);super(l);this.name="AgentRuntimeAbortError",this.reason=c}}var Io={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function _t(c,l,u){return{id:Ke("msg"),role:c,content:l,createdAt:Date.now(),metadata:u}}function tt(c){return{...c}}var Rf={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Xa(c){return c.replace(/[_"<>]/g,(l)=>Rf[l])}function en(c,l){let u=[`source="${c.source}"`];if("toolCall"in c)u.push(`tool_name="${Xa(c.toolCall.toolName)}"`,`tool_call_id="${Xa(c.toolCall.toolCallId)}"`);let g=l.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${u.join(" ")}>
|
|
9
|
+
${g}
|
|
10
|
+
</hook_context>`}function xe(c){return c.map((l)=>({...l,content:l.content.map((u)=>({...u})),metadata:l.metadata?{...l.metadata}:void 0,modelInfo:l.modelInfo?{...l.modelInfo}:void 0,metrics:l.metrics?{...l.metrics}:void 0}))}function Ef(c,l){let u=Math.max(0,(l.inputTokens??0)-(c.inputTokens??0)),g=Math.max(0,(l.outputTokens??0)-(c.outputTokens??0)),_=Math.max(0,(l.cacheReadTokens??0)-(c.cacheReadTokens??0)),y=Math.max(0,(l.cacheWriteTokens??0)-(c.cacheWriteTokens??0)),T=Math.max(0,(l.reasoningTokenCount??0)-(c.reasoningTokenCount??0)),b=c.totalCost??0,E=l.totalCost??0,S=Math.max(0,E-b);if(u===0&&g===0&&_===0&&y===0&&T===0&&S===0)return;return{inputTokens:u>0?u:0,outputTokens:g>0?g:0,cacheReadTokens:_>0?_:0,cacheWriteTokens:y>0?y:0,...T>0?{reasoningTokenCount:T}:{},...S>0?{cost:S}:{}}}function Sf(c){return c.options?.thinking===!1}function Ja(c){if(!c)return"";return c.content.filter((l)=>l.type==="text").map((l)=>l.text).join("")}function xf(c){let l=c?.content.find((u)=>u.type==="tool-result");if(!l||l.isError)return"";if(typeof l.output==="string")return l.output;try{return JSON.stringify(l.output)}catch{return String(l.output)}}function kf(c){if(typeof c==="string")return[_t("user",[{type:"text",text:c}])];if(Array.isArray(c))return xe(c);return xe([c])}class rn{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};pendingHookContexts=[];state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:tt(Io),lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};overflowRecoveryAttempted=!1;maxTokensRecoveryCount=0;maxTokensRecoveryAttempted=!1;initialization;abortController;modelSteerController;telemetryProviderId;telemetryModelId;modelRequestId;constructor(c){this.telemetryProviderId=fi(c.messageModelInfo?.provider)??("providerId"in c?fi(c.providerId):void 0),this.telemetryModelId=fi(c.messageModelInfo?.id)??("modelId"in c?fi(c.modelId):void 0);let l=wf(c);this.config={...l,toolExecution:l.toolExecution??"sequential"},this.state.agentId=l.agentId??Ke("agent"),this.state.agentRole=l.agentRole,this.state.parentAgentId=l.parentAgentId,this.state.messages=xe(l.initialMessages??[])}async run(c){return this.execute(c)}async continue(c){return this.execute(c)}notifyPendingUserMessage(){this.modelSteerController?.abort()}abort(c){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let l=c instanceof pc?c:new pc(c);this.state.lastError=l.message,this.captureTaskLifecycle(uy,{error:l}),this.abortController.abort(l)}subscribe(c){return this.listeners.add(c),()=>{this.listeners.delete(c)}}restore(c){this.abort("Agent state restored"),this.state.runId=void 0,this.state.status="idle",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.usage=tt(Io),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=xe(c),this.config={...this.config,initialMessages:xe(c)}}snapshot(){return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,messages:xe(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:tt(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let c of this.config.tools??[])this.tools.set(c.name,c);for(let c of this.config.plugins??[]){let l=await c.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let u of l?.tools??[])this.tools.set(u.name,u);this.registerHooks(l?.hooks)}}registerHooks(c){if(!c)return;if(c.beforeRun)this.hooks.beforeRun.push(c.beforeRun);if(c.afterRun)this.hooks.afterRun.push(c.afterRun);if(c.beforeModel)this.hooks.beforeModel.push(c.beforeModel);if(c.afterModel)this.hooks.afterModel.push(c.afterModel);if(c.beforeTool)this.hooks.beforeTool.push(c.beforeTool);if(c.afterTool)this.hooks.afterTool.push(c.afterTool);if(c.onEvent)this.hooks.onEvent.push(c.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((c)=>c.lifecycle?.completesRun===!0).map((c)=>c.name).sort()}getCompletionToolReminderMessage(){let c=this.getRequiredCompletionToolNames();if(c.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${c.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}getCompletionReminderMessages(){return[this.getCompletionToolReminderMessage(),this.config.completionPolicy?.completionGuard?.()].filter((c)=>Boolean(c))}async addUserReminderMessage(c,l={}){let u=_t("user",[{type:"text",text:c}],{...l,userRunSpan:0});return this.state.messages.push(u),await this.emit({type:"message-added",snapshot:this.snapshot(),message:u}),u}async execute(c){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=Ke("run"),this.modelRequestId=void 0,this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.lastFinishReason=void 0,this.state.usage=tt(Io),this.overflowRecoveryAttempted=!1,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[],this.maxTokensRecoveryCount=0,this.maxTokensRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let g of c?kf(c):[])this.state.messages.push(g),await this.emit({type:"message-added",snapshot:this.snapshot(),message:g});let l=this.getCompletionToolReminderMessage();if(l)await this.addUserReminderMessage(l);await this.flushPendingHookContexts();let u;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration}),this.resetLastError();let{message:g,finishReason:_,interrupted:y}=await this.generateAssistantMessageWithProviderRetry();if(y&&g.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(_==="aborted")throw this.normalizeAbortError();if(g.content.length===0){if(_==="error")throw this.state.lastFinishReason=_,Error(this.state.lastError??"Model stream failed");if(!this.hasModelToolActivity(g)&&_!=="max-tokens"&&_!=="unknown")throw this.state.lastFinishReason=_,Error(_==="content-filter"?hf:"Model returned empty response")}let T=g.content.filter((S)=>S.type==="tool-call");if(u=g,await this.recordAssistantMessage(g,_),y){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(_==="unknown"&&T.length===0)throw this.state.lastFinishReason=_,Error("Model ended without a recognized finish reason");if(_==="max-tokens"&&T.length===0){if(await this.recoverFromIncompleteMaxTokensTurn()){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}throw this.state.lastFinishReason=_,Error(uf)}if(_==="error"&&T.length===0)throw this.state.lastFinishReason=_,Error(this.state.lastError??"Model stream failed");if(T.length>0)this.maxTokensRecoveryCount=0;if(this.state.pendingToolCalls=T.map((S)=>S.toolCallId),T.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let S=this.getCompletionReminderMessages();if(S.length>0){for(let A of S)await this.addUserReminderMessage(A);continue}let k=this.finishRun("completed",u);return await this.callAfterRunHooks(k),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:k}),k}let b=await this.executeToolCalls(T);this.state.pendingToolCalls=[];for(let S of b)this.state.messages.push(S),await this.emit({type:"message-added",snapshot:this.snapshot(),message:S});if(_==="unknown"&&!b.some((S)=>S.content.some((k)=>k.type==="tool-result"&&!k.isError)))throw this.state.lastFinishReason=_,Error("Model ended without a recognized finish reason or successful tool work");await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:T.length});let E=this.findCompletingToolMessage(T,b);if(E){let S=this.finishRun("completed",u,xf(E)||void 0);return await this.callAfterRunHooks(S),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:S}),S}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(l){let u=l instanceof Error?l:Error(String(l)),g=u instanceof Oo,y=this.abortController.signal.aborted||g?"aborted":"failed",T=u instanceof zt?"context_window_exceeded":u.message===this.state.lastError?this.state.lastErrorClass:void 0,b=u.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=y,this.state.lastError=u.message,this.state.lastErrorClass=T,this.state.lastErrorReported=b;let E=this.findLastAssistantMessage(),S={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??Ke("run"),status:y,iterations:this.state.iteration,outputText:Ja(E),messages:xe(this.state.messages),usage:tt(this.state.usage),error:y==="failed"?u:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:y==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:S.runId,status:y,iteration:this.state.iteration,errorName:u.name,errorMessage:u.message,assistantContentPartCount:E?.content.length??0}),await this.callAfterRunHooks(S),y==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:u,errorClass:T});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:S});return S}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let c=this.pendingHookContexts.join(`
|
|
11
|
+
|
|
12
|
+
`);this.pendingHookContexts=[];let l=_t("user",[{type:"text",text:c}],{userRunSpan:0,displayRole:"system"}),u=this.state.messages.at(-1);if(u?.role==="assistant"&&u.content.some((_)=>_.type==="tool-call"))this.state.messages.splice(-1,0,l);else this.state.messages.push(l);await this.emit({type:"message-added",snapshot:this.snapshot(),message:l})}async callBeforeRunHooks(){for(let c of this.hooks.beforeRun){let l=await c({snapshot:this.snapshot()});if(this.applyStopControl(l),l?.appendContext?.trim())this.pendingHookContexts.push(en({source:"RunStart"},l.appendContext))}}async callAfterRunHooks(c){for(let l of this.hooks.afterRun)await l({snapshot:this.snapshot(),result:c})}async recoverFromIncompleteMaxTokensTurn(){if(this.maxTokensRecoveryCount>=Po)return!1;return this.maxTokensRecoveryCount+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`output-token limit reached before a tool call — nudging for a more concise response (attempt ${this.maxTokensRecoveryCount}/${Po})`,metadata:{kind:"max_tokens_recovery",reason:"max_tokens_recovery",phase:"started",iteration:this.state.iteration,attempt:this.maxTokensRecoveryCount,maxRetries:Po}}),await this.addUserReminderMessage(df),!0}async generateAssistantMessageWithProviderRetry(){let c=()=>this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery()),l=await c();if(l.finishReason!=="unknown"||l.interrupted)return l;if(l.message.content.some((u)=>u.type==="tool-call")||this.hasModelToolActivity(l.message))return l;return await this.recordAssistantMessage(l.message,l.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await c()}async withProviderErrorRetry(c){let l=0;for(;;){let u=await c();if(l>=Co||!this.isRetryableProviderErrorTurn(u))return u;l+=1;let g=this.state.lastError;this.resetLastError();let _=Math.min(pf*2**(l-1),ff);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${l}/${Co})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:l,maxRetries:Co,delayMs:_,providerError:g}}),await this.abortableDelay(_)}}isRetryableProviderErrorTurn(c){if(c.finishReason!=="error")return!1;if(c.message.content.some((g)=>g.type!=="reasoning"))return!1;let l=c.message.metadata?.modelToolActivities;if(Array.isArray(l)&&l.length>0)return!1;let u=this.state.lastErrorClass;if(u==="auth"||u==="context_window_exceeded")return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(c){this.throwIfAborted();let l=this.abortController?.signal;await new Promise((u,g)=>{let _=()=>{clearTimeout(y),g(this.normalizeAbortError())},y=setTimeout(()=>{l?.removeEventListener("abort",_),u()},c);if(l)l.addEventListener("abort",_,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){let c=await this.generateAssistantMessage();if(this.isRecoverableMaxTokensTurn(c))return await this.retryTruncatedTurnWithCompaction(c);if(!this.isRecoverableOverflowTurn(c))return c;this.overflowRecoveryAttempted=!0;let l=this.state.lastError;if(!this.config.prepareTurn)throw new zt(_f,l);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:l}});let u=await this.generateAssistantMessage({overflowRecovery:!0});if(u.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new zt(gf,this.state.lastError);return u}isRecoverableOverflowTurn(c){if(c.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!c.message.content.some((l)=>l.type==="tool-call")}isRecoverableMaxTokensTurn(c){if(c.finishReason!=="max-tokens"||this.maxTokensRecoveryAttempted||!this.config.prepareTurn)return!1;if(c.message.content.some((l)=>l.type==="tool-call"))return!1;return!this.hasModelToolActivity(c.message)}hasModelToolActivity(c){let l=c.metadata?.modelToolActivities;return Array.isArray(l)&&l.length>0}async retryTruncatedTurnWithCompaction(c){this.maxTokensRecoveryAttempted=!0;let l={kind:"max_tokens_compaction",reason:"max_tokens_compaction",iteration:this.state.iteration};this.captureTaskLifecycle(ml,{phase:"started"});let u;try{await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"response hit the output token limit — compacting and retrying",metadata:{...l,phase:"started"}});let g=await this.prepareModelRequest({overflowRecovery:!0});u=await this.withProviderErrorRetry(()=>this.issuePreparedRequest(g))}catch(g){if(g instanceof zt)return this.captureTaskLifecycle(ml,{phase:"failed",eventType:"nothing_to_compact"}),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output-token-limit recovery failed: nothing to compact",metadata:{...l,phase:"failed"}}),c;throw this.captureTaskLifecycle(ml,{phase:"failed",eventType:"recovery_threw",error:g}),await this.recordAssistantMessage(c.message,c.finishReason),g}if(this.captureTaskLifecycle(ml,{phase:"retried",eventType:u.finishReason}),u.finishReason==="aborted")throw await this.recordAssistantMessage(c.message,c.finishReason),this.normalizeAbortError();if(u.finishReason==="error"&&!u.message.content.some((g)=>g.type==="tool-call")){if(await this.recordAssistantMessage(c.message,c.finishReason),u.message.content.length>0||this.hasModelToolActivity(u.message))await this.recordAssistantMessage(u.message,u.finishReason);throw Error(this.state.lastError??"Model stream failed")}if(u.message.content.length===0&&!this.hasModelToolActivity(u.message))return c;return u}async recordAssistantMessage(c,l){this.state.messages.push(c),await this.emit({type:"message-added",snapshot:this.snapshot(),message:c}),await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:c,finishReason:l})}async generateAssistantMessage(c){let l=new AbortController;this.modelSteerController=l;try{return await this.generateAssistantMessageForRequest(l,c)}finally{this.modelSteerController=void 0}}async issuePreparedRequest(c){let l=new AbortController;this.modelSteerController=l;try{return await this.streamPreparedRequest({...c,startedAt:Date.now()},l)}finally{this.modelSteerController=void 0}}async prepareModelRequest(c){let l=ty({distinctId:fi(this.config.distinctId),clientName:fi(this.config.clientName),clientVersion:fi(this.config.clientVersion),clineCoreVersion:fi(this.config.clineCoreVersion),sessionId:fi(this.config.sessionId),agentId:this.state.agentId,conversationId:fi(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),u={systemPrompt:this.config.systemPrompt,messages:xe(this.state.messages),tools:[...this.tools.values()].map((y)=>({name:y.name,description:y.description,inputSchema:y.inputSchema})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:rp(this.config.modelOptions,{metadata:l})},g=Date.now(),_=await this.consumePendingUserMessage();if(_)u={...u,messages:[...u.messages,...xe([_])]};u=await this.prepareTurnForModelRequest(u,c),this.throwIfAborted();for(let y of this.hooks.beforeModel){let T=await y({snapshot:this.snapshot(),request:u});if(this.throwIfAborted(),this.applyStopControl(T),T?.messages)u={...u,messages:xe(T.messages)};if(T?.tools)u={...u,tools:[...T.tools]};if(T?.options)u={...u,options:rp(u.options,T.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...bf(u)}),{request:u,startedAt:g}}async generateAssistantMessageForRequest(c,l){let u=await this.prepareModelRequest(l);return await this.streamPreparedRequest(u,c)}async streamPreparedRequest(c,l){let u=tt(this.state.usage),g=()=>Date.now()-c.startedAt,_=c.request;this.throwIfAborted(),this.modelRequestId=Ke("model_request",21),_={..._,options:rp(_.options,{metadata:{modelRequestId:this.modelRequestId}})},this.captureTaskLifecycle(ry,{durationMs:g(),phase:"provider_request_started"}),_={..._,signal:AbortSignal.any([l.signal,...this.abortController?[this.abortController.signal]:[]])};let y=this.openTaskLifecycleStream(_,g),T=[],b=new Map,E=new Map,S=0,k=[],A=[],z=0,C="unknown",P,I="",M="";for await(let O of y){if(l.signal.aborted)break;switch(this.throwIfAborted(),O.type){case"text-delta":{I+=O.text;let H=A.at(-1);if(H?.type==="part"&&H.part.type==="text")H.part.text+=O.text;else A.push({type:"part",part:{type:"text",text:O.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:O.text,accumulatedText:I});break}case"media":{A.push({type:"part",part:{type:"media",media:O.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:O.media});break}case"reasoning-delta":{M+=O.text;let H=A.at(-1);if(H?.type==="part"&&H.part.type==="reasoning")H.part.text+=O.text,H.part.redacted=O.redacted??H.part.redacted,H.part.metadata=O.metadata??H.part.metadata;else A.push({type:"part",part:{type:"reasoning",text:O.text,redacted:O.redacted,metadata:O.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:O.text,accumulatedText:M,redacted:O.redacted,metadata:O.metadata});break}case"tool-call-delta":{if(O.execution){let Se={type:"tool-call",toolCallId:O.toolCallId??Ke("model_tool"),toolName:O.toolName??"tool",input:O.input,metadata:O.metadata,execution:O.execution};E.set(Se.toolCallId,{toolCallId:Se.toolCallId,toolName:Se.toolName,execution:O.execution,input:Se.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Se});break}let H=O.toolCallId??`tool_${O.index??z}`;if(O.index==null&&O.toolCallId==null)z+=1;let ee=b.get(H);if(!ee)ee={toolCallId:O.toolCallId??Ke("tool"),inputText:""},b.set(H,ee),A.push({type:"tool",key:H});if(O.toolCallId)ee.toolCallId=O.toolCallId;if(O.toolName)ee.toolName=O.toolName;if(O.input!==void 0)ee.inputValue=O.input;if(O.metadata!==void 0)ee.metadata=Ya(ee.metadata,O.metadata);if(O.inputText)ee.inputText=Cf(ee.inputText,O.inputText);if(Date.now()-S>=1000)S=Date.now(),await this.emit({type:"tool-call-delta",snapshot:this.snapshot(),iteration:this.state.iteration});break}case"tool-result":{let H=E.get(O.toolCallId),ee={...H,toolCallId:O.toolCallId,toolName:O.toolName,execution:O.execution,input:O.input===void 0?H?.input:O.input,output:O.output,isError:O.isError};E.set(O.toolCallId,ee);let Se={type:"tool-call",toolCallId:O.toolCallId,toolName:O.toolName,input:ee.input,execution:O.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Se,message:_t("tool",[{type:"tool-result",toolCallId:O.toolCallId,toolName:O.toolName,output:O.output,isError:O.isError,execution:O.execution}])});break}case"usage":{if(typeof O.usage.inputTokens==="number"&&O.usage.inputTokens>0)this.state.lastRequestInputTokens=O.usage.inputTokens;await this.updateUsage(O.usage);break}case"finish":{if(C=O.reason,P=O.requestId,O.error)this.state.lastError=O.error,this.state.lastErrorClass=O.errorClass??Mr(O.error),this.state.lastErrorRetryable=O.errorRetryable??fc(O.error),this.state.lastErrorReported=O.errorReported===!0;break}}}this.throwIfAborted();let N=l.signal.aborted;if(N)C="stop";for(let O of A){if(N&&(O.type==="tool"||O.part.type==="reasoning"))continue;if(O.type==="part"){T.push(O.part);continue}let H=b.get(O.key);if(!H?.toolName){k.push({toolCallId:H?.toolCallId??O.key,input:tn(H?.inputText??""),reason:"missing_name"});continue}let ee=Af(H);if(ee.reason)k.push({toolCallId:H.toolCallId,toolName:H.toolName,input:ee.invalidInput,reason:ee.reason});T.push({type:"tool-call",toolCallId:H.toolCallId,toolName:H.toolName,input:ee.input,metadata:ee.parseError?Ya(H.metadata,{inputParseError:ee.parseError,rawInputText:H.inputText}):H.metadata})}let D={};if(k.length>0)D.invalidToolCalls=k;if(E.size>0)D.modelToolActivities=[...E.values()];let U=_t("assistant",T,Object.keys(D).length>0?D:void 0),F=Ef(u,this.state.usage);if(F)U.metrics=F,this.captureUnexpectedReasoningTokens(_,F);if(this.config.messageModelInfo)U.modelInfo={...this.config.messageModelInfo};for(let O of this.hooks.afterModel){let H=await O({snapshot:this.snapshot(),assistantMessage:U,finishReason:C,...P?{requestId:P}:{}});this.applyStopControl(H)}return{message:U,finishReason:C,interrupted:N}}async*openTaskLifecycleStream(c,l){let u,g="provider_request_started";try{u=await this.config.model.stream(c),this.throwIfAborted(),g="provider_stream_started",this.captureTaskLifecycle(sy,{durationMs:l(),phase:g})}catch(y){if(c.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!c.signal?.aborted&&!this.isAbortError(y))this.captureTaskLifecycleFailure(y,g,l());throw y}let _=!1;try{for await(let y of u){if(!_)_=!0,g="first_chunk_received",this.captureTaskLifecycle(cy,{durationMs:l(),phase:g,eventType:y.type});yield y}}catch(y){if(c.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!c.signal?.aborted&&!this.isAbortError(y))this.captureTaskLifecycleFailure(y,g,l());throw y}}captureTaskLifecycleFailure(c,l,u){this.captureTaskLifecycle(ly,{durationMs:u,error:c,errorClass:Mr(c),phase:l})}captureTaskLifecycle(c,l={}){let u=fi(this.config.sessionId);dy(this.config.telemetry,{event:c,modelRequestId:this.modelRequestId,sessionId:u,ulid:u,agentId:this.state.agentId,conversationId:fi(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...l})}getTelemetryProviderId(){return fi(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return fi(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(c){return c instanceof pc||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(c,l){if(!Sf(c)||(l.reasoningTokenCount??0)<=0)return;let u=l.reasoningTokenCount;if(u===void 0)return;py(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:u})}async prepareTurnForModelRequest(c,l){if(!this.config.prepareTurn)return c;let u=l?.overflowRecovery===!0,g=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:c.messages,systemPrompt:c.systemPrompt,tools:c.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:c.signal,overflowRecovery:u||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(y,T)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:y,metadata:T})}});if(u){if(!(g?.messages!==void 0&&JSON.stringify(g.messages).length<JSON.stringify(c.messages).length))throw new zt(mf,this.state.lastError)}if(!g)return c;let _=c;if(g.messages){let y=xe(g.messages);_={..._,messages:xe(y)}}if(g.systemPrompt!==void 0)_={..._,systemPrompt:g.systemPrompt};return _}async consumePendingUserMessage(){let c=this.config.consumePendingUserMessage;if(!c)return;let l=(await c())?.trim();if(!l)return;let u=_t("user",[{type:"text",text:l}],{userRunSpan:0});return this.state.messages.push(u),await this.emit({type:"message-added",snapshot:this.snapshot(),message:u}),u}async updateUsage(c){this.state.usage={inputTokens:this.state.usage.inputTokens+(c.inputTokens??0),outputTokens:this.state.usage.outputTokens+(c.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(c.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(c.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(c.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(c.totalCost??0)},await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:tt(this.state.usage)})}async executeToolCalls(c){this.pendingHookContexts=[];let l=[];for(let g of c)l.push(await this.prepareToolExecution(g));let u=[];for(let g=0;g<l.length;){let _=l[g];if((_.tool?.executionMode??this.config.toolExecution)==="sequential"){u.push(await this.executePreparedTool(_)),g+=1;continue}let T=g;while(g<l.length&&(l[g].tool?.executionMode??this.config.toolExecution)==="parallel")g+=1;u.push(...await Promise.all(l.slice(T,g).map((b)=>this.executePreparedTool(b))))}return u}findCompletingToolMessage(c,l){for(let u=0;u<c.length;u+=1){let g=c[u];if(this.tools.get(g.toolName)?.lifecycle?.completesRun!==!0)continue;let _=l[u],y=_?.content.find((T)=>T.type==="tool-result"&&T.toolCallId===g.toolCallId);if(y&&!y.isError)return _}return}async prepareToolExecution(c){let l=this.tools.get(c.toolName),u=c.input,g,_=c.metadata&&typeof c.metadata==="object"&&!Array.isArray(c.metadata)?c.metadata:void 0;if(typeof _?.inputParseError==="string")g=_.inputParseError;let y=_?.toolSource&&typeof _.toolSource==="object"&&!Array.isArray(_.toolSource)?_.toolSource:void 0;if(y?.executionMode==="provider")g=`Tool execution is disabled for provider ${typeof y.providerId==="string"?y.providerId:"provider"}`;if(l&&!g)u=lp(u,l.inputSchema);let T;if(l&&!g)for(let b of this.hooks.beforeTool){let E=await b({snapshot:this.snapshot(),tool:l,toolCall:{...c,input:u},input:u});if(E?.input!==void 0)u=E.input;if(E?.policy)T={...T,...E.policy};if(E?.appendContext?.trim())this.pendingHookContexts.push(en({source:"PreToolUse",toolCall:c},E.appendContext));if(this.applyStopControl(E),E?.skip){g=E.reason??`Tool ${l.name} was blocked by a runtime hook`;break}}if(l&&!g){let b={...vf(c.toolName,this.config.toolPolicies),...T};if(b.enabled===!1)g=`Tool "${c.toolName}" is disabled by policy`;else if(b.autoApprove===!1){let E=await this.requestToolApproval(c,u,b);if(!E.approved)g=`${E.reason??"Tool was not executed"} -- ${Vf}`}}return{toolCall:{...c,input:u},tool:l,input:u,skipReason:g}}async requestToolApproval(c,l,u){let g=this.config.requestToolApproval;if(!g)return{approved:!1,reason:`Tool "${c.toolName}" requires approval but no approval callback is configured`};try{return await g({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:c.toolCallId,toolName:c.toolName,input:l,policy:u})}catch(_){return{approved:!1,reason:`Tool "${c.toolName}" approval request failed: ${_ instanceof Error?_.message:String(_)}`}}}async executePreparedTool(c){let l=this.pendingHookContexts,u=new Date;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:c.toolCall});let g;if(c.skipReason)g={output:{error:c.skipReason},isError:!0};else if(!c.tool)g={output:{error:`Unknown tool: ${c.toolCall.toolName}`},isError:!0};else try{g={output:await c.tool.execute(c.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??Ke("run"),iteration:this.state.iteration,toolCallId:c.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(E)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:c.toolCall,update:E})}})}}catch(b){g={output:{error:b instanceof Error?b.message:String(b)},isError:!0}}let _=new Date,y=Math.max(0,_.getTime()-u.getTime());if(c.tool)for(let b of this.hooks.afterTool){let E=await b({snapshot:this.snapshot(),tool:c.tool,toolCall:c.toolCall,input:c.input,result:g,startedAt:u,endedAt:_,durationMs:y});if(E?.appendContext?.trim())l.push(en({source:"PostToolUse",toolCall:c.toolCall},E.appendContext));if(this.applyStopControl(E),E?.result)g=E.result}if(!c.skipReason&&!g.isError&&c.tool?.successContext?.trim())l.push(en({source:"ToolSuccess",toolCall:c.toolCall},c.tool.successContext));let T=_t("tool",[{type:"tool-result",toolCallId:c.toolCall.toolCallId,toolName:c.toolCall.toolName,output:g.output,isError:g.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:c.toolCall,message:T}),T}finishRun(c,l,u){return this.state.status=c,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??Ke("run"),status:c,iterations:this.state.iteration,outputText:u??Ja(l??this.findLastAssistantMessage()),messages:xe(this.state.messages),usage:tt(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((c)=>c.role==="assistant")}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let c=this.abortController?.signal.reason;if(c instanceof Error)return c;if(typeof c==="string")return Error(c);return Error(this.state.lastError??"Run aborted")}async emit(c){let l=$f(c);switch(c.type){case"run-started":this.config.logger?.info?.("Agent run started",l);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",l);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...l,error:c.error}),!this.state.lastErrorReported)hl(this.config.telemetry,{component:"agents",operation:"agent.run",error:c.error,severity:"error",handled:!1,context:{...l,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),modelRequestId:this.modelRequestId,...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:this.config.logger?.debug?.("Agent event",l);break}switch(c.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-call-delta":case"tool-updated":break;case"run-finished":case"run-failed":this.config.telemetry?.capture({event:`agent.${c.type}`,properties:{...l,...this.config.runEndTelemetryProperties?.()}});break;default:this.config.telemetry?.capture({event:`agent.${c.type}`,properties:l});break}for(let u of this.listeners)u(c);for(let u of this.hooks.onEvent)await u(c)}applyStopControl(c){if(!c?.stop)return;if(c.reason)this.state.lastError=c.reason;throw new Oo(c.reason)}}function $f(c){return{agentId:c.snapshot.agentId,agentRole:c.snapshot.agentRole,runId:c.snapshot.runId,status:c.snapshot.status,iteration:c.snapshot.iteration,eventType:c.type}}function Ya(c,l){if(!l||typeof l!=="object"||Array.isArray(l))return l;if(!c||typeof c!=="object"||Array.isArray(c))return l;return{...c,...l}}function Af(c){if(c.inputValue!==void 0)return{input:c.inputValue,invalidInput:tn(JSON.stringify(c.inputValue))};if(!c.inputText.trim())return{input:{},invalidInput:{}};let l=Pf(c.inputText);if(l.ok)return{input:l.value,invalidInput:tn(c.inputText)};return{input:{},invalidInput:tn(c.inputText,l.error),parseError:`Tool call ${c.toolName??c.toolCallId} emitted invalid JSON arguments: ${l.error}`,reason:"invalid_arguments"}}function tn(c,l){if(!c.trim())return{};return l?{rawInputText:c,parseError:l}:{rawInputText:c}}function Pf(c){let l=c.trim();if(!l)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(l)}}catch{}if(!(l.startsWith("{")||l.startsWith("[")))return{ok:!1,error:"Tool call arguments must be encoded as a JSON object or array."};return{ok:!1,error:"Tool call arguments could not be parsed as JSON. Ensure the outer tool payload is valid JSON and escape embedded quotes/newlines inside string fields."}}function Cf(c,l){if(!c)return l;let u=l.trimStart();if(u.startsWith("{")||u.startsWith("["))return l;return c+l}function Cn(c){return new rn(c)}var zv=rn;var Mt="2025-11-25";var Qa=[Mt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],nt="io.modelcontextprotocol/related-task",on="2.0",ce=J((c)=>c!==null&&(typeof c==="object"||typeof c==="function")),ei=p([e(),n().int()]),ti=e(),OE=ae({ttl:n().optional(),pollInterval:n().optional()}),zf=t({ttl:n().optional()}),Of=t({taskId:e()}),Mo=ae({progressToken:ei.optional(),[nt]:Of.optional()}),ke=t({_meta:Mo.optional()}),pr=ke.extend({task:zf.optional()}),ri=(c)=>pr.safeParse(c).success,de=t({method:e(),params:ke.loose().optional()}),$e=t({_meta:Mo.optional()}),Ae=t({method:e(),params:$e.loose().optional()}),pe=ae({_meta:Mo.optional()}),sn=p([e(),n().int()]),ni=t({jsonrpc:a(on),id:sn,...de.shape}).strict(),fr=(c)=>ni.safeParse(c).success,oi=t({jsonrpc:a(on),...Ae.shape}).strict(),si=(c)=>oi.safeParse(c).success,No=t({jsonrpc:a(on),id:sn,result:pe}).strict(),yt=(c)=>No.safeParse(c).success;var Y;(function(c){c[c.ConnectionClosed=-32000]="ConnectionClosed",c[c.RequestTimeout=-32001]="RequestTimeout",c[c.ParseError=-32700]="ParseError",c[c.InvalidRequest=-32600]="InvalidRequest",c[c.MethodNotFound=-32601]="MethodNotFound",c[c.InvalidParams=-32602]="InvalidParams",c[c.InternalError=-32603]="InternalError",c[c.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));var qo=t({jsonrpc:a(on),id:sn.optional(),error:t({code:n().int(),message:e(),data:m().optional()})}).strict();var ai=(c)=>qo.safeParse(c).success;var Nt=p([ni,oi,No,qo]),ME=p([No,qo]),vt=pe.strict(),Mf=$e.extend({requestId:sn.optional(),reason:e().optional()}),an=Ae.extend({method:a("notifications/cancelled"),params:Mf}),Nf=t({src:e(),mimeType:e().optional(),sizes:o(e()).optional(),theme:s(["light","dark"]).optional()}),hr=t({icons:o(Nf).optional()}),Ot=t({name:e(),title:e().optional()}),ii=Ot.extend({...Ot.shape,...hr.shape,version:e(),websiteUrl:e().optional(),description:e().optional()}),qf=la(t({applyDefaults:r().optional()}),d(e(),m())),Df=je((c)=>{if(c&&typeof c==="object"&&!Array.isArray(c)){if(Object.keys(c).length===0)return{form:{}}}return c},la(t({form:qf.optional(),url:ce.optional()}),d(e(),m()).optional())),jf=ae({list:ce.optional(),cancel:ce.optional(),requests:ae({sampling:ae({createMessage:ce.optional()}).optional(),elicitation:ae({create:ce.optional()}).optional()}).optional()}),Lf=ae({list:ce.optional(),cancel:ce.optional(),requests:ae({tools:ae({call:ce.optional()}).optional()}).optional()}),Uf=t({experimental:d(e(),ce).optional(),sampling:t({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:Df.optional(),roots:t({listChanged:r().optional()}).optional(),tasks:jf.optional(),extensions:d(e(),ce).optional()}),Ff=ke.extend({protocolVersion:e(),capabilities:Uf,clientInfo:ii}),Hf=de.extend({method:a("initialize"),params:Ff});var Wf=t({experimental:d(e(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:t({listChanged:r().optional()}).optional(),resources:t({subscribe:r().optional(),listChanged:r().optional()}).optional(),tools:t({listChanged:r().optional()}).optional(),tasks:Lf.optional(),extensions:d(e(),ce).optional()}),Do=pe.extend({protocolVersion:e(),capabilities:Wf,serverInfo:ii,instructions:e().optional()}),ci=Ae.extend({method:a("notifications/initialized"),params:$e.optional()}),li=(c)=>ci.safeParse(c).success,cn=de.extend({method:a("ping"),params:ke.optional()}),Kf=t({progress:n(),total:Le(n()),message:Le(e())}),Bf=t({...$e.shape,...Kf.shape,progressToken:ei}),ln=Ae.extend({method:a("notifications/progress"),params:Bf}),Gf=ke.extend({cursor:ti.optional()}),mr=de.extend({params:Gf.optional()}),gr=pe.extend({nextCursor:ti.optional()}),Zf=s(["working","input_required","completed","failed","cancelled"]),_r=t({taskId:e(),status:Zf,ttl:p([n(),Ht()]),createdAt:e(),lastUpdatedAt:e(),pollInterval:Le(n()),statusMessage:Le(e())}),Tt=pe.extend({task:_r}),Xf=$e.merge(_r),yr=Ae.extend({method:a("notifications/tasks/status"),params:Xf}),dn=de.extend({method:a("tasks/get"),params:ke.extend({taskId:e()})}),pn=pe.merge(_r),fn=de.extend({method:a("tasks/result"),params:ke.extend({taskId:e()})}),NE=pe.loose(),hn=mr.extend({method:a("tasks/list")}),mn=gr.extend({tasks:o(_r)}),gn=de.extend({method:a("tasks/cancel"),params:ke.extend({taskId:e()})}),ui=pe.merge(_r),di=t({uri:e(),mimeType:Le(e()),_meta:d(e(),m()).optional()}),pi=di.extend({text:e()}),jo=e().refine((c)=>{try{return atob(c),!0}catch{return!1}},{message:"Invalid Base64 string"}),hi=di.extend({blob:jo}),wr=s(["user","assistant"]),qt=t({audience:o(wr).optional(),priority:n().min(0).max(1).optional(),lastModified:Vw({offset:!0}).optional()}),mi=t({...Ot.shape,...hr.shape,uri:e(),description:Le(e()),mimeType:Le(e()),size:Le(n()),annotations:qt.optional(),_meta:Le(ae({}))}),Jf=t({...Ot.shape,...hr.shape,uriTemplate:e(),description:Le(e()),mimeType:Le(e()),annotations:qt.optional(),_meta:Le(ae({}))}),Yf=mr.extend({method:a("resources/list")}),Lo=gr.extend({resources:o(mi)}),Qf=mr.extend({method:a("resources/templates/list")}),Uo=gr.extend({resourceTemplates:o(Jf)}),Fo=ke.extend({uri:e()}),eh=Fo,th=de.extend({method:a("resources/read"),params:eh}),ga=pe.extend({contents:o(p([pi,hi]))}),Vo=Ae.extend({method:a("notifications/resources/list_changed"),params:$e.optional()}),rh=Fo,nh=de.extend({method:a("resources/subscribe"),params:rh}),oh=Fo,sh=de.extend({method:a("resources/unsubscribe"),params:oh}),ah=$e.extend({uri:e()}),ih=Ae.extend({method:a("notifications/resources/updated"),params:ah}),ch=t({name:e(),description:Le(e()),required:Le(r())}),lh=t({...Ot.shape,...hr.shape,description:Le(e()),arguments:Le(o(ch)),_meta:Le(ae({}))}),uh=mr.extend({method:a("prompts/list")}),Wo=gr.extend({prompts:o(lh)}),dh=ke.extend({name:e(),arguments:d(e(),e()).optional()}),ph=de.extend({method:a("prompts/get"),params:dh}),Bo=t({type:a("text"),text:e(),annotations:qt.optional(),_meta:d(e(),m()).optional()}),Go=t({type:a("image"),data:jo,mimeType:e(),annotations:qt.optional(),_meta:d(e(),m()).optional()}),Zo=t({type:a("audio"),data:jo,mimeType:e(),annotations:qt.optional(),_meta:d(e(),m()).optional()}),fh=t({type:a("tool_use"),name:e(),id:e(),input:d(e(),m()),_meta:d(e(),m()).optional()}),hh=t({type:a("resource"),resource:p([pi,hi]),annotations:qt.optional(),_meta:d(e(),m()).optional()}),mh=mi.extend({type:a("resource_link")}),Xo=p([Bo,Go,Zo,mh,hh]),gh=t({role:wr,content:Xo}),Jo=pe.extend({description:e().optional(),messages:o(gh)}),Yo=Ae.extend({method:a("notifications/prompts/list_changed"),params:$e.optional()}),_h=t({title:e().optional(),readOnlyHint:r().optional(),destructiveHint:r().optional(),idempotentHint:r().optional(),openWorldHint:r().optional()}),yh=t({taskSupport:s(["required","optional","forbidden"]).optional()}),gi=t({...Ot.shape,...hr.shape,description:e().optional(),inputSchema:t({type:a("object"),properties:d(e(),ce).optional(),required:o(e()).optional()}).catchall(m()),outputSchema:t({type:a("object"),properties:d(e(),ce).optional(),required:o(e()).optional()}).catchall(m()).optional(),annotations:_h.optional(),execution:yh.optional(),_meta:d(e(),m()).optional()}),wh=mr.extend({method:a("tools/list")}),es=gr.extend({tools:o(gi)}),Dt=pe.extend({content:o(Xo).default([]),structuredContent:d(e(),m()).optional(),isError:r().optional()}),qE=Dt.or(pe.extend({toolResult:m()})),vh=pr.extend({name:e(),arguments:d(e(),m()).optional()}),Th=de.extend({method:a("tools/call"),params:vh}),ts=Ae.extend({method:a("notifications/tools/list_changed"),params:$e.optional()}),_i=t({autoRefresh:r().default(!0),debounceMs:n().int().nonnegative().default(300)}),yi=s(["debug","info","notice","warning","error","critical","alert","emergency"]),bh=ke.extend({level:yi}),Rh=de.extend({method:a("logging/setLevel"),params:bh}),Eh=$e.extend({level:yi,logger:e().optional(),data:m()}),Sh=Ae.extend({method:a("notifications/message"),params:Eh}),xh=t({name:e().optional()}),kh=t({hints:o(xh).optional(),costPriority:n().min(0).max(1).optional(),speedPriority:n().min(0).max(1).optional(),intelligencePriority:n().min(0).max(1).optional()}),$h=t({mode:s(["auto","required","none"]).optional()}),Ah=t({type:a("tool_result"),toolUseId:e().describe("The unique identifier for the corresponding tool call."),content:o(Xo).default([]),structuredContent:t({}).loose().optional(),isError:r().optional(),_meta:d(e(),m()).optional()}),Ph=w("type",[Bo,Go,Zo]),nn=w("type",[Bo,Go,Zo,fh,Ah]),Ch=t({role:wr,content:p([nn,o(nn)]),_meta:d(e(),m()).optional()}),Ih=pr.extend({messages:o(Ch),modelPreferences:kh.optional(),systemPrompt:e().optional(),includeContext:s(["none","thisServer","allServers"]).optional(),temperature:n().optional(),maxTokens:n().int(),stopSequences:o(e()).optional(),metadata:ce.optional(),tools:o(gi).optional(),toolChoice:$h.optional()}),rs=de.extend({method:a("sampling/createMessage"),params:Ih}),ns=pe.extend({model:e(),stopReason:Le(s(["endTurn","stopSequence","maxTokens"]).or(e())),role:wr,content:Ph}),os=pe.extend({model:e(),stopReason:Le(s(["endTurn","stopSequence","maxTokens","toolUse"]).or(e())),role:wr,content:p([nn,o(nn)])}),zh=t({type:a("boolean"),title:e().optional(),description:e().optional(),default:r().optional()}),Oh=t({type:a("string"),title:e().optional(),description:e().optional(),minLength:n().optional(),maxLength:n().optional(),format:s(["email","uri","date","date-time"]).optional(),default:e().optional()}),Mh=t({type:s(["number","integer"]),title:e().optional(),description:e().optional(),minimum:n().optional(),maximum:n().optional(),default:n().optional()}),Nh=t({type:a("string"),title:e().optional(),description:e().optional(),enum:o(e()),default:e().optional()}),qh=t({type:a("string"),title:e().optional(),description:e().optional(),oneOf:o(t({const:e(),title:e()})),default:e().optional()}),Dh=t({type:a("string"),title:e().optional(),description:e().optional(),enum:o(e()),enumNames:o(e()).optional(),default:e().optional()}),jh=p([Nh,qh]),Lh=t({type:a("array"),title:e().optional(),description:e().optional(),minItems:n().optional(),maxItems:n().optional(),items:t({type:a("string"),enum:o(e())}),default:o(e()).optional()}),Uh=t({type:a("array"),title:e().optional(),description:e().optional(),minItems:n().optional(),maxItems:n().optional(),items:t({anyOf:o(t({const:e(),title:e()}))}),default:o(e()).optional()}),Fh=p([Lh,Uh]),Hh=p([Dh,jh,Fh]),Vh=p([Hh,zh,Oh,Mh]),Wh=pr.extend({mode:a("form").optional(),message:e(),requestedSchema:t({type:a("object"),properties:d(e(),Vh),required:o(e()).optional()})}),Kh=pr.extend({mode:a("url"),message:e(),elicitationId:e(),url:e().url()}),Bh=p([Wh,Kh]),ss=de.extend({method:a("elicitation/create"),params:Bh}),Gh=$e.extend({elicitationId:e()}),Zh=Ae.extend({method:a("notifications/elicitation/complete"),params:Gh}),as=pe.extend({action:s(["accept","decline","cancel"]),content:je((c)=>c===null?void 0:c,d(e(),p([e(),n(),r(),o(e())])).optional())}),Xh=t({type:a("ref/resource"),uri:e()});var Jh=t({type:a("ref/prompt"),name:e()}),Yh=ke.extend({ref:p([Jh,Xh]),argument:t({name:e(),value:e()}),context:t({arguments:d(e(),e()).optional()}).optional()}),Qh=de.extend({method:a("completion/complete"),params:Yh});var is=pe.extend({completion:ae({values:o(e()).max(100),total:Le(n().int()),hasMore:Le(r())})}),em=t({uri:e().startsWith("file://"),name:e().optional(),_meta:d(e(),m()).optional()}),tm=de.extend({method:a("roots/list"),params:ke.optional()}),rm=pe.extend({roots:o(em)}),nm=Ae.extend({method:a("notifications/roots/list_changed"),params:$e.optional()}),DE=p([cn,Hf,Qh,Rh,ph,uh,Yf,Qf,th,nh,sh,Th,wh,dn,fn,hn,gn]),jE=p([an,ln,ci,nm,yr]),LE=p([vt,ns,os,as,rm,pn,mn,Tt]),UE=p([cn,rs,ss,tm,dn,fn,hn,gn]),FE=p([an,ln,Sh,ih,Vo,ts,Yo,yr,Zh]),HE=p([vt,Do,is,Jo,Wo,Lo,Uo,ga,Dt,es,pn,mn,Tt]);class q extends Error{constructor(c,l,u){super(`MCP error ${c}: ${l}`);this.code=c,this.data=u,this.name="McpError"}static fromError(c,l,u){if(c===Y.UrlElicitationRequired&&u){let g=u;if(g.elicitations)return new wi(g.elicitations,l)}return new q(c,l,u)}}class wi extends q{constructor(c,l=`URL elicitation${c.length>1?"s":""} required`){super(Y.UrlElicitationRequired,l,{elicitations:c})}get elicitations(){return this.data?.elicitations??[]}}function _n(c){return!!c._zod}function ze(c,l){if(_n(c))return Al(c,l);return c.safeParse(l)}function yn(c){if(!c)return;let l;if(_n(c))l=c._zod?.def?.shape;else l=c.shape;if(!l)return;if(typeof l==="function")try{return l()}catch{return}return l}function wn(c){if(_n(c)){let y=c._zod?.def;if(y){if(y.value!==void 0)return y.value;if(Array.isArray(y.values)&&y.values.length>0)return y.values[0]}}let u=c._def;if(u){if(u.value!==void 0)return u.value;if(Array.isArray(u.values)&&u.values.length>0)return u.values[0]}let g=c.value;if(g!==void 0)return g;return}function st(c){return c==="completed"||c==="failed"||c==="cancelled"}var om=Symbol("Let zodToJsonSchema decide on which parser to use");var xS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function cs(c){let u=yn(c)?.method;if(!u)throw Error("Schema is missing a method literal");let g=wn(u);if(typeof g!=="string")throw Error("Schema method literal must be a string");return g}function ls(c,l){let u=ze(c,l);if(!u.success)throw u.error;return u.data}var um=60000;class us{constructor(c){if(this._options=c,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(an,(l)=>{this._oncancel(l)}),this.setNotificationHandler(ln,(l)=>{this._onprogress(l)}),this.setRequestHandler(cn,(l)=>({})),this._taskStore=c?.taskStore,this._taskMessageQueue=c?.taskMessageQueue,this._taskStore)this.setRequestHandler(dn,async(l,u)=>{let g=await this._taskStore.getTask(l.params.taskId,u.sessionId);if(!g)throw new q(Y.InvalidParams,"Failed to retrieve task: Task not found");return{...g}}),this.setRequestHandler(fn,async(l,u)=>{let g=async()=>{let _=l.params.taskId;if(!await this._taskStore.getTask(_,u.sessionId))throw new q(Y.InvalidParams,`Task not found: ${_}`);if(this._taskMessageQueue){let T;while(T=await this._taskMessageQueue.dequeue(_,u.sessionId)){if(T.type==="response"||T.type==="error"){let b=T.message,E=b.id,S=this._requestResolvers.get(E);if(S)if(this._requestResolvers.delete(E),T.type==="response")S(b);else{let k=b,A=new q(k.error.code,k.error.message,k.error.data);S(A)}else{let k=T.type==="response"?"Response":"Error";this._onerror(Error(`${k} handler missing for request ${E}`))}continue}await this._transport?.send(T.message,{relatedRequestId:u.requestId})}}let y=await this._taskStore.getTask(_,u.sessionId);if(!y)throw new q(Y.InvalidParams,`Task not found: ${_}`);if(!st(y.status))return await this._waitForTaskUpdate(_,u.signal,u.sessionId),await g();if(st(y.status)){let T=await this._taskStore.getTaskResult(_,u.sessionId);return this._clearTaskQueue(_,u.sessionId),{...T,_meta:{...T._meta,[nt]:{taskId:_}}}}return await g()};return await g()}),this.setRequestHandler(hn,async(l,u)=>{try{let{tasks:g,nextCursor:_}=await this._taskStore.listTasks(l.params?.cursor,u.sessionId);return{tasks:g,nextCursor:_,_meta:{}}}catch(g){throw new q(Y.InvalidParams,`Failed to list tasks: ${g instanceof Error?g.message:String(g)}`)}}),this.setRequestHandler(gn,async(l,u)=>{try{let g=await this._taskStore.getTask(l.params.taskId,u.sessionId);if(!g)throw new q(Y.InvalidParams,`Task not found: ${l.params.taskId}`);if(st(g.status))throw new q(Y.InvalidParams,`Cannot cancel task in terminal status: ${g.status}`);await this._taskStore.updateTaskStatus(l.params.taskId,"cancelled","Client cancelled task execution.",u.sessionId),this._clearTaskQueue(l.params.taskId,u.sessionId);let _=await this._taskStore.getTask(l.params.taskId,u.sessionId);if(!_)throw new q(Y.InvalidParams,`Task not found after cancellation: ${l.params.taskId}`);return{_meta:{},..._}}catch(g){if(g instanceof q)throw g;throw new q(Y.InvalidRequest,`Failed to cancel task: ${g instanceof Error?g.message:String(g)}`)}})}async _oncancel(c){if(!c.params.requestId)return;this._requestHandlerAbortControllers.get(c.params.requestId)?.abort(c.params.reason)}_setupTimeout(c,l,u,g,_=!1){this._timeoutInfo.set(c,{timeoutId:setTimeout(g,l),startTime:Date.now(),timeout:l,maxTotalTimeout:u,resetTimeoutOnProgress:_,onTimeout:g})}_resetTimeout(c){let l=this._timeoutInfo.get(c);if(!l)return!1;let u=Date.now()-l.startTime;if(l.maxTotalTimeout&&u>=l.maxTotalTimeout)throw this._timeoutInfo.delete(c),q.fromError(Y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:l.maxTotalTimeout,totalElapsed:u});return clearTimeout(l.timeoutId),l.timeoutId=setTimeout(l.onTimeout,l.timeout),!0}_cleanupTimeout(c){let l=this._timeoutInfo.get(c);if(l)clearTimeout(l.timeoutId),this._timeoutInfo.delete(c)}async connect(c){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=c;let l=this.transport?.onclose;this._transport.onclose=()=>{l?.(),this._onclose()};let u=this.transport?.onerror;this._transport.onerror=(_)=>{u?.(_),this._onerror(_)};let g=this._transport?.onmessage;this._transport.onmessage=(_,y)=>{if(g?.(_,y),yt(_)||ai(_))this._onresponse(_);else if(fr(_))this._onrequest(_,y);else if(si(_))this._onnotification(_);else this._onerror(Error(`Unknown message type: ${JSON.stringify(_)}`))},await this._transport.start()}_onclose(){let c=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let u of this._timeoutInfo.values())clearTimeout(u.timeoutId);this._timeoutInfo.clear();for(let u of this._requestHandlerAbortControllers.values())u.abort();this._requestHandlerAbortControllers.clear();let l=q.fromError(Y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let u of c.values())u(l)}_onerror(c){this.onerror?.(c)}_onnotification(c){let l=this._notificationHandlers.get(c.method)??this.fallbackNotificationHandler;if(l===void 0)return;Promise.resolve().then(()=>l(c)).catch((u)=>this._onerror(Error(`Uncaught error in notification handler: ${u}`)))}_onrequest(c,l){let u=this._requestHandlers.get(c.method)??this.fallbackRequestHandler,g=this._transport,_=c.params?._meta?.[nt]?.taskId,y=g?.sessionId,T=this._taskStore,b=!0,E;if(_&&T&&this._taskMessageQueue&&y!==void 0)b=!1,E=(async()=>{if(!await T.getTask(_,y))throw new q(Y.InvalidParams,`Task not found: ${_}`);b=!0})();if(u===void 0){let C={jsonrpc:"2.0",id:c.id,error:{code:Y.MethodNotFound,message:"Method not found"}};if(_&&E){let P={type:"error",message:C,timestamp:Date.now()};E.then(()=>this._enqueueTaskMessage(_,P,y),()=>g?.send(C)).catch((I)=>this._onerror(Error(`Failed to send an error response: ${I}`)))}else if(_&&this._taskMessageQueue)this._enqueueTaskMessage(_,{type:"error",message:C,timestamp:Date.now()},g?.sessionId).catch((P)=>this._onerror(Error(`Failed to enqueue error response: ${P}`)));else g?.send(C).catch((P)=>this._onerror(Error(`Failed to send an error response: ${P}`)));return}let S=new AbortController;this._requestHandlerAbortControllers.set(c.id,S);let k=ri(c.params)?c.params.task:void 0,A=this._taskStore?this.requestTaskStore(c,g?.sessionId):void 0,z={signal:S.signal,sessionId:g?.sessionId,_meta:c.params?._meta,sendNotification:async(C)=>{if(S.signal.aborted)return;let P={relatedRequestId:c.id};if(_)P.relatedTask={taskId:_};await this.notification(C,P)},sendRequest:async(C,P,I)=>{if(S.signal.aborted)throw new q(Y.ConnectionClosed,"Request was cancelled");let M={...I,relatedRequestId:c.id};if(_&&!M.relatedTask)M.relatedTask={taskId:_};let N=M.relatedTask?.taskId??_;if(N&&A)await A.updateTaskStatus(N,"input_required");return await this.request(C,P,M)},authInfo:l?.authInfo,requestId:c.id,requestInfo:l?.requestInfo,taskId:_,taskStore:A,taskRequestedTtl:k?.ttl,closeSSEStream:l?.closeSSEStream,closeStandaloneSSEStream:l?.closeStandaloneSSEStream};(E??Promise.resolve()).then(()=>{if(E&&S.signal.aborted)throw new q(Y.ConnectionClosed,"Request was cancelled");if(k)this.assertTaskHandlerCapability(c.method)}).then(()=>u(c,z)).then(async(C)=>{if(S.signal.aborted)return;let P={result:C,jsonrpc:"2.0",id:c.id};if(_&&this._taskMessageQueue)await this._enqueueTaskMessage(_,{type:"response",message:P,timestamp:Date.now()},g?.sessionId);else await g?.send(P)},async(C)=>{if(S.signal.aborted)return;let P={jsonrpc:"2.0",id:c.id,error:{code:Number.isSafeInteger(C.code)?C.code:Y.InternalError,message:C.message??"Internal error",...C.data!==void 0&&{data:C.data}}};if(_&&this._taskMessageQueue&&b)await this._enqueueTaskMessage(_,{type:"error",message:P,timestamp:Date.now()},g?.sessionId);else await g?.send(P)}).catch((C)=>this._onerror(Error(`Failed to send response: ${C}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(c.id)===S)this._requestHandlerAbortControllers.delete(c.id)})}_onprogress(c){let{progressToken:l,...u}=c.params,g=Number(l),_=this._progressHandlers.get(g);if(!_){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(c)}`));return}let y=this._responseHandlers.get(g),T=this._timeoutInfo.get(g);if(T&&y&&T.resetTimeoutOnProgress)try{this._resetTimeout(g)}catch(b){this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),y(b);return}_(u)}_onresponse(c){let l=Number(c.id),u=this._requestResolvers.get(l);if(u){if(this._requestResolvers.delete(l),yt(c))u(c);else{let y=new q(c.error.code,c.error.message,c.error.data);u(y)}return}let g=this._responseHandlers.get(l);if(g===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(c)}`));return}this._responseHandlers.delete(l),this._cleanupTimeout(l);let _=!1;if(yt(c)&&c.result&&typeof c.result==="object"){let y=c.result;if(y.task&&typeof y.task==="object"){let T=y.task;if(typeof T.taskId==="string")_=!0,this._taskProgressTokens.set(T.taskId,l)}}if(!_)this._progressHandlers.delete(l);if(yt(c))g(c);else{let y=q.fromError(c.error.code,c.error.message,c.error.data);g(y)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(c,l,u){let{task:g}=u??{};if(!g){try{yield{type:"result",result:await this.request(c,l,u)}}catch(y){yield{type:"error",error:y instanceof q?y:new q(Y.InternalError,String(y))}}return}let _;try{let y=await this.request(c,Tt,u);if(y.task)_=y.task.taskId,yield{type:"taskCreated",task:y.task};else throw new q(Y.InternalError,"Task creation did not return a task");while(!0){let T=await this.getTask({taskId:_},u);if(yield{type:"taskStatus",task:T},st(T.status)){if(T.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:_},l,u)};else if(T.status==="failed")yield{type:"error",error:new q(Y.InternalError,`Task ${_} failed`)};else if(T.status==="cancelled")yield{type:"error",error:new q(Y.InternalError,`Task ${_} was cancelled`)};return}if(T.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:_},l,u)};return}let b=T.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((E)=>setTimeout(E,b)),u?.signal?.throwIfAborted()}}catch(y){yield{type:"error",error:y instanceof q?y:new q(Y.InternalError,String(y))}}}request(c,l,u){let{relatedRequestId:g,resumptionToken:_,onresumptiontoken:y,task:T,relatedTask:b}=u??{};return new Promise((E,S)=>{let k=(N)=>{S(N)};if(!this._transport){k(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(c.method),T)this.assertTaskCapability(c.method)}catch(N){k(N);return}u?.signal?.throwIfAborted();let A=this._requestMessageId++,z={...c,jsonrpc:"2.0",id:A};if(u?.onprogress)this._progressHandlers.set(A,u.onprogress),z.params={...c.params,_meta:{...c.params?._meta||{},progressToken:A}};if(T)z.params={...z.params,task:T};if(b)z.params={...z.params,_meta:{...z.params?._meta||{},[nt]:b}};let C=(N)=>{this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(N)}},{relatedRequestId:g,resumptionToken:_,onresumptiontoken:y}).catch((U)=>this._onerror(Error(`Failed to send cancellation: ${U}`)));let D=N instanceof q?N:new q(Y.RequestTimeout,String(N));S(D)};this._responseHandlers.set(A,(N)=>{if(u?.signal?.aborted)return;if(N instanceof Error)return S(N);try{let D=ze(l,N.result);if(!D.success)S(D.error);else E(D.data)}catch(D){S(D)}}),u?.signal?.addEventListener("abort",()=>{C(u?.signal?.reason)});let P=u?.timeout??um,I=()=>C(q.fromError(Y.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(A,P,u?.maxTotalTimeout,I,u?.resetTimeoutOnProgress??!1);let M=b?.taskId;if(M){let N=(D)=>{let U=this._responseHandlers.get(A);if(U)U(D);else this._onerror(Error(`Response handler missing for side-channeled request ${A}`))};this._requestResolvers.set(A,N),this._enqueueTaskMessage(M,{type:"request",message:z,timestamp:Date.now()}).catch((D)=>{this._cleanupTimeout(A),S(D)})}else this._transport.send(z,{relatedRequestId:g,resumptionToken:_,onresumptiontoken:y}).catch((N)=>{this._cleanupTimeout(A),S(N)})})}async getTask(c,l){return this.request({method:"tasks/get",params:c},pn,l)}async getTaskResult(c,l,u){return this.request({method:"tasks/result",params:c},l,u)}async listTasks(c,l){return this.request({method:"tasks/list",params:c},mn,l)}async cancelTask(c,l){return this.request({method:"tasks/cancel",params:c},ui,l)}async notification(c,l){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(c.method);let u=l?.relatedTask?.taskId;if(u){let T={...c,jsonrpc:"2.0",params:{...c.params,_meta:{...c.params?._meta||{},[nt]:l.relatedTask}}};await this._enqueueTaskMessage(u,{type:"notification",message:T,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(c.method)&&!c.params&&!l?.relatedRequestId&&!l?.relatedTask){if(this._pendingDebouncedNotifications.has(c.method))return;this._pendingDebouncedNotifications.add(c.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(c.method),!this._transport)return;let T={...c,jsonrpc:"2.0"};if(l?.relatedTask)T={...T,params:{...T.params,_meta:{...T.params?._meta||{},[nt]:l.relatedTask}}};this._transport?.send(T,l).catch((b)=>this._onerror(b))});return}let y={...c,jsonrpc:"2.0"};if(l?.relatedTask)y={...y,params:{...y.params,_meta:{...y.params?._meta||{},[nt]:l.relatedTask}}};await this._transport.send(y,l)}setRequestHandler(c,l){let u=cs(c);this.assertRequestHandlerCapability(u),this._requestHandlers.set(u,(g,_)=>{let y=ls(c,g);return Promise.resolve(l(y,_))})}removeRequestHandler(c){this._requestHandlers.delete(c)}assertCanSetRequestHandler(c){if(this._requestHandlers.has(c))throw Error(`A request handler for ${c} already exists, which would be overridden`)}setNotificationHandler(c,l){let u=cs(c);this._notificationHandlers.set(u,(g)=>{let _=ls(c,g);return Promise.resolve(l(_))})}removeNotificationHandler(c){this._notificationHandlers.delete(c)}_cleanupTaskProgressHandler(c){let l=this._taskProgressTokens.get(c);if(l!==void 0)this._progressHandlers.delete(l),this._taskProgressTokens.delete(c)}async _enqueueTaskMessage(c,l,u){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let g=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(c,l,u??this._transport?.sessionId,g)}async _clearTaskQueue(c,l){if(this._taskMessageQueue){let u=await this._taskMessageQueue.dequeueAll(c,l);for(let g of u)if(g.type==="request"&&fr(g.message)){let _=g.message.id,y=this._requestResolvers.get(_);if(y)y(new q(Y.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(_);else this._onerror(Error(`Resolver missing for request ${_} during task ${c} cleanup`))}}}async _waitForTaskUpdate(c,l,u){let g=this._options?.defaultTaskPollInterval??1000;try{let _=await this._taskStore?.getTask(c,u);if(_?.pollInterval)g=_.pollInterval}catch{}return new Promise((_,y)=>{if(l.aborted){y(new q(Y.InvalidRequest,"Request cancelled"));return}let T=setTimeout(_,g);l.addEventListener("abort",()=>{clearTimeout(T),y(new q(Y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(c,l){let u=this._taskStore;if(!u)throw Error("No task store configured");return{createTask:async(g)=>{if(!c)throw Error("No request provided");return await u.createTask(g,c.id,{method:c.method,params:c.params},l)},getTask:async(g)=>{let _=await u.getTask(g,l);if(!_)throw new q(Y.InvalidParams,"Failed to retrieve task: Task not found");return _},storeTaskResult:async(g,_,y)=>{await u.storeTaskResult(g,_,y,l);let T=await u.getTask(g,l);if(T){let b=yr.parse({method:"notifications/tasks/status",params:T});if(await this.notification(b),st(T.status))this._cleanupTaskProgressHandler(g)}},getTaskResult:(g)=>u.getTaskResult(g,l),updateTaskStatus:async(g,_,y)=>{let T=await u.getTask(g,l);if(!T)throw new q(Y.InvalidParams,`Task "${g}" not found - it may have been cleaned up`);if(st(T.status))throw new q(Y.InvalidParams,`Cannot update task "${g}" from terminal status "${T.status}" to "${_}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await u.updateTaskStatus(g,_,y,l);let b=await u.getTask(g,l);if(b){let E=yr.parse({method:"notifications/tasks/status",params:b});if(await this.notification(E),st(b.status))this._cleanupTaskProgressHandler(g)}},listTasks:(g)=>u.listTasks(g,l)}}}function vi(c){return c!==null&&typeof c==="object"&&!Array.isArray(c)}function Ti(c,l){let u={...c};for(let g in l){let _=g,y=l[_];if(y===void 0)continue;let T=u[_];if(vi(T)&&vi(y))u[_]={...T,...y};else u[_]=y}return u}var $p=v(ha(),1),Ap=v(kp(),1);function wR(){let c=new $p.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Ap.default(c),c}class Sa{constructor(c){this._ajv=c??wR()}getValidator(c){let l="$id"in c&&typeof c.$id==="string"?this._ajv.getSchema(c.$id)??this._ajv.compile(c):this._ajv.compile(c);return(u)=>{if(l(u))return{valid:!0,data:u,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(l.errors)}}}}class xa{constructor(c){this._client=c}async*callToolStream(c,l=Dt,u){let g=this._client,_={...u,task:u?.task??(g.isToolTask(c.name)?{}:void 0)},y=g.requestStream({method:"tools/call",params:c},l,_),T=g.getToolOutputValidator(c.name);for await(let b of y){if(b.type==="result"&&T){let E=b.result;if(!E.structuredContent&&!E.isError){yield{type:"error",error:new q(Y.InvalidRequest,`Tool ${c.name} has an output schema but did not return structured content`)};return}if(E.structuredContent)try{let S=T(E.structuredContent);if(!S.valid){yield{type:"error",error:new q(Y.InvalidParams,`Structured content does not match the tool's output schema: ${S.errorMessage}`)};return}}catch(S){if(S instanceof q){yield{type:"error",error:S};return}yield{type:"error",error:new q(Y.InvalidParams,`Failed to validate structured content: ${S instanceof Error?S.message:String(S)}`)};return}}yield b}}async getTask(c,l){return this._client.getTask({taskId:c},l)}async getTaskResult(c,l,u){return this._client.getTaskResult({taskId:c},l,u)}async listTasks(c,l){return this._client.listTasks(c?{cursor:c}:void 0,l)}async cancelTask(c,l){return this._client.cancelTask({taskId:c},l)}requestStream(c,l,u){return this._client.requestStream(c,l,u)}}function Pp(c,l,u){if(!c)throw Error(`${u} does not support task creation (required for ${l})`);switch(l){case"tools/call":if(!c.tools?.call)throw Error(`${u} does not support task creation for tools/call (required for ${l})`);break;default:break}}function Cp(c,l,u){if(!c)throw Error(`${u} does not support task creation (required for ${l})`);switch(l){case"sampling/createMessage":if(!c.sampling?.createMessage)throw Error(`${u} does not support task creation for sampling/createMessage (required for ${l})`);break;case"elicitation/create":if(!c.elicitation?.create)throw Error(`${u} does not support task creation for elicitation/create (required for ${l})`);break;default:break}}function uo(c,l){if(!c||l===null||typeof l!=="object")return;if(c.type==="object"&&c.properties&&typeof c.properties==="object"){let u=l,g=c.properties;for(let _ of Object.keys(g)){let y=g[_];if(u[_]===void 0&&Object.prototype.hasOwnProperty.call(y,"default"))u[_]=y.default;if(u[_]!==void 0)uo(y,u[_])}}if(Array.isArray(c.anyOf)){for(let u of c.anyOf)if(typeof u!=="boolean")uo(u,l)}if(Array.isArray(c.oneOf)){for(let u of c.oneOf)if(typeof u!=="boolean")uo(u,l)}}function vR(c){if(!c)return{supportsFormMode:!1,supportsUrlMode:!1};let l=c.form!==void 0,u=c.url!==void 0;return{supportsFormMode:l||!l&&!u,supportsUrlMode:u}}class un extends us{constructor(c,l){super(l);if(this._clientInfo=c,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=l?.capabilities??{},this._jsonSchemaValidator=l?.jsonSchemaValidator??new Sa,l?.listChanged)this._pendingListChangedConfig=l.listChanged}_setupListChangedHandlers(c){if(c.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",ts,c.tools,async()=>(await this.listTools()).tools);if(c.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",Yo,c.prompts,async()=>(await this.listPrompts()).prompts);if(c.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",Vo,c.resources,async()=>(await this.listResources()).resources)}get experimental(){if(!this._experimental)this._experimental={tasks:new xa(this)};return this._experimental}registerCapabilities(c){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Ti(this._capabilities,c)}setRequestHandler(c,l){let g=yn(c)?.method;if(!g)throw Error("Schema is missing a method literal");let _=wn(g);if(typeof _!=="string")throw Error("Schema method literal must be a string");let y=_;if(y==="elicitation/create"){let T=async(b,E)=>{let S=ze(ss,b);if(!S.success){let N=S.error instanceof Error?S.error.message:String(S.error);throw new q(Y.InvalidParams,`Invalid elicitation request: ${N}`)}let{params:k}=S.data;k.mode=k.mode??"form";let{supportsFormMode:A,supportsUrlMode:z}=vR(this._capabilities.elicitation);if(k.mode==="form"&&!A)throw new q(Y.InvalidParams,"Client does not support form-mode elicitation requests");if(k.mode==="url"&&!z)throw new q(Y.InvalidParams,"Client does not support URL-mode elicitation requests");let C=await Promise.resolve(l(b,E));if(k.task){let N=ze(Tt,C);if(!N.success){let D=N.error instanceof Error?N.error.message:String(N.error);throw new q(Y.InvalidParams,`Invalid task creation result: ${D}`)}return N.data}let P=ze(as,C);if(!P.success){let N=P.error instanceof Error?P.error.message:String(P.error);throw new q(Y.InvalidParams,`Invalid elicitation result: ${N}`)}let I=P.data,M=k.mode==="form"?k.requestedSchema:void 0;if(k.mode==="form"&&I.action==="accept"&&I.content&&M){if(this._capabilities.elicitation?.form?.applyDefaults)try{uo(M,I.content)}catch{}}return I};return super.setRequestHandler(c,T)}if(y==="sampling/createMessage"){let T=async(b,E)=>{let S=ze(rs,b);if(!S.success){let I=S.error instanceof Error?S.error.message:String(S.error);throw new q(Y.InvalidParams,`Invalid sampling request: ${I}`)}let{params:k}=S.data,A=await Promise.resolve(l(b,E));if(k.task){let I=ze(Tt,A);if(!I.success){let M=I.error instanceof Error?I.error.message:String(I.error);throw new q(Y.InvalidParams,`Invalid task creation result: ${M}`)}return I.data}let C=k.tools||k.toolChoice?os:ns,P=ze(C,A);if(!P.success){let I=P.error instanceof Error?P.error.message:String(P.error);throw new q(Y.InvalidParams,`Invalid sampling result: ${I}`)}return P.data};return super.setRequestHandler(c,T)}return super.setRequestHandler(c,l)}assertCapability(c,l){if(!this._serverCapabilities?.[c])throw Error(`Server does not support ${c} (required for ${l})`)}async connect(c,l){if(await super.connect(c),c.sessionId!==void 0)return;try{let u=await this.request({method:"initialize",params:{protocolVersion:Mt,capabilities:this._capabilities,clientInfo:this._clientInfo}},Do,l);if(u===void 0)throw Error(`Server sent invalid initialize result: ${u}`);if(!Qa.includes(u.protocolVersion))throw Error(`Server's protocol version is not supported: ${u.protocolVersion}`);if(this._serverCapabilities=u.capabilities,this._serverVersion=u.serverInfo,c.setProtocolVersion)c.setProtocolVersion(u.protocolVersion);if(this._instructions=u.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(u){throw this.close(),u}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(c){switch(c){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${c})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${c})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${c})`);if(c==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${c})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${c})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${c})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(c){switch(c){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${c})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(c){if(!this._capabilities)return;switch(c){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${c})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${c})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${c})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${c})`);break;case"ping":break}}assertTaskCapability(c){Pp(this._serverCapabilities?.tasks?.requests,c,"Server")}assertTaskHandlerCapability(c){if(!this._capabilities)return;Cp(this._capabilities.tasks?.requests,c,"Client")}async ping(c){return this.request({method:"ping"},vt,c)}async complete(c,l){return this.request({method:"completion/complete",params:c},is,l)}async setLoggingLevel(c,l){return this.request({method:"logging/setLevel",params:{level:c}},vt,l)}async getPrompt(c,l){return this.request({method:"prompts/get",params:c},Jo,l)}async listPrompts(c,l){return this.request({method:"prompts/list",params:c},Wo,l)}async listResources(c,l){return this.request({method:"resources/list",params:c},Lo,l)}async listResourceTemplates(c,l){return this.request({method:"resources/templates/list",params:c},Uo,l)}async readResource(c,l){return this.request({method:"resources/read",params:c},ga,l)}async subscribeResource(c,l){return this.request({method:"resources/subscribe",params:c},vt,l)}async unsubscribeResource(c,l){return this.request({method:"resources/unsubscribe",params:c},vt,l)}async callTool(c,l=Dt,u){if(this.isToolTaskRequired(c.name))throw new q(Y.InvalidRequest,`Tool "${c.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let g=await this.request({method:"tools/call",params:c},l,u),_=this.getToolOutputValidator(c.name);if(_){if(!g.structuredContent&&!g.isError)throw new q(Y.InvalidRequest,`Tool ${c.name} has an output schema but did not return structured content`);if(g.structuredContent)try{let y=_(g.structuredContent);if(!y.valid)throw new q(Y.InvalidParams,`Structured content does not match the tool's output schema: ${y.errorMessage}`)}catch(y){if(y instanceof q)throw y;throw new q(Y.InvalidParams,`Failed to validate structured content: ${y instanceof Error?y.message:String(y)}`)}}return g}isToolTask(c){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(c)}isToolTaskRequired(c){return this._cachedRequiredTaskTools.has(c)}cacheToolMetadata(c){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let l of c){if(l.outputSchema){let g=this._jsonSchemaValidator.getValidator(l.outputSchema);this._cachedToolOutputValidators.set(l.name,g)}let u=l.execution?.taskSupport;if(u==="required"||u==="optional")this._cachedKnownTaskTools.add(l.name);if(u==="required")this._cachedRequiredTaskTools.add(l.name)}}getToolOutputValidator(c){return this._cachedToolOutputValidators.get(c)}async listTools(c,l){let u=await this.request({method:"tools/list",params:c},es,l);return this.cacheToolMetadata(u.tools),u}_setupListChangedHandler(c,l,u,g){let _=_i.safeParse(u);if(!_.success)throw Error(`Invalid ${c} listChanged options: ${_.error.message}`);if(typeof u.onChanged!=="function")throw Error(`Invalid ${c} listChanged options: onChanged must be a function`);let{autoRefresh:y,debounceMs:T}=_.data,{onChanged:b}=u,E=async()=>{if(!y){b(null,null);return}try{let k=await g();b(null,k)}catch(k){let A=k instanceof Error?k:Error(String(k));b(A,null)}},S=()=>{if(T){let k=this._listChangedDebounceTimers.get(c);if(k)clearTimeout(k);let A=setTimeout(E,T);this._listChangedDebounceTimers.set(c,A)}else E()};this.setNotificationHandler(l,S)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var ka;ka=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((c)=>c.webcrypto);async function TR(c){return(await ka).getRandomValues(new Uint8Array(c))}async function bR(c){let u=Math.pow(2,8)-Math.pow(2,8)%66,g="";while(g.length<c){let _=await TR(c-g.length);for(let y of _)if(y<u)g+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[y%66]}return g}async function RR(c){return await bR(c)}async function ER(c){let l=await(await ka).subtle.digest("SHA-256",new TextEncoder().encode(c));return btoa(String.fromCharCode(...new Uint8Array(l))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function $a(c){if(!c)c=43;if(c<43||c>128)throw`Expected a length between 43 and 128. Received ${c}.`;let l=await RR(c),u=await ER(l);return{code_verifier:l,code_challenge:u}}var me=zp().superRefine((c,l)=>{if(!URL.canParse(c))return l.addIssue({code:oa.custom,message:"URL must be parseable",fatal:!0}),Sl}).refine((c)=>{let l=new URL(c);return l.protocol!=="javascript:"&&l.protocol!=="data:"&&l.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Op=ae({resource:e().url(),authorization_servers:o(me).optional(),jwks_uri:e().url().optional(),scopes_supported:o(e()).optional(),bearer_methods_supported:o(e()).optional(),resource_signing_alg_values_supported:o(e()).optional(),resource_name:e().optional(),resource_documentation:e().optional(),resource_policy_uri:e().url().optional(),resource_tos_uri:e().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(e()).optional(),dpop_signing_alg_values_supported:o(e()).optional(),dpop_bound_access_tokens_required:r().optional()}),Aa=ae({issuer:e(),authorization_endpoint:me,token_endpoint:me,registration_endpoint:me.optional(),scopes_supported:o(e()).optional(),response_types_supported:o(e()),response_modes_supported:o(e()).optional(),grant_types_supported:o(e()).optional(),token_endpoint_auth_methods_supported:o(e()).optional(),token_endpoint_auth_signing_alg_values_supported:o(e()).optional(),service_documentation:me.optional(),revocation_endpoint:me.optional(),revocation_endpoint_auth_methods_supported:o(e()).optional(),revocation_endpoint_auth_signing_alg_values_supported:o(e()).optional(),introspection_endpoint:e().optional(),introspection_endpoint_auth_methods_supported:o(e()).optional(),introspection_endpoint_auth_signing_alg_values_supported:o(e()).optional(),code_challenge_methods_supported:o(e()).optional(),client_id_metadata_document_supported:r().optional()}),SR=ae({issuer:e(),authorization_endpoint:me,token_endpoint:me,userinfo_endpoint:me.optional(),jwks_uri:me,registration_endpoint:me.optional(),scopes_supported:o(e()).optional(),response_types_supported:o(e()),response_modes_supported:o(e()).optional(),grant_types_supported:o(e()).optional(),acr_values_supported:o(e()).optional(),subject_types_supported:o(e()),id_token_signing_alg_values_supported:o(e()),id_token_encryption_alg_values_supported:o(e()).optional(),id_token_encryption_enc_values_supported:o(e()).optional(),userinfo_signing_alg_values_supported:o(e()).optional(),userinfo_encryption_alg_values_supported:o(e()).optional(),userinfo_encryption_enc_values_supported:o(e()).optional(),request_object_signing_alg_values_supported:o(e()).optional(),request_object_encryption_alg_values_supported:o(e()).optional(),request_object_encryption_enc_values_supported:o(e()).optional(),token_endpoint_auth_methods_supported:o(e()).optional(),token_endpoint_auth_signing_alg_values_supported:o(e()).optional(),display_values_supported:o(e()).optional(),claim_types_supported:o(e()).optional(),claims_supported:o(e()).optional(),service_documentation:e().optional(),claims_locales_supported:o(e()).optional(),ui_locales_supported:o(e()).optional(),claims_parameter_supported:r().optional(),request_parameter_supported:r().optional(),request_uri_parameter_supported:r().optional(),require_request_uri_registration:r().optional(),op_policy_uri:me.optional(),op_tos_uri:me.optional(),client_id_metadata_document_supported:r().optional()}),Mp=t({...SR.shape,...Aa.pick({code_challenge_methods_supported:!0}).shape}),Np=t({access_token:e(),id_token:e().optional(),token_type:e(),expires_in:Kw().optional(),scope:e().optional(),refresh_token:e().optional(),issuer:e().optional().catch(void 0)}).strip(),qp=t({error:e(),error_description:e().optional(),error_uri:e().optional()}),Ip=me.optional().or(a("").transform(()=>{return})),xR=t({redirect_uris:o(me),token_endpoint_auth_method:e().optional(),grant_types:o(e()).optional(),response_types:o(e()).optional(),client_name:e().optional(),client_uri:me.optional(),logo_uri:Ip,scope:e().optional(),contacts:o(e()).optional(),tos_uri:Ip,policy_uri:e().optional(),jwks_uri:me.optional(),jwks:L().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional()}).strip(),kR=t({client_id:e(),client_secret:e().optional(),client_id_issued_at:n().optional(),client_secret_expires_at:n().optional(),issuer:e().optional().catch(void 0)}).strip(),Dp=xR.merge(kR),EA=t({error:e(),error_description:e().optional()}).strip(),SA=t({token:e(),token_type_hint:e().optional()}).strip();function jp(c){let l=typeof c==="string"?new URL(c):new URL(c.href);return l.hash="",l}function Lp({requestedResource:c,configuredResource:l}){let u=typeof c==="string"?new URL(c):new URL(c.href),g=typeof l==="string"?new URL(l):new URL(l.href);if(u.origin!==g.origin)return!1;if(u.pathname.length<g.pathname.length)return!1;let _=u.pathname.endsWith("/")?u.pathname:u.pathname+"/",y=g.pathname.endsWith("/")?g.pathname:g.pathname+"/";return _.startsWith(y)}class ie extends Error{constructor(c,l){super(c);this.errorUri=l,this.name=this.constructor.name}toResponseObject(){let c={error:this.errorCode,error_description:this.message};if(this.errorUri)c.error_uri=this.errorUri;return c}get errorCode(){return this.constructor.errorCode}}class po extends ie{}po.errorCode="invalid_request";class Yt extends ie{}Yt.errorCode="invalid_client";class Qt extends ie{}Qt.errorCode="invalid_grant";class er extends ie{}er.errorCode="unauthorized_client";class fo extends ie{}fo.errorCode="unsupported_grant_type";class ho extends ie{}ho.errorCode="invalid_scope";class mo extends ie{}mo.errorCode="access_denied";class ht extends ie{}ht.errorCode="server_error";class _o extends ie{}_o.errorCode="temporarily_unavailable";class yo extends ie{}yo.errorCode="unsupported_response_type";class wo extends ie{}wo.errorCode="unsupported_token_type";class vo extends ie{}vo.errorCode="invalid_token";class To extends ie{}To.errorCode="method_not_allowed";class bo extends ie{}bo.errorCode="too_many_requests";class tr extends ie{}tr.errorCode="invalid_client_metadata";class Ro extends ie{}Ro.errorCode="insufficient_scope";class Eo extends ie{}Eo.errorCode="invalid_target";var Up={[po.errorCode]:po,[Yt.errorCode]:Yt,[Qt.errorCode]:Qt,[er.errorCode]:er,[fo.errorCode]:fo,[ho.errorCode]:ho,[mo.errorCode]:mo,[ht.errorCode]:ht,[_o.errorCode]:_o,[yo.errorCode]:yo,[wo.errorCode]:wo,[vo.errorCode]:vo,[To.errorCode]:To,[bo.errorCode]:bo,[tr.errorCode]:tr,[Ro.errorCode]:Ro,[Eo.errorCode]:Eo};function rr(c){if(!c)return{};if(c instanceof Headers)return Object.fromEntries(c.entries());if(Array.isArray(c))return Object.fromEntries(c);return{...c}}function So(c=fetch,l){if(!l)return c;return async(u,g)=>{let _={...l,...g,headers:g?.headers?{...rr(l.headers),...rr(g.headers)}:l.headers};return c(u,_)}}var $R=5,AR=[301,302,303,307,308];function PR(c,l){if(c.protocol===l.protocol&&c.hostname===l.hostname&&c.port===l.port)return!0;return c.hostname===l.hostname&&c.protocol==="http:"&&c.port===""&&l.protocol==="https:"&&l.port===""}function Fp(c,l){let u=AR.includes(c.status)?c.headers.get("location"):null;try{return u?new URL(u,l):void 0}catch{return}}function xo(c,l,u,g,_=0){let y=Fp(g,l),T=g.status===307||g.status===308||(u?.method??"GET").toUpperCase()==="GET";if(!y||_===$R||!T)return;let b=new URL(l);if((y.username||y.password)&&(y.username!==b.username||y.password!==b.password)||!PR(b,y))return;return Promise.resolve(g.body?.cancel()).then(()=>c(y,{...u,redirect:"manual"})).then((S)=>xo(c,y,u,S,_+1)??S)}var Hp=new WeakSet;function nr(c){let l=(u,g)=>(c??fetch)(u,g);return Hp.add(l),l}function We(c=fetch){if(Hp.has(c))return c;return(l,u)=>{if(u?.redirect==="error"||u?.redirect==="manual")return c(l,u);return Promise.resolve(c(l,{...u,redirect:"manual"})).then((g)=>xo(c,l,u,g)??g)}}function or(c,l){if(c.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let u=c.url||l,g=Fp(c,u);if(!g)return;if(g.username=g.password=g.search=g.hash="",g.protocol==="http:"&&new URL(u).protocol==="https:")return g.protocol="https:",`Redirect to plain http not followed; try ${g.href} instead`;return`Redirect to ${g.href} not followed`}class ot extends Error{constructor(c){super(c??"Unauthorized")}}function CR(c){return["client_secret_basic","client_secret_post","none"].includes(c)}var Pa="code",Ca="S256";function IR(c,l){let u=c.client_secret!==void 0;if("token_endpoint_auth_method"in c&&c.token_endpoint_auth_method&&CR(c.token_endpoint_auth_method)&&(l.length===0||l.includes(c.token_endpoint_auth_method)))return c.token_endpoint_auth_method;if(l.length===0)return u?"client_secret_basic":"none";if(u&&l.includes("client_secret_basic"))return"client_secret_basic";if(u&&l.includes("client_secret_post"))return"client_secret_post";if(l.includes("none"))return"none";return u?"client_secret_post":"none"}function zR(c,l,u,g){let{client_id:_,client_secret:y}=l;switch(c){case"client_secret_basic":OR(_,y,u);return;case"client_secret_post":MR(_,y,g);return;case"none":NR(_,g);return;default:throw Error(`Unsupported client authentication method: ${c}`)}}function OR(c,l,u){if(!l)throw Error("client_secret_basic authentication requires a client_secret");let g=btoa(`${c}:${l}`);u.set("Authorization",`Basic ${g}`)}function MR(c,l,u){if(u.set("client_id",c),l)u.set("client_secret",l)}function NR(c,l){l.set("client_id",c)}async function Wp(c){let l=c instanceof Response?c.status:void 0,u=c instanceof Response?await c.text():c;try{let g=qp.parse(JSON.parse(u)),{error:_,error_description:y,error_uri:T}=g;return new(Up[_]||ht)(y||"",T)}catch(g){let _=c instanceof Response?or(c,c.url):void 0,y=`${l?`HTTP ${l}: `:""}${_??`Invalid OAuth error response: ${g}. Raw body: ${u}`}`;return new ht(y)}}function qR(c,l){let[u,g]=[c,l];try{[u,g]=[new URL(c).href,new URL(l).href]}catch{}return u===g||u.endsWith("/")&&u.slice(0,-1)===g||g.endsWith("/")&&g.slice(0,-1)===u}function Oa(c,l){if(!c)return;if(typeof c.issuer!=="string")return c.issuer==null?c:{...c,issuer:void 0};return qR(c.issuer,l)?c:void 0}var DR=Np.omit({issuer:!0}),jR=Dp.omit({issuer:!0});function Kp(c,l){return Error(`OAuth client information is bound to authorization server ${c.issuer} and is not presented to ${l}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function Qe(c,l){try{return await Ia(c,l)}catch(u){if(u instanceof Yt||u instanceof er)return await c.invalidateCredentials?.("all"),await Ia(c,l);else if(u instanceof Qt)return await c.invalidateCredentials?.("tokens"),await Ia(c,l);throw u}}async function Ia(c,{serverUrl:l,authorizationCode:u,scope:g,resourceMetadataUrl:_,fetchFn:y}){let T=await c.discoveryState?.(),b,E,S,k=_;if(!k&&T?.resourceMetadataUrl)k=new URL(T.resourceMetadataUrl);if(T?.authorizationServerUrl){if(E=T.authorizationServerUrl,b=T.resourceMetadata,S=T.authorizationServerMetadata??await Gp(E,{fetchFn:y}),!b)try{b=await Bp(l,{resourceMetadataUrl:k},y)}catch{}if(S!==T.authorizationServerMetadata||b!==T.resourceMetadata)await c.saveDiscoveryState?.({authorizationServerUrl:String(E),resourceMetadataUrl:k?.toString(),resourceMetadata:b,authorizationServerMetadata:S})}else{let ue=await KR(l,{resourceMetadataUrl:k,fetchFn:y});E=ue.authorizationServerUrl,S=ue.authorizationServerMetadata,b=ue.resourceMetadata,await c.saveDiscoveryState?.({authorizationServerUrl:String(E),resourceMetadataUrl:k?.toString(),resourceMetadata:b,authorizationServerMetadata:S})}let A=String(E),z=await UR(l,c,b),C=z&&b&&!c.validateResourceURL?b.resource:z,P=g||b?.scopes_supported?.join(" ")||c.clientMetadata.scope,I=await Promise.resolve(c.clientInformation()),M=Oa(I,A),N=c.saveClientInformation!==void 0&&!!c.redirectUrl;if(I&&!M&&!N)throw Kp(I,A);let D=M?.issuer==null?M:void 0,U=async()=>{try{if(D)await c.saveClientInformation?.({...D,issuer:A})}catch{}};if(!M){if(u!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let ue=S?.client_id_metadata_document_supported===!0,Ie=c.clientMetadataUrl;if(Ie&&!LR(Ie))throw new tr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ie}`);if(ue&&Ie)M={client_id:Ie,issuer:A},await c.saveClientInformation?.(M);else{if(!c.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");M={...await JR(E,{metadata:S,clientMetadata:c.clientMetadata,scope:P,fetchFn:y}),issuer:A},await c.saveClientInformation(M)}}let F=!c.redirectUrl;if(u!==void 0||F){let ue=await XR(c,E,{metadata:S,resource:C,authorizationCode:u,fetchFn:y});return await U(),await c.saveTokens({...ue,issuer:A}),"AUTHORIZED"}let O=Oa(await c.tokens(),A);if(O?.refresh_token&&O.issuer==null)console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");if(O?.refresh_token)try{let ue=await ZR(E,{metadata:S,clientInformation:M,refreshToken:O.refresh_token,resource:C,addClientAuthentication:c.addClientAuthentication,fetchFn:y});return await U(),await c.saveTokens({...ue,issuer:A}),"AUTHORIZED"}catch(ue){if(!(ue instanceof ie)||ue instanceof ht);else throw ue}let H=c.state?await c.state():void 0,{authorizationUrl:ee,codeVerifier:Se}=await BR(E,{metadata:S,clientInformation:M,state:H,redirectUrl:c.redirectUrl,scope:P,resource:C});return await c.saveCodeVerifier(Se),await c.redirectToAuthorization(ee),"REDIRECT"}function LR(c){if(!c)return!1;try{let l=new URL(c);return l.protocol==="https:"&&l.pathname!=="/"}catch{return!1}}async function UR(c,l,u){let g=jp(c);if(l.validateResourceURL)return await l.validateResourceURL(g,u?.resource);if(!u)return;if(!Lp({requestedResource:g,configuredResource:u.resource}))throw Error(`Protected resource ${u.resource} does not match expected ${g} (or origin)`);return new URL(u.resource)}function sr(c){let l=c.headers.get("WWW-Authenticate");if(!l)return{};let[u,g]=l.split(" ");if(u.toLowerCase()!=="bearer"||!g)return{};let _=za(c,"resource_metadata")||void 0,y;if(_)try{y=new URL(_)}catch{}let T=za(c,"scope")||void 0,b=za(c,"error")||void 0;return{resourceMetadataUrl:y,scope:T,error:b}}function za(c,l){let u=c.headers.get("WWW-Authenticate");if(!u)return null;let g=new RegExp(`${l}=(?:"([^"]+)"|([^\\s,]+))`),_=u.match(g);if(_)return _[1]||_[2];return null}async function Bp(c,l,u=fetch){let g=await VR(c,"oauth-protected-resource",u,{protocolVersion:l?.protocolVersion,metadataUrl:l?.resourceMetadataUrl});if(!g||g.status===404)throw await g?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!g.ok)throw await g.body?.cancel(),Error(`HTTP ${g.status} trying to load well-known OAuth protected resource metadata.`);return Op.parse(await g.json())}async function Ma(c,l,u=fetch){try{return await We(u)(c,{headers:l})}catch(g){if(g instanceof TypeError)if(l)return Ma(c,void 0,u);else return;throw g}}function FR(c,l="",u={}){if(l.endsWith("/"))l=l.slice(0,-1);return u.prependPathname?`${l}/.well-known/${c}`:`/.well-known/${c}${l}`}async function Vp(c,l,u=fetch){return await Ma(c,{"MCP-Protocol-Version":l},u)}function HR(c,l){return!c||!c.ok&&c.status<500&&l!=="/"}async function VR(c,l,u,g){let _=new URL(c),y=g?.protocolVersion??Mt,T;if(g?.metadataUrl)T=new URL(g.metadataUrl);else{let E=FR(l,_.pathname);T=new URL(E,g?.metadataServerUrl??_),T.search=_.search}let b=await Vp(T,y,u);if(!g?.metadataUrl&&HR(b,_.pathname)){let E=new URL(`/.well-known/${l}`,_);b=await Vp(E,y,u)}return b}function WR(c){let l=typeof c==="string"?new URL(c):c,u=l.pathname!=="/",g=[];if(!u)return g.push({url:new URL("/.well-known/oauth-authorization-server",l.origin),type:"oauth"}),g.push({url:new URL("/.well-known/openid-configuration",l.origin),type:"oidc"}),g;let _=l.pathname;if(_.endsWith("/"))_=_.slice(0,-1);return g.push({url:new URL(`/.well-known/oauth-authorization-server${_}`,l.origin),type:"oauth"}),g.push({url:new URL(`/.well-known/openid-configuration${_}`,l.origin),type:"oidc"}),g.push({url:new URL(`${_}/.well-known/openid-configuration`,l.origin),type:"oidc"}),g}async function Gp(c,{fetchFn:l=fetch,protocolVersion:u=Mt}={}){let g={"MCP-Protocol-Version":u,Accept:"application/json"},_=WR(c);for(let{url:y,type:T}of _){let b=await Ma(y,g,l);if(!b)continue;if(!b.ok){if(await b.body?.cancel(),b.status<500)continue;throw Error(`HTTP ${b.status} trying to load ${T==="oauth"?"OAuth":"OpenID provider"} metadata from ${y}`)}if(T==="oauth")return Aa.parse(await b.json());else return Mp.parse(await b.json())}return}async function KR(c,l){let u,g;try{if(u=await Bp(c,{resourceMetadataUrl:l?.resourceMetadataUrl},l?.fetchFn),u.authorization_servers&&u.authorization_servers.length>0)g=u.authorization_servers[0]}catch{}if(!g)g=String(new URL("/",c));let _=await Gp(g,{fetchFn:l?.fetchFn});return{authorizationServerUrl:g,authorizationServerMetadata:_,resourceMetadata:u}}function Zp(c){return typeof c==="string"?c:c.href}async function BR(c,{metadata:l,clientInformation:u,redirectUrl:g,scope:_,state:y,resource:T}){let b;if(l){if(b=new URL(l.authorization_endpoint),!l.response_types_supported.includes(Pa))throw Error(`Incompatible auth server: does not support response type ${Pa}`);if(l.code_challenge_methods_supported&&!l.code_challenge_methods_supported.includes(Ca))throw Error(`Incompatible auth server: does not support code challenge method ${Ca}`)}else b=new URL("/authorize",c);let E=await $a(),{code_verifier:S,code_challenge:k}=E;if(b.searchParams.set("response_type",Pa),b.searchParams.set("client_id",u.client_id),b.searchParams.set("code_challenge",k),b.searchParams.set("code_challenge_method",Ca),b.searchParams.set("redirect_uri",String(g)),y)b.searchParams.set("state",y);if(_)b.searchParams.set("scope",_);if(_?.includes("offline_access"))b.searchParams.append("prompt","consent");if(T)b.searchParams.set("resource",Zp(T));return{authorizationUrl:b,codeVerifier:S}}function GR(c,l,u){return new URLSearchParams({grant_type:"authorization_code",code:c,code_verifier:l,redirect_uri:String(u)})}async function Xp(c,{metadata:l,tokenRequestParams:u,clientInformation:g,addClientAuthentication:_,resource:y,fetchFn:T}){let b=l?.token_endpoint?new URL(l.token_endpoint):new URL("/token",c),E=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(y)u.set("resource",Zp(y));if(_)await _(E,u,b,l);else if(g){let k=l?.token_endpoint_auth_methods_supported??[],A=IR(g,k);zR(A,g,E,u)}let S=await We(T??fetch)(b,{method:"POST",headers:E,body:u});if(!S.ok)throw await Wp(S);return DR.parse(await S.json())}async function ZR(c,{metadata:l,clientInformation:u,refreshToken:g,resource:_,addClientAuthentication:y,fetchFn:T}){let b=new URLSearchParams({grant_type:"refresh_token",refresh_token:g}),E=await Xp(c,{metadata:l,tokenRequestParams:b,clientInformation:u,addClientAuthentication:y,resource:_,fetchFn:T});return{refresh_token:g,...E}}async function XR(c,l,{metadata:u,resource:g,authorizationCode:_,fetchFn:y}={}){let T=async()=>{let k=await c.clientInformation(),A=Oa(k,String(l));if(k&&!A)throw Kp(k,String(l));return A},b=await T(),E=c.clientMetadata.scope,S;if(c.prepareTokenRequest)S=await c.prepareTokenRequest(E);if(!S){if(!_)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!c.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let k=await c.codeVerifier();S=GR(_,k,c.redirectUrl)}return b??(b=await T()),Xp(l,{metadata:u,tokenRequestParams:S,clientInformation:b,addClientAuthentication:c.addClientAuthentication,resource:g,fetchFn:y})}async function JR(c,{metadata:l,clientMetadata:u,scope:g,fetchFn:_}){let y;if(l){if(!l.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");y=new URL(l.registration_endpoint)}else y=new URL("/register",c);let T=await We(_??fetch)(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...u,...g!==void 0?{scope:g}:{}})});if(!T.ok)throw await Wp(T);return jR.parse(await T.json())}class Na extends Event{constructor(c,l){var u,g;super(c),this.code=(u=l==null?void 0:l.code)!=null?u:void 0,this.message=(g=l==null?void 0:l.message)!=null?g:void 0}[Symbol.for("nodejs.util.inspect.custom")](c,l,u){return u(Jp(this),l)}[Symbol.for("Deno.customInspect")](c,l){return c(Jp(this),l)}}function YR(c){let l=globalThis.DOMException;return typeof l=="function"?new l(c,"SyntaxError"):SyntaxError(c)}function qa(c){return c instanceof Error?"errors"in c&&Array.isArray(c.errors)?c.errors.map(qa).join(", "):("cause"in c)&&c.cause instanceof Error?`${c}: ${qa(c.cause)}`:c.message:`${c}`}function Jp(c){return{type:c.type,message:c.message,code:c.code,defaultPrevented:c.defaultPrevented,cancelable:c.cancelable,timeStamp:c.timeStamp}}var Qp=(c)=>{throw TypeError(c)},Wa=(c,l,u)=>l.has(c)||Qp("Cannot "+u),G=(c,l,u)=>(Wa(c,l,"read from private field"),u?u.call(c):l.get(c)),le=(c,l,u)=>l.has(c)?Qp("Cannot add the same private member more than once"):l instanceof WeakSet?l.add(c):l.set(c,u),ne=(c,l,u,g)=>(Wa(c,l,"write to private field"),l.set(c,u),u),et=(c,l,u)=>(Wa(c,l,"access private method"),u),Ee,Pt,ar,ko,$o,Jr,lr,Yr,mt,ir,ur,cr,Zr,Fe,Da,ja,La,Yp,Ua,Fa,Xr,Ha,Va;class dr extends EventTarget{constructor(c,l){var u,g;super(),le(this,Fe),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,le(this,Ee),le(this,Pt),le(this,ar),le(this,ko),le(this,$o),le(this,Jr),le(this,lr),le(this,Yr,null),le(this,mt),le(this,ir),le(this,ur,null),le(this,cr,null),le(this,Zr,null),le(this,ja,async(_)=>{var y;G(this,ir).reset();let{body:T,redirected:b,status:E,headers:S}=_;if(E===204){et(this,Fe,Xr).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(b?ne(this,ar,new URL(_.url)):ne(this,ar,void 0),E!==200){et(this,Fe,Xr).call(this,`Non-200 status code (${E})`,E);return}if(!(S.get("content-type")||"").startsWith("text/event-stream")){et(this,Fe,Xr).call(this,'Invalid content type, expected "text/event-stream"',E);return}if(G(this,Ee)===this.CLOSED)return;ne(this,Ee,this.OPEN);let k=new Event("open");if((y=G(this,Zr))==null||y.call(this,k),this.dispatchEvent(k),typeof T!="object"||!T||!("getReader"in T)){et(this,Fe,Xr).call(this,"Invalid response body, expected a web ReadableStream",E),this.close();return}let A=new TextDecoder,z=T.getReader(),C=!0;do{let{done:P,value:I}=await z.read();I&&G(this,ir).feed(A.decode(I,{stream:!P})),P&&(C=!1,G(this,ir).reset(),et(this,Fe,Ha).call(this))}while(C)}),le(this,La,(_)=>{ne(this,mt,void 0),!(_.name==="AbortError"||_.type==="aborted")&&et(this,Fe,Ha).call(this,qa(_))}),le(this,Ua,(_)=>{typeof _.id=="string"&&ne(this,Yr,_.id);let y=new MessageEvent(_.event||"message",{data:_.data,origin:G(this,ar)?G(this,ar).origin:G(this,Pt).origin,lastEventId:_.id||""});G(this,cr)&&(!_.event||_.event==="message")&&G(this,cr).call(this,y),this.dispatchEvent(y)}),le(this,Fa,(_)=>{ne(this,Jr,_)}),le(this,Va,()=>{ne(this,lr,void 0),G(this,Ee)===this.CONNECTING&&et(this,Fe,Da).call(this)});try{if(c instanceof URL)ne(this,Pt,c);else if(typeof c=="string")ne(this,Pt,new URL(c,QR()));else throw Error("Invalid URL")}catch{throw YR("An invalid or illegal string was specified")}ne(this,ir,Xm({onEvent:G(this,Ua),onRetry:G(this,Fa)})),ne(this,Ee,this.CONNECTING),ne(this,Jr,3000),ne(this,$o,(u=l==null?void 0:l.fetch)!=null?u:globalThis.fetch),ne(this,ko,(g=l==null?void 0:l.withCredentials)!=null?g:!1),et(this,Fe,Da).call(this)}get readyState(){return G(this,Ee)}get url(){return G(this,Pt).href}get withCredentials(){return G(this,ko)}get onerror(){return G(this,ur)}set onerror(c){ne(this,ur,c)}get onmessage(){return G(this,cr)}set onmessage(c){ne(this,cr,c)}get onopen(){return G(this,Zr)}set onopen(c){ne(this,Zr,c)}addEventListener(c,l,u){let g=l;super.addEventListener(c,g,u)}removeEventListener(c,l,u){let g=l;super.removeEventListener(c,g,u)}close(){G(this,lr)&&clearTimeout(G(this,lr)),G(this,Ee)!==this.CLOSED&&(G(this,mt)&&G(this,mt).abort(),ne(this,Ee,this.CLOSED),ne(this,mt,void 0))}}Ee=new WeakMap,Pt=new WeakMap,ar=new WeakMap,ko=new WeakMap,$o=new WeakMap,Jr=new WeakMap,lr=new WeakMap,Yr=new WeakMap,mt=new WeakMap,ir=new WeakMap,ur=new WeakMap,cr=new WeakMap,Zr=new WeakMap,Fe=new WeakSet,Da=function(){ne(this,Ee,this.CONNECTING),ne(this,mt,new AbortController),G(this,$o)(G(this,Pt),et(this,Fe,Yp).call(this)).then(G(this,ja)).catch(G(this,La))},ja=new WeakMap,La=new WeakMap,Yp=function(){var c;let l={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...G(this,Yr)?{"Last-Event-ID":G(this,Yr)}:void 0},cache:"no-store",signal:(c=G(this,mt))==null?void 0:c.signal};return"window"in globalThis&&(l.credentials=this.withCredentials?"include":"same-origin"),l},Ua=new WeakMap,Fa=new WeakMap,Xr=function(c,l){var u;G(this,Ee)!==this.CLOSED&&ne(this,Ee,this.CLOSED);let g=new Na("error",{code:l,message:c});(u=G(this,ur))==null||u.call(this,g),this.dispatchEvent(g)},Ha=function(c,l){var u;if(G(this,Ee)===this.CLOSED)return;ne(this,Ee,this.CONNECTING);let g=new Na("error",{code:l,message:c});(u=G(this,ur))==null||u.call(this,g),this.dispatchEvent(g),ne(this,lr,setTimeout(G(this,Va),G(this,Jr)))},Va=new WeakMap,dr.CONNECTING=0,dr.OPEN=1,dr.CLOSED=2;function QR(){let c="document"in globalThis?globalThis.document:void 0;return c&&typeof c=="object"&&"baseURI"in c&&typeof c.baseURI=="string"?c.baseURI:void 0}class go extends Error{constructor(c,l,u){super(`SSE error: ${l}`);this.code=c,this.event=u}}class Ko{constructor(c,l){if(this._url=c,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=l?.eventSourceInit,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._fetchWithInit=So(l?.fetch,l?.requestInit),this._followRedirects=l?.redirectPolicy==="follow",this._followRedirects)this._fetch=nr(this._fetch),this._fetchWithInit=nr(this._fetchWithInit)}_unfollowedRedirect(c,l){let u=or(c,l);return u&&!this._followRedirects?`${u} (redirectPolicy: 'same-origin')`:u}async _authThenStart(){if(!this._authProvider)throw new ot("No auth provider");let c;try{c=await Qe(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(l){throw this.onerror?.(l),l}if(c!=="AUTHORIZED")throw new ot;return await this._startOrAuth()}async _commonHeaders(){let c={};if(this._authProvider){let u=await this._authProvider.tokens();if(u)c.Authorization=`Bearer ${u.access_token}`}if(this._protocolVersion)c["mcp-protocol-version"]=this._protocolVersion;let l=rr(this._requestInit?.headers);return new Headers({...c,...l})}_startOrAuth(){let c=this?._eventSourceInit?.fetch??this._fetch??fetch,l=this._followRedirects?c:We(c),u;return new Promise((g,_)=>{this._eventSource=new dr(this._url.href,{...this._eventSourceInit,fetch:async(y,T)=>{let b=await this._commonHeaders();b.set("Accept","text/event-stream");let E=await l(y,{...T,headers:b});if(u=this._unfollowedRedirect(E,y),E.status===401&&E.headers.has("www-authenticate")){let{resourceMetadataUrl:S,scope:k}=sr(E);this._resourceMetadataUrl=S,this._scope=k}return E}}),this._abortController=new AbortController,this._eventSource.onerror=(y)=>{if(y.code===401&&this._authProvider){this._authThenStart().then(g,_);return}let T=new go(y.code,u??y.message,y);_(T),this.onerror?.(T)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(y)=>{let T=y;try{if(this._endpoint=new URL(T.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(b){_(b),this.onerror?.(b),this.close();return}g()}),this._eventSource.onmessage=(y)=>{let T=y,b;try{b=Nt.parse(JSON.parse(T.data))}catch(E){this.onerror?.(E);return}this.onmessage?.(b)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(c){if(!this._authProvider)throw new ot("No auth provider");if(await Qe(this._authProvider,{serverUrl:this._url,authorizationCode:c,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ot("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(c){if(!this._endpoint)throw Error("Not connected");try{let l=await this._commonHeaders();l.set("content-type","application/json");let u={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(c),signal:this._abortController?.signal},g=await We(this._fetch??fetch)(this._endpoint,u);if(!g.ok){let _=await g.text().catch(()=>null);if(g.status===401&&this._authProvider){let{resourceMetadataUrl:y,scope:T}=sr(g);if(this._resourceMetadataUrl=y,this._scope=T,await Qe(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ot;return this.send(c)}throw Error(`Error POSTing to endpoint (HTTP ${g.status}): ${this._unfollowedRedirect(g,this._endpoint)??_}`)}await g.body?.cancel()}catch(l){throw this.onerror?.(l),l}}setProtocolVersion(c){this._protocolVersion=c}}/*!
|
|
13
|
+
* content-type
|
|
14
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
15
|
+
* MIT Licensed
|
|
16
|
+
*/var ef=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;var eE=/\\([\u000b\u0020-\u00ff])/g;var tE=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;var tf=rE;function rE(c){if(!c)throw TypeError("argument string is required");var l=typeof c==="object"?nE(c):c;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),g=u!==-1?l.slice(0,u).trim():l.trim();if(!tE.test(g))throw TypeError("invalid media type");var _=new oE(g.toLowerCase());if(u!==-1){var y,T,b;ef.lastIndex=u;while(T=ef.exec(l)){if(T.index!==u)throw TypeError("invalid parameter format");if(u+=T[0].length,y=T[1].toLowerCase(),b=T[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(eE,"$1")}_.parameters[y]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return _}function nE(c){var l;if(typeof c.getHeader==="function")l=c.getHeader("content-type");else if(typeof c.headers==="object")l=c.headers&&c.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function oE(c){this.parameters=Object.create(null),this.type=c}function rf(c){if(!c)return;try{return tf(c).type}catch{let l=(c.split(";",1)[0]??"").trim().toLowerCase();if(l===""||c.slice(l.length).includes(","))return;return l}}var aE={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ct extends Error{constructor(c,l){super(`Streamable HTTP error: ${l}`);this.code=c}}class Ho{constructor(c,l){if(this._hasCompletedAuthFlow=!1,this._url=c,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._fetchWithInit=So(l?.fetch,l?.requestInit),this._followRedirects=l?.redirectPolicy==="follow",this._followRedirects)this._fetch=nr(this._fetch),this._fetchWithInit=nr(this._fetchWithInit);this._sessionId=l?.sessionId,this._reconnectionOptions=l?.reconnectionOptions??aE}_unfollowedRedirect(c,l){let u=or(c,l);return u&&!this._followRedirects?`${u} (redirectPolicy: 'same-origin')`:u}async _authThenStart(){if(!this._authProvider)throw new ot("No auth provider");let c;try{c=await Qe(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(l){throw this.onerror?.(l),l}if(c!=="AUTHORIZED")throw new ot;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let c={};if(this._authProvider){let u=await this._authProvider.tokens();if(u)c.Authorization=`Bearer ${u.access_token}`}if(this._sessionId)c["mcp-session-id"]=this._sessionId;if(this._protocolVersion)c["mcp-protocol-version"]=this._protocolVersion;let l=rr(this._requestInit?.headers);return new Headers({...c,...l})}async _startOrAuthSse(c){let{resumptionToken:l}=c;try{let u=await this._commonHeaders();if(u.set("Accept","text/event-stream"),l)u.set("last-event-id",l);let g=this._fetch??fetch,_={method:"GET",headers:u,signal:this._abortController?.signal},y=await g(this._url,this._followRedirects?_:{..._,redirect:"manual"}),T=this._followRedirects?void 0:xo(g,this._url,_,y);if(T)y=await T;if(!y.ok){if(await y.body?.cancel(),y.status===401&&this._authProvider)return await this._authThenStart();if(y.status===405)return;throw new Ct(y.status,`Failed to open SSE stream: ${this._unfollowedRedirect(y,this._url)??y.statusText}`)}this._handleSseStream(y.body,c,!0)}catch(u){throw this.onerror?.(u),u}}_getNextReconnectionDelay(c){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let l=this._reconnectionOptions.initialReconnectionDelay,u=this._reconnectionOptions.reconnectionDelayGrowFactor,g=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(u,c),g)}_scheduleReconnection(c,l=0){let u=this._reconnectionOptions.maxRetries;if(l>=u){this.onerror?.(Error(`Maximum reconnection attempts (${u}) exceeded.`));return}let g=this._getNextReconnectionDelay(l);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(c).catch((_)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${_ instanceof Error?_.message:String(_)}`)),this._scheduleReconnection(c,l+1)})},g)}_handleSseStream(c,l,u){if(!c)return;let{onresumptiontoken:g,replayMessageId:_}=l,y,T=!1,b=!1;(async()=>{try{let S=c.pipeThrough(new TextDecoderStream).pipeThrough(new Wr({onRetry:(z)=>{this._serverRetryMs=z}})).getReader();while(!0){let{value:z,done:C}=await S.read();if(C)break;if(z.id)y=z.id,T=!0,g?.(z.id);if(!z.data)continue;if(!z.event||z.event==="message")try{let P=Nt.parse(JSON.parse(z.data));if(yt(P)){if(b=!0,_!==void 0)P.id=_}this.onmessage?.(P)}catch(P){this.onerror?.(P)}}if((u||T)&&!b&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:y,onresumptiontoken:g,replayMessageId:_},0)}catch(S){if(this.onerror?.(Error(`SSE stream disconnected: ${S}`)),(u||T)&&!b&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:y,onresumptiontoken:g,replayMessageId:_},0)}catch(z){this.onerror?.(Error(`Failed to reconnect: ${z instanceof Error?z.message:String(z)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(c){if(!this._authProvider)throw new ot("No auth provider");if(await Qe(this._authProvider,{serverUrl:this._url,authorizationCode:c,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ot("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(c,l){try{let{resumptionToken:u,onresumptiontoken:g}=l||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:fr(c)?c.id:void 0}).catch((z)=>this.onerror?.(z));return}let _=await this._commonHeaders();_.set("content-type","application/json"),_.set("accept","application/json, text/event-stream");let y={...this._requestInit,method:"POST",headers:_,body:JSON.stringify(c),signal:this._abortController?.signal},T=await We(this._fetch??fetch)(this._url,y),b=T.headers.get("mcp-session-id");if(b)this._sessionId=b;if(!T.ok){let z=await T.text().catch(()=>null);if(T.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ct(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:C,scope:P}=sr(T);if(this._resourceMetadataUrl=C,this._scope=P,await Qe(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ot;return this._hasCompletedAuthFlow=!0,this.send(c)}if(T.status===403&&this._authProvider){let{resourceMetadataUrl:C,scope:P,error:I}=sr(T);if(I==="insufficient_scope"){let M=T.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new Ct(403,"Server returned 403 after trying upscoping");if(P)this._scope=P;if(C)this._resourceMetadataUrl=C;if(this._lastUpscopingHeader=M??void 0,await Qe(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ot;return this.send(c)}}throw new Ct(T.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(T,this._url)??z}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,T.status===202){if(await T.body?.cancel(),li(c))this._startOrAuthSse({resumptionToken:void 0}).catch((z)=>this.onerror?.(z));return}let S=(Array.isArray(c)?c:[c]).filter((z)=>("method"in z)&&("id"in z)&&z.id!==void 0).length>0,k=T.headers.get("content-type"),A=rf(k);if(S)if(A==="text/event-stream")this._handleSseStream(T.body,{onresumptiontoken:g},!1);else if(A==="application/json"){let z=await T.json(),C=Array.isArray(z)?z.map((P)=>Nt.parse(P)):[Nt.parse(z)];for(let P of C)this.onmessage?.(P)}else throw await T.body?.cancel(),new Ct(-1,`Unexpected content type: ${k}`);else await T.body?.cancel()}catch(u){throw this.onerror?.(u),u}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let c=await this._commonHeaders(),l={...this._requestInit,method:"DELETE",headers:c,signal:this._abortController?.signal},u=await We(this._fetch??fetch)(this._url,l);if(await u.body?.cancel(),!u.ok&&u.status!==405)throw new Ct(u.status,`Failed to terminate session: ${this._unfollowedRedirect(u,this._url)??u.statusText}`);this._sessionId=void 0}catch(c){throw this.onerror?.(c),c}}setProtocolVersion(c){this._protocolVersion=c}get protocolVersion(){return this._protocolVersion}async resumeStream(c,l){await this._startOrAuthSse({resumptionToken:c,onresumptiontoken:l?.onresumptiontoken})}}import{mkdirSync as iE}from"node:fs";import{createRequire as cE}from"node:module";import{dirname as lE}from"node:path";var uE=3,dE=50;function x(){return new Date().toISOString()}function rt(c){return c?1:0}function f(c){return typeof c==="string"?c:""}function h(c){if(typeof c!=="string")return;let l=c.trim();return l.length>0?l:void 0}function wt(c){return c===1||c===!0}function pE(c){if(c<=0)return;try{let l=new SharedArrayBuffer(4),u=new Int32Array(l);Atomics.wait(u,0,0,c)}catch{}}function fE(c){if(!c||typeof c!=="object")return!1;let l=sf(c),u=cf(c);return u==="SQLITE_BUSY"||u==="SQLITE_LOCKED"||l.includes("SQLITE_BUSY")||l.includes("SQLITE_LOCKED")||l.includes("database is locked")}function gt(c){let l=0;for(;;)try{return c()}catch(u){if(!fE(u)||l>=uE)throw u;l+=1,pE(dE*2**(l-1))}}function hE(c){return{prepare:(l)=>{let u=c.query(l);return{run:(...g)=>gt(()=>u.run(...g)),get:(...g)=>gt(()=>u.get(...g)),all:(...g)=>gt(()=>u.all(...g))}},exec:(l)=>gt(()=>c.exec(l)),close:()=>c.close?.()}}function mE(c){return{prepare:(l)=>{let u=c.prepare(l);return{run:(...g)=>gt(()=>u.run(...g)),get:(...g)=>gt(()=>u.get(...g)??null),all:(...g)=>gt(()=>u.all(...g))}},exec:(l)=>gt(()=>c.exec(l)),close:()=>c.close?.()}}function V(c){iE(lE(c),{recursive:!0});let l=cE(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:g}=l("bun:sqlite");return hE(new g(c,{create:!0}))}let u=process.emitWarning;process.emitWarning=(g,..._)=>{if((typeof g==="string"?g:g?.message??"").includes("SQLite"))return;return u.call(process,g,..._)};try{let{DatabaseSync:g}=l(["node",":sqlite"].join(""));return mE(new g(c))}finally{process.emitWarning=u}}var gE=[`CREATE TABLE IF NOT EXISTS sessions (
|
|
17
|
+
session_id TEXT PRIMARY KEY,
|
|
18
|
+
source TEXT NOT NULL,
|
|
19
|
+
pid INTEGER NOT NULL,
|
|
20
|
+
started_at TEXT NOT NULL,
|
|
21
|
+
ended_at TEXT,
|
|
22
|
+
exit_code INTEGER,
|
|
23
|
+
status TEXT NOT NULL,
|
|
24
|
+
status_lock INTEGER NOT NULL DEFAULT 0,
|
|
25
|
+
interactive INTEGER NOT NULL,
|
|
26
|
+
provider TEXT NOT NULL,
|
|
27
|
+
model TEXT NOT NULL,
|
|
28
|
+
cwd TEXT NOT NULL,
|
|
29
|
+
workspace_root TEXT NOT NULL,
|
|
30
|
+
team_name TEXT,
|
|
31
|
+
enable_tools INTEGER NOT NULL,
|
|
32
|
+
enable_spawn INTEGER NOT NULL,
|
|
33
|
+
enable_teams INTEGER NOT NULL,
|
|
34
|
+
parent_session_id TEXT,
|
|
35
|
+
parent_agent_id TEXT,
|
|
36
|
+
agent_id TEXT,
|
|
37
|
+
conversation_id TEXT,
|
|
38
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
prompt TEXT,
|
|
40
|
+
metadata_json TEXT,
|
|
41
|
+
transcript_path TEXT NOT NULL DEFAULT '',
|
|
42
|
+
hook_path TEXT NOT NULL,
|
|
43
|
+
messages_path TEXT,
|
|
44
|
+
updated_at TEXT NOT NULL
|
|
45
|
+
);`,`CREATE TABLE IF NOT EXISTS subagent_spawn_queue (
|
|
46
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
47
|
+
root_session_id TEXT NOT NULL,
|
|
48
|
+
parent_agent_id TEXT NOT NULL,
|
|
49
|
+
task TEXT,
|
|
50
|
+
system_prompt TEXT,
|
|
51
|
+
created_at TEXT NOT NULL,
|
|
52
|
+
consumed_at TEXT
|
|
53
|
+
);`,`CREATE TABLE IF NOT EXISTS schedules (
|
|
54
|
+
schedule_id TEXT PRIMARY KEY,
|
|
55
|
+
name TEXT NOT NULL,
|
|
56
|
+
cron_pattern TEXT NOT NULL,
|
|
57
|
+
prompt TEXT NOT NULL,
|
|
58
|
+
provider TEXT NOT NULL,
|
|
59
|
+
model TEXT NOT NULL,
|
|
60
|
+
mode TEXT NOT NULL DEFAULT 'act',
|
|
61
|
+
workspace_root TEXT,
|
|
62
|
+
cwd TEXT,
|
|
63
|
+
system_prompt TEXT,
|
|
64
|
+
max_iterations INTEGER,
|
|
65
|
+
timeout_seconds INTEGER,
|
|
66
|
+
max_parallel INTEGER NOT NULL DEFAULT 1,
|
|
67
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
68
|
+
created_at TEXT NOT NULL,
|
|
69
|
+
updated_at TEXT NOT NULL,
|
|
70
|
+
last_run_at TEXT,
|
|
71
|
+
next_run_at TEXT,
|
|
72
|
+
claim_token TEXT,
|
|
73
|
+
claim_started_at TEXT,
|
|
74
|
+
claim_until_at TEXT,
|
|
75
|
+
created_by TEXT,
|
|
76
|
+
tags TEXT,
|
|
77
|
+
metadata_json TEXT
|
|
78
|
+
);`,`CREATE TABLE IF NOT EXISTS schedule_executions (
|
|
79
|
+
execution_id TEXT PRIMARY KEY,
|
|
80
|
+
schedule_id TEXT NOT NULL,
|
|
81
|
+
session_id TEXT,
|
|
82
|
+
triggered_at TEXT NOT NULL,
|
|
83
|
+
started_at TEXT,
|
|
84
|
+
ended_at TEXT,
|
|
85
|
+
status TEXT NOT NULL,
|
|
86
|
+
exit_code INTEGER,
|
|
87
|
+
error_message TEXT,
|
|
88
|
+
iterations INTEGER,
|
|
89
|
+
tokens_used INTEGER,
|
|
90
|
+
cost_usd REAL,
|
|
91
|
+
FOREIGN KEY (schedule_id) REFERENCES schedules(schedule_id) ON DELETE CASCADE,
|
|
92
|
+
FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE SET NULL
|
|
93
|
+
);`,`CREATE INDEX IF NOT EXISTS idx_schedule_executions_schedule
|
|
94
|
+
ON schedule_executions(schedule_id, triggered_at DESC);`,`CREATE INDEX IF NOT EXISTS idx_schedules_next_run
|
|
95
|
+
ON schedules(enabled, next_run_at);`],_E=[{table:"sessions",column:"workspace_root",sql:"ALTER TABLE sessions ADD COLUMN workspace_root TEXT;"},{table:"sessions",column:"parent_session_id",sql:"ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;"},{table:"sessions",column:"parent_agent_id",sql:"ALTER TABLE sessions ADD COLUMN parent_agent_id TEXT;"},{table:"sessions",column:"agent_id",sql:"ALTER TABLE sessions ADD COLUMN agent_id TEXT;"},{table:"sessions",column:"conversation_id",sql:"ALTER TABLE sessions ADD COLUMN conversation_id TEXT;"},{table:"sessions",column:"is_subagent",sql:"ALTER TABLE sessions ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0;"},{table:"sessions",column:"messages_path",sql:"ALTER TABLE sessions ADD COLUMN messages_path TEXT;"},{table:"sessions",column:"metadata_json",sql:"ALTER TABLE sessions ADD COLUMN metadata_json TEXT;"},{table:"sessions",column:"transcript_path",sql:"ALTER TABLE sessions ADD COLUMN transcript_path TEXT NOT NULL DEFAULT '';"},{table:"schedules",column:"claim_token",sql:"ALTER TABLE schedules ADD COLUMN claim_token TEXT;"},{table:"schedules",column:"claim_started_at",sql:"ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;"},{table:"schedules",column:"claim_until_at",sql:"ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;"}];function yE(c,l){return new Set(c.prepare(`PRAGMA table_info(${l});`).all().map((u)=>u.name))}function Qo(c,l={}){c.exec("PRAGMA journal_mode = WAL;"),c.exec("PRAGMA busy_timeout = 5000;");for(let _ of gE)c.exec(_);if(!l.includeLegacyMigrations)return;let u=new Map,g=(_)=>{let y=u.get(_);if(!y)y=yE(c,_),u.set(_,y);return y};for(let _ of _E)if(!g(_.table).has(_.column)){if(c.exec(_.sql),_.column==="workspace_root")c.exec("UPDATE sessions SET workspace_root = cwd WHERE workspace_root IS NULL OR workspace_root = '';");u.delete(_.table)}}import{existsSync as wE,readFileSync as vE,renameSync as TE}from"node:fs";var bE=`CREATE TABLE IF NOT EXISTS connector_configs (
|
|
96
|
+
channel TEXT PRIMARY KEY,
|
|
97
|
+
type TEXT NOT NULL,
|
|
98
|
+
values_json TEXT NOT NULL DEFAULT '{}',
|
|
99
|
+
security_enabled INTEGER NOT NULL DEFAULT 0,
|
|
100
|
+
security_values_json TEXT NOT NULL DEFAULT '{}',
|
|
101
|
+
configured_at TEXT NOT NULL,
|
|
102
|
+
updated_at TEXT NOT NULL
|
|
103
|
+
);`,RE=`CREATE TABLE IF NOT EXISTS connector_connections (
|
|
104
|
+
channel TEXT NOT NULL,
|
|
105
|
+
instance_id TEXT NOT NULL,
|
|
106
|
+
connect_args_json TEXT NOT NULL,
|
|
107
|
+
last_successful_args_json TEXT NOT NULL,
|
|
108
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
109
|
+
updated_at TEXT NOT NULL,
|
|
110
|
+
last_connected_at TEXT NOT NULL,
|
|
111
|
+
PRIMARY KEY (channel, instance_id)
|
|
112
|
+
);`;function af(c){c.exec("PRAGMA journal_mode = WAL;"),c.exec("PRAGMA busy_timeout = 5000;"),c.exec(bE),c.exec(RE)}function It(c){return typeof c==="object"&&c!==null&&!Array.isArray(c)}function nf(c){if(typeof c!=="string"||!c)return{};try{let l=JSON.parse(c);if(!It(l))return{};let u={};for(let[g,_]of Object.entries(l))if(typeof _==="string")u[g]=_;return u}catch{return{}}}function of(c){if(typeof c!=="string"||!c)return;try{let l=JSON.parse(c);if(!Array.isArray(l))return;return l.filter((u)=>typeof u==="string")}catch{return}}class Ga{dbPath;db;constructor(c={}){this.dbPath=c.dbPath??Vu()}getRawDb(){if(this.db)return this.db;let c=V(this.dbPath);return af(c),this.db=c,this.importLegacyJsonSettings(),c}close(){this.db?.close?.(),this.db=void 0}getConfig(c){let l=this.getRawDb().prepare("SELECT * FROM connector_configs WHERE channel = ?").get(c);return l?Ka(l):void 0}listConfigs(){return this.getRawDb().prepare("SELECT * FROM connector_configs ORDER BY channel ASC").all().map(Ka)}getConnection(c,l){let u=this.getRawDb().prepare(`SELECT * FROM connector_connections
|
|
113
|
+
WHERE channel = ? AND instance_id = ?`).get(c,l);return u?Ba(u):void 0}listConnections(c){return(c?this.getRawDb().prepare(`SELECT * FROM connector_connections
|
|
114
|
+
WHERE channel = ?
|
|
115
|
+
ORDER BY instance_id ASC`).all(c):this.getRawDb().prepare(`SELECT * FROM connector_connections
|
|
116
|
+
ORDER BY channel ASC, instance_id ASC`).all()).map(Ba)}upsertConfig(c){let l=x(),u=this.getRawDb();u.exec("BEGIN IMMEDIATE;");try{let g=u.prepare("SELECT * FROM connector_configs WHERE channel = ?").get(c.channel),_=g?Ka(g):void 0,T=u.prepare("SELECT * FROM connector_connections WHERE channel = ?").all(c.channel).map(Ba),b=c.updateConnectArgs&&T.length===1&&T[0]?c.updateConnectArgs({config:_,connection:T[0]}):void 0;if(u.prepare(`INSERT INTO connector_configs (
|
|
117
|
+
channel, type, values_json, security_enabled,
|
|
118
|
+
security_values_json, configured_at, updated_at
|
|
119
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
120
|
+
ON CONFLICT(channel) DO UPDATE SET
|
|
121
|
+
type = excluded.type,
|
|
122
|
+
values_json = excluded.values_json,
|
|
123
|
+
security_enabled = excluded.security_enabled,
|
|
124
|
+
security_values_json = excluded.security_values_json,
|
|
125
|
+
configured_at = excluded.configured_at,
|
|
126
|
+
updated_at = excluded.updated_at`).run(c.channel,c.type??c.channel,JSON.stringify(c.values),rt(c.security?.enabled===!0),JSON.stringify(c.security?.values??{}),c.configuredAt??_?.configuredAt??l,c.updatedAt??l),b&&T[0])u.prepare(`UPDATE connector_connections
|
|
127
|
+
SET connect_args_json = ?, updated_at = ?
|
|
128
|
+
WHERE channel = ? AND instance_id = ?`).run(JSON.stringify(b),l,c.channel,T[0].instanceId);u.exec("COMMIT;")}catch(g){try{u.exec("ROLLBACK;")}catch{}throw g}}recordConnected(c,l,u){let g=x();this.getRawDb().prepare(`INSERT INTO connector_connections (
|
|
129
|
+
channel, instance_id, connect_args_json,
|
|
130
|
+
last_successful_args_json, enabled, updated_at, last_connected_at
|
|
131
|
+
) VALUES (?, ?, ?, ?, 1, ?, ?)
|
|
132
|
+
ON CONFLICT(channel, instance_id) DO UPDATE SET
|
|
133
|
+
connect_args_json = excluded.connect_args_json,
|
|
134
|
+
last_successful_args_json = excluded.last_successful_args_json,
|
|
135
|
+
enabled = 1,
|
|
136
|
+
updated_at = excluded.updated_at,
|
|
137
|
+
last_connected_at = excluded.last_connected_at`).run(c,l,JSON.stringify(u),JSON.stringify(u),g,g)}setEnabled(c,l,u){if(u){this.getRawDb().prepare(`UPDATE connector_connections
|
|
138
|
+
SET enabled = ?, updated_at = ?
|
|
139
|
+
WHERE channel = ? AND instance_id = ?`).run(rt(l),x(),c,u);return}this.getRawDb().prepare(`UPDATE connector_connections
|
|
140
|
+
SET enabled = ?, updated_at = ?
|
|
141
|
+
WHERE channel = ?`).run(rt(l),x(),c)}deleteConnection(c,l){return(this.getRawDb().prepare(`DELETE FROM connector_connections
|
|
142
|
+
WHERE channel = ? AND instance_id = ?`).run(c,l).changes??0)>0}disableAll(){this.getRawDb().prepare("UPDATE connector_connections SET enabled = 0, updated_at = ?").run(x())}deleteConfig(c){return(this.getRawDb().prepare("DELETE FROM connector_configs WHERE channel = ?").run(c).changes??0)>0}importLegacyJsonSettings(){let c=Gu();if(!wE(c))return;try{let l=JSON.parse(vE(c,"utf8")),u=It(l)&&It(l.connectors)?l.connectors:{};for(let[g,_]of Object.entries(u)){if(!It(_)||this.getConfig(g))continue;let y={};if(It(_.values)){for(let[E,S]of Object.entries(_.values))if(typeof S==="string")y[E]=S}let T={},b=It(_.security)?_.security:void 0;if(b&&It(b.values)){for(let[E,S]of Object.entries(b.values))if(typeof S==="string")T[E]=S}this.upsertConfig({channel:g,type:typeof _.type==="string"?_.type:g,values:y,security:b?{enabled:b.enabled===!0,values:T}:void 0,configuredAt:typeof _.configuredAt==="string"?_.configuredAt:void 0,updatedAt:typeof _.updatedAt==="string"?_.updatedAt:void 0})}TE(c,`${c}.migrated`)}catch{}}}function Ka(c){let l=c.security_enabled===1,u=nf(c.security_values_json),g=l||Object.keys(u).length>0;return{channel:f(c.channel),type:f(c.type),values:nf(c.values_json),security:g?{enabled:l,values:u}:void 0,configuredAt:f(c.configured_at),updatedAt:f(c.updated_at)}}function Ba(c){return{channel:f(c.channel),instanceId:f(c.instance_id),connectArgs:of(c.connect_args_json)??[],lastSuccessfulArgs:of(c.last_successful_args_json)??[],enabled:c.enabled===1,updatedAt:f(c.updated_at),lastConnectedAt:h(c.last_connected_at)??f(c.updated_at)}}function Je(c){let l=new Ga;try{return c(l)}finally{l.close()}}export{pc,Cn,zv,Y,ga,q,un,ot,go,Ko,Ho,x,rt,f,h,wt,V,Qo,Je};
|