@ours.network/mcp 0.17.0-nightly.16 → 0.17.0-nightly.18
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/cli.js
CHANGED
|
@@ -1,56 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
3
|
-
var sy=Object.create;var Js=Object.defineProperty;var iy=Object.getOwnPropertyDescriptor;var ay=Object.getOwnPropertyNames;var cy=Object.getPrototypeOf,uy=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gs=(e,t)=>{for(var r in t)Js(e,r,{get:t[r],enumerable:!0})},ly=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ay(t))!uy.call(e,o)&&o!==r&&Js(e,o,{get:()=>t[o],enumerable:!(n=iy(t,o))||n.enumerable});return e};var Qu=(e,t,r)=>(r=e!=null?sy(cy(e)):{},ly(t||!e||!e.__esModule?Js(r,"default",{value:e,enumerable:!0}):r,e));var $n=T(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.regexpCode=B.getEsmExportName=B.getProperty=B.safeStringify=B.stringify=B.strConcat=B.addCodeArg=B.str=B._=B.nil=B._Code=B.Name=B.IDENTIFIER=B._CodeOrName=void 0;var bn=class{};B._CodeOrName=bn;B.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jt=class extends bn{constructor(t){if(super(),!B.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};B.Name=Jt;var He=class extends bn{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Jt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};B._Code=He;B.nil=new He("");function Df(e,...t){let r=[e[0]],n=0;for(;n<t.length;)wa(r,t[n]),r.push(e[++n]);return new He(r)}B._=Df;var va=new He("+");function Uf(e,...t){let r=[Sn(e[0])],n=0;for(;n<t.length;)r.push(va),wa(r,t[n]),r.push(va,Sn(e[++n]));return gb(r),new He(r)}B.str=Uf;function wa(e,t){t instanceof He?e.push(...t._items):t instanceof Jt?e.push(t):e.push(vb(t))}B.addCodeArg=wa;function gb(e){let t=1;for(;t<e.length-1;){if(e[t]===va){let r=_b(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function _b(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Jt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Jt))return`"${e}${t.slice(1)}`}function yb(e,t){return t.emptyStr()?e:e.emptyStr()?t:Uf`${e}${t}`}B.strConcat=yb;function vb(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Sn(Array.isArray(e)?e.join(","):e)}function wb(e){return new He(Sn(e))}B.stringify=wb;function Sn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}B.safeStringify=Sn;function bb(e){return typeof e=="string"&&B.IDENTIFIER.test(e)?new He(`.${e}`):Df`[${e}]`}B.getProperty=bb;function Sb(e){if(typeof e=="string"&&B.IDENTIFIER.test(e))return new He(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}B.getEsmExportName=Sb;function $b(e){return new He(e.toString())}B.regexpCode=$b});var $a=T(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.ValueScope=Ne.ValueScopeName=Ne.Scope=Ne.varKinds=Ne.UsedValueState=void 0;var Ce=$n(),ba=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Go;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Go||(Ne.UsedValueState=Go={}));Ne.varKinds={const:new Ce.Name("const"),let:new Ce.Name("let"),var:new Ce.Name("var")};var Wo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ce.Name?t:this.name(t)}name(t){return new Ce.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ne.Scope=Wo;var Yo=class extends Ce.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ce._)`.${new Ce.Name(r)}[${n}]`}};Ne.ValueScopeName=Yo;var xb=(0,Ce._)`\n`,Sa=class extends Wo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?xb:Ce.nil}}get(){return this._scope}name(t){return new Yo(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ce._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ce.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Go.Started);let l=r(u);if(l){let d=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const;s=(0,Ce._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ce._)`${s}${l}${this.opts._n}`;else throw new ba(u);c.set(u,Go.Completed)})}return s}};Ne.ValueScope=Sa});var M=T(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var Z=$n(),Qe=$a(),Tt=$n();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Tt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Tt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Tt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Tt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Tt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Tt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Tt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Tt.Name}});var ts=$a();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return ts.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return ts.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return ts.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return ts.varKinds}});D.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("+")};var mt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},xa=class extends mt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Qe.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Tr(this.rhs,t,r)),this}get names(){return this.rhs instanceof Z._CodeOrName?this.rhs.names:{}}},Xo=class extends mt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Z.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Tr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Z.Name?{}:{...this.lhs.names};return es(t,this.rhs)}},ka=class extends Xo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},za=class extends mt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Pa=class extends mt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ta=class extends mt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ra=class extends mt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Tr(this.code,t,r),this}get names(){return this.code instanceof Z._CodeOrName?this.code.names:{}}},xn=class extends mt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(kb(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Yt(t,r.names),{})}},ht=class extends xn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ea=class extends xn{},Pr=class extends ht{};Pr.kind="else";var Gt=class e extends ht{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Pr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(qf(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Tr(this.condition,t,r),this}get names(){let t=super.names;return es(t,this.condition),this.else&&Yt(t,this.else.names),t}};Gt.kind="if";var Wt=class extends ht{};Wt.kind="for";var Ia=class extends Wt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Tr(this.iteration,t,r),this}get names(){return Yt(super.names,this.iteration.names)}},Oa=class extends Wt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Qe.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=es(super.names,this.from);return es(t,this.to)}},Qo=class extends Wt{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Tr(this.iterable,t,r),this}get names(){return Yt(super.names,this.iterable.names)}},kn=class extends ht{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};kn.kind="func";var zn=class extends xn{render(t){return"return "+super.render(t)}};zn.kind="return";var Aa=class extends ht{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Yt(t,this.catch.names),this.finally&&Yt(t,this.finally.names),t}},Pn=class extends ht{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Pn.kind="catch";var Tn=class extends ht{render(t){return"finally"+super.render(t)}};Tn.kind="finally";var Ca=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
4
|
-
`:""},this._extScope=t,this._scope=new Qe.Scope({parent:t}),this._nodes=[new Ea]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new xa(t,s,n)),s}const(t,r,n){return this._def(Qe.varKinds.const,t,r,n)}let(t,r,n){return this._def(Qe.varKinds.let,t,r,n)}var(t,r,n){return this._def(Qe.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Xo(t,r,n))}add(t,r){return this._leafNode(new ka(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Z.nil&&this._leafNode(new Ra(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Z.addCodeArg)(r,o));return r.push("}"),new Z._Code(r)}if(t,r,n){if(this._blockNode(new Gt(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Gt(t))}else(){return this._elseNode(new Pr)}endIf(){return this._endBlockNode(Gt,Pr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ia(t),r)}forRange(t,r,n,o,s=this.opts.es5?Qe.varKinds.var:Qe.varKinds.let){let i=this._scope.toName(t);return this._for(new Oa(s,i,r,n),()=>o(i))}forOf(t,r,n,o=Qe.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof Z.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Z._)`${i}.length`,a=>{this.var(s,(0,Z._)`${i}[${a}]`),n(s)})}return this._for(new Qo("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Z._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new Qo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Wt)}label(t){return this._leafNode(new za(t))}break(t){return this._leafNode(new Pa(t))}return(t){let r=new zn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(zn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Aa;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new Pn(s),r(s)}return n&&(this._currNode=o.finally=new Tn,this.code(n)),this._endBlockNode(Pn,Tn)}throw(t){return this._leafNode(new Ta(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Z.nil,n,o){return this._blockNode(new kn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(kn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Gt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};D.CodeGen=Ca;function Yt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function es(e,t){return t instanceof Z._CodeOrName?Yt(e,t.names):e}function Tr(e,t,r){if(e instanceof Z.Name)return n(e);if(!o(e))return e;return new Z._Code(e._items.reduce((s,i)=>(i instanceof Z.Name&&(i=n(i)),i instanceof Z._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof Z._Code&&s._items.some(i=>i instanceof Z.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function kb(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function qf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Z._)`!${Na(e)}`}D.not=qf;var zb=Zf(D.operators.AND);function Pb(...e){return e.reduce(zb)}D.and=Pb;var Tb=Zf(D.operators.OR);function Rb(...e){return e.reduce(Tb)}D.or=Rb;function Zf(e){return(t,r)=>t===Z.nil?r:r===Z.nil?t:(0,Z._)`${Na(t)} ${e} ${Na(r)}`}function Na(e){return e instanceof Z.Name?e:(0,Z._)`(${e})`}});var F=T(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.checkStrictMode=U.getErrorPath=U.Type=U.useFunc=U.setEvaluated=U.evaluatedPropsToName=U.mergeEvaluated=U.eachItem=U.unescapeJsonPointer=U.escapeJsonPointer=U.escapeFragment=U.unescapeFragment=U.schemaRefOrVal=U.schemaHasRulesButRef=U.schemaHasRules=U.checkUnknownRules=U.alwaysValidSchema=U.toHash=void 0;var Q=M(),Eb=$n();function Ib(e){let t={};for(let r of e)t[r]=!0;return t}U.toHash=Ib;function Ob(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Vf(e,t),!Hf(t,e.self.RULES.all))}U.alwaysValidSchema=Ob;function Vf(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||Jf(e,`unknown keyword: "${s}"`)}U.checkUnknownRules=Vf;function Hf(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}U.schemaHasRules=Hf;function Ab(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}U.schemaHasRulesButRef=Ab;function Cb({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Q._)`${r}`}return(0,Q._)`${e}${t}${(0,Q.getProperty)(n)}`}U.schemaRefOrVal=Cb;function Nb(e){return Bf(decodeURIComponent(e))}U.unescapeFragment=Nb;function jb(e){return encodeURIComponent(Ma(e))}U.escapeFragment=jb;function Ma(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}U.escapeJsonPointer=Ma;function Bf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}U.unescapeJsonPointer=Bf;function Mb(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}U.eachItem=Mb;function Lf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Q.Name?(s instanceof Q.Name?e(o,s,i):t(o,s,i),i):s instanceof Q.Name?(t(o,i,s),s):r(s,i);return a===Q.Name&&!(c instanceof Q.Name)?n(o,c):c}}U.mergeEvaluated={props:Lf({mergeNames:(e,t,r)=>e.if((0,Q._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Q._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Q._)`${r} || {}`).code((0,Q._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Q._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Q._)`${r} || {}`),Da(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Kf}),items:Lf({mergeNames:(e,t,r)=>e.if((0,Q._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Q._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Q._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Q._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Kf(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,Q._)`{}`);return t!==void 0&&Da(e,r,t),r}U.evaluatedPropsToName=Kf;function Da(e,t,r){Object.keys(r).forEach(n=>e.assign((0,Q._)`${t}${(0,Q.getProperty)(n)}`,!0))}U.setEvaluated=Da;var Ff={};function Db(e,t){return e.scopeValue("func",{ref:t,code:Ff[t.code]||(Ff[t.code]=new Eb._Code(t.code))})}U.useFunc=Db;var ja;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ja||(U.Type=ja={}));function Ub(e,t,r){if(e instanceof Q.Name){let n=t===ja.Num;return r?n?(0,Q._)`"[" + ${e} + "]"`:(0,Q._)`"['" + ${e} + "']"`:n?(0,Q._)`"/" + ${e}`:(0,Q._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Q.getProperty)(e).toString():"/"+Ma(e)}U.getErrorPath=Ub;function Jf(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}U.checkStrictMode=Jf});var gt=T(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var ke=M(),qb={data:new ke.Name("data"),valCxt:new ke.Name("valCxt"),instancePath:new ke.Name("instancePath"),parentData:new ke.Name("parentData"),parentDataProperty:new ke.Name("parentDataProperty"),rootData:new ke.Name("rootData"),dynamicAnchors:new ke.Name("dynamicAnchors"),vErrors:new ke.Name("vErrors"),errors:new ke.Name("errors"),this:new ke.Name("this"),self:new ke.Name("self"),scope:new ke.Name("scope"),json:new ke.Name("json"),jsonPos:new ke.Name("jsonPos"),jsonLen:new ke.Name("jsonLen"),jsonPart:new ke.Name("jsonPart")};Ua.default=qb});var Rn=T(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var V=M(),rs=F(),Re=gt();ze.keywordError={message:({keyword:e})=>(0,V.str)`must pass "${e}" keyword validation`};ze.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,V.str)`"${e}" keyword must be ${t} ($data)`:(0,V.str)`"${e}" keyword is invalid ($data)`};function Zb(e,t=ze.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=Yf(e,t,r);n??(i||a)?Gf(s,c):Wf(o,(0,V._)`[${c}]`)}ze.reportError=Zb;function Lb(e,t=ze.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=Yf(e,t,r);Gf(o,a),s||i||Wf(n,Re.default.vErrors)}ze.reportExtraError=Lb;function Fb(e,t){e.assign(Re.default.errors,t),e.if((0,V._)`${Re.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,V._)`${Re.default.vErrors}.length`,t),()=>e.assign(Re.default.vErrors,null)))}ze.resetErrorsCount=Fb;function Vb({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,Re.default.errors,a=>{e.const(i,(0,V._)`${Re.default.vErrors}[${a}]`),e.if((0,V._)`${i}.instancePath === undefined`,()=>e.assign((0,V._)`${i}.instancePath`,(0,V.strConcat)(Re.default.instancePath,s.errorPath))),e.assign((0,V._)`${i}.schemaPath`,(0,V.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,V._)`${i}.schema`,r),e.assign((0,V._)`${i}.data`,n))})}ze.extendErrors=Vb;function Gf(e,t){let r=e.const("err",t);e.if((0,V._)`${Re.default.vErrors} === null`,()=>e.assign(Re.default.vErrors,(0,V._)`[${r}]`),(0,V._)`${Re.default.vErrors}.push(${r})`),e.code((0,V._)`${Re.default.errors}++`)}function Wf(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,V._)`new ${e.ValidationError}(${t})`):(r.assign((0,V._)`${n}.errors`,t),r.return(!1))}var Xt={keyword:new V.Name("keyword"),schemaPath:new V.Name("schemaPath"),params:new V.Name("params"),propertyName:new V.Name("propertyName"),message:new V.Name("message"),schema:new V.Name("schema"),parentSchema:new V.Name("parentSchema")};function Yf(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,V._)`{}`:Hb(e,t,r)}function Hb(e,t,r={}){let{gen:n,it:o}=e,s=[Bb(o,r),Kb(e,r)];return Jb(e,t,s),n.object(...s)}function Bb({errorPath:e},{instancePath:t}){let r=t?(0,V.str)`${e}${(0,rs.getErrorPath)(t,rs.Type.Str)}`:e;return[Re.default.instancePath,(0,V.strConcat)(Re.default.instancePath,r)]}function Kb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,V.str)`${t}/${e}`;return r&&(o=(0,V.str)`${o}${(0,rs.getErrorPath)(r,rs.Type.Str)}`),[Xt.schemaPath,o]}function Jb(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Xt.keyword,o],[Xt.params,typeof t=="function"?t(e):t||(0,V._)`{}`]),c.messages&&n.push([Xt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Xt.schema,i],[Xt.parentSchema,(0,V._)`${l}${d}`],[Re.default.data,s]),u&&n.push([Xt.propertyName,u])}});var Qf=T(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.boolOrEmptySchema=Rr.topBoolOrEmptySchema=void 0;var Gb=Rn(),Wb=M(),Yb=gt(),Xb={message:"boolean schema is false"};function Qb(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Xf(e,!1):typeof r=="object"&&r.$async===!0?t.return(Yb.default.data):(t.assign((0,Wb._)`${n}.errors`,null),t.return(!0))}Rr.topBoolOrEmptySchema=Qb;function eS(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Xf(e)):r.var(t,!0)}Rr.boolOrEmptySchema=eS;function Xf(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Gb.reportError)(o,Xb,void 0,t)}});var qa=T(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.getRules=Er.isJSONType=void 0;var tS=["string","number","integer","boolean","null","object","array"],rS=new Set(tS);function nS(e){return typeof e=="string"&&rS.has(e)}Er.isJSONType=nS;function oS(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Er.getRules=oS});var Za=T(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.shouldUseRule=Rt.shouldUseGroup=Rt.schemaHasRulesForType=void 0;function sS({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&em(e,n)}Rt.schemaHasRulesForType=sS;function em(e,t){return t.rules.some(r=>tm(e,r))}Rt.shouldUseGroup=em;function tm(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Rt.shouldUseRule=tm});var En=T(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.reportTypeError=Pe.checkDataTypes=Pe.checkDataType=Pe.coerceAndCheckDataType=Pe.getJSONTypes=Pe.getSchemaTypes=Pe.DataType=void 0;var iS=qa(),aS=Za(),cS=Rn(),j=M(),rm=F(),Ir;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ir||(Pe.DataType=Ir={}));function uS(e){let t=nm(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Pe.getSchemaTypes=uS;function nm(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(iS.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Pe.getJSONTypes=nm;function lS(e,t){let{gen:r,data:n,opts:o}=e,s=dS(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,aS.schemaHasRulesForType)(e,t[0]));if(i){let a=Fa(t,n,o.strictNumbers,Ir.Wrong);r.if(a,()=>{s.length?pS(e,t,s):Va(e)})}return i}Pe.coerceAndCheckDataType=lS;var om=new Set(["string","number","integer","boolean","null"]);function dS(e,t){return t?e.filter(r=>om.has(r)||t==="array"&&r==="array"):[]}function pS(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,j._)`typeof ${o}`),a=n.let("coerced",(0,j._)`undefined`);s.coerceTypes==="array"&&n.if((0,j._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,j._)`${o}[0]`).assign(i,(0,j._)`typeof ${o}`).if(Fa(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,j._)`${a} !== undefined`);for(let u of r)(om.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Va(e),n.endIf(),n.if((0,j._)`${a} !== undefined`,()=>{n.assign(o,a),fS(e,a)});function c(u){switch(u){case"string":n.elseIf((0,j._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,j._)`"" + ${o}`).elseIf((0,j._)`${o} === null`).assign(a,(0,j._)`""`);return;case"number":n.elseIf((0,j._)`${i} == "boolean" || ${o} === null
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,j._)`[${o}]`)}}}function fS({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,j._)`${t} !== undefined`,()=>e.assign((0,j._)`${t}[${r}]`,n))}function La(e,t,r,n=Ir.Correct){let o=n===Ir.Correct?j.operators.EQ:j.operators.NEQ,s;switch(e){case"null":return(0,j._)`${t} ${o} null`;case"array":s=(0,j._)`Array.isArray(${t})`;break;case"object":s=(0,j._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,j._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,j._)`typeof ${t} ${o} ${e}`}return n===Ir.Correct?s:(0,j.not)(s);function i(a=j.nil){return(0,j.and)((0,j._)`typeof ${t} == "number"`,a,r?(0,j._)`isFinite(${t})`:j.nil)}}Pe.checkDataType=La;function Fa(e,t,r,n){if(e.length===1)return La(e[0],t,r,n);let o,s=(0,rm.toHash)(e);if(s.array&&s.object){let i=(0,j._)`typeof ${t} != "object"`;o=s.null?i:(0,j._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=j.nil;s.number&&delete s.integer;for(let i in s)o=(0,j.and)(o,La(i,t,r,n));return o}Pe.checkDataTypes=Fa;var mS={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,j._)`{type: ${e}}`:(0,j._)`{type: ${t}}`};function Va(e){let t=hS(e);(0,cS.reportError)(t,mS)}Pe.reportTypeError=Va;function hS(e){let{gen:t,data:r,schema:n}=e,o=(0,rm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var im=T(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.assignDefaults=void 0;var Or=M(),gS=F();function _S(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)sm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>sm(e,s,o.default))}ns.assignDefaults=_S;function sm(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,Or._)`${s}${(0,Or.getProperty)(t)}`;if(o){(0,gS.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Or._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Or._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Or._)`${a} = ${(0,Or.stringify)(r)}`)}});var Be=T(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.validateUnion=Y.validateArray=Y.usePattern=Y.callValidateCode=Y.schemaProperties=Y.allSchemaProperties=Y.noPropertyInData=Y.propertyInData=Y.isOwnProperty=Y.hasPropFunc=Y.reportMissingProp=Y.checkMissingProp=Y.checkReportMissingProp=void 0;var ie=M(),Ha=F(),Et=gt(),yS=F();function vS(e,t){let{gen:r,data:n,it:o}=e;r.if(Ka(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ie._)`${t}`},!0),e.error()})}Y.checkReportMissingProp=vS;function wS({gen:e,data:t,it:{opts:r}},n,o){return(0,ie.or)(...n.map(s=>(0,ie.and)(Ka(e,t,s,r.ownProperties),(0,ie._)`${o} = ${s}`)))}Y.checkMissingProp=wS;function bS(e,t){e.setParams({missingProperty:t},!0),e.error()}Y.reportMissingProp=bS;function am(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ie._)`Object.prototype.hasOwnProperty`})}Y.hasPropFunc=am;function Ba(e,t,r){return(0,ie._)`${am(e)}.call(${t}, ${r})`}Y.isOwnProperty=Ba;function SS(e,t,r,n){let o=(0,ie._)`${t}${(0,ie.getProperty)(r)} !== undefined`;return n?(0,ie._)`${o} && ${Ba(e,t,r)}`:o}Y.propertyInData=SS;function Ka(e,t,r,n){let o=(0,ie._)`${t}${(0,ie.getProperty)(r)} === undefined`;return n?(0,ie.or)(o,(0,ie.not)(Ba(e,t,r))):o}Y.noPropertyInData=Ka;function cm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Y.allSchemaProperties=cm;function $S(e,t){return cm(t).filter(r=>!(0,Ha.alwaysValidSchema)(e,t[r]))}Y.schemaProperties=$S;function xS({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ie._)`${e}, ${t}, ${n}${o}`:t,d=[[Et.default.instancePath,(0,ie.strConcat)(Et.default.instancePath,s)],[Et.default.parentData,i.parentData],[Et.default.parentDataProperty,i.parentDataProperty],[Et.default.rootData,Et.default.rootData]];i.opts.dynamicRef&&d.push([Et.default.dynamicAnchors,Et.default.dynamicAnchors]);let p=(0,ie._)`${l}, ${r.object(...d)}`;return c!==ie.nil?(0,ie._)`${a}.call(${c}, ${p})`:(0,ie._)`${a}(${p})`}Y.callValidateCode=xS;var kS=(0,ie._)`new RegExp`;function zS({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ie._)`${o.code==="new RegExp"?kS:(0,yS.useFunc)(e,o)}(${r}, ${n})`})}Y.usePattern=zS;function PS(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,ie._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:Ha.Type.Num},s),t.if((0,ie.not)(s),a)})}}Y.validateArray=PS;function TS(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ha.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,ie._)`${i} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,ie.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}Y.validateUnion=TS});var dm=T(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateKeywordUsage=st.validSchemaType=st.funcKeywordCode=st.macroKeywordCode=void 0;var Ee=M(),Qt=gt(),RS=Be(),ES=Rn();function IS(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=lm(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:Ee.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}st.macroKeywordCode=IS;function OS(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;CS(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=lm(n,o,u),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)g(),t.modifying&&um(e),y(()=>e.error());else{let b=t.async?m():h();t.modifying&&um(e),y(()=>AS(e,b))}}function m(){let b=n.let("ruleErrs",null);return n.try(()=>g((0,Ee._)`await `),$=>n.assign(d,!1).if((0,Ee._)`${$} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Ee._)`${$}.errors`),()=>n.throw($))),b}function h(){let b=(0,Ee._)`${l}.errors`;return n.assign(b,null),g(Ee.nil),b}function g(b=t.async?(0,Ee._)`await `:Ee.nil){let $=c.opts.passContext?Qt.default.this:Qt.default.self,S=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Ee._)`${b}${(0,RS.callValidateCode)(e,l,$,S)}`,t.modifying)}function y(b){var $;n.if((0,Ee.not)(($=t.valid)!==null&&$!==void 0?$:d),b)}}st.funcKeywordCode=OS;function um(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ee._)`${n.parentData}[${n.parentDataProperty}]`))}function AS(e,t){let{gen:r}=e;r.if((0,Ee._)`Array.isArray(${t})`,()=>{r.assign(Qt.default.vErrors,(0,Ee._)`${Qt.default.vErrors} === null ? ${t} : ${Qt.default.vErrors}.concat(${t})`).assign(Qt.default.errors,(0,Ee._)`${Qt.default.vErrors}.length`),(0,ES.extendErrors)(e)},()=>e.error())}function CS({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function lm(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ee.stringify)(r)})}function NS(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}st.validSchemaType=NS;function jS({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}st.validateKeywordUsage=jS});var fm=T(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.extendSubschemaMode=It.extendSubschemaData=It.getSubschema=void 0;var it=M(),pm=F();function MS(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,it._)`${e.schemaPath}${(0,it.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,it._)`${e.schemaPath}${(0,it.getProperty)(t)}${(0,it.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,pm.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}It.getSubschema=MS;function DS(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",(0,it._)`${t.data}${(0,it.getProperty)(r)}`,!0);c(p),e.errorPath=(0,it.str)`${u}${(0,pm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,it._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let u=o instanceof it.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}It.extendSubschemaData=DS;function US(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}It.extendSubschemaMode=US});var Ja=T((pC,mm)=>{"use strict";mm.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var gm=T((fC,hm)=>{"use strict";var Ot=hm.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};os(t,n,o,e,"",e)};Ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ot.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ot.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 os(e,t,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Ot.arrayKeywords)for(var p=0;p<d.length;p++)os(e,t,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in Ot.propsKeywords){if(d&&typeof d=="object")for(var m in d)os(e,t,r,d[m],o+"/"+l+"/"+qS(m),s,o,l,n,m)}else(l in Ot.keywords||e.allKeys&&!(l in Ot.skipKeywords))&&os(e,t,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function qS(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var In=T(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getSchemaRefs=je.resolveUrl=je.normalizeId=je._getFullPath=je.getFullPath=je.inlineRef=void 0;var ZS=F(),LS=Ja(),FS=gm(),VS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function HS(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ga(e):t?_m(e)<=t:!1}je.inlineRef=HS;var BS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ga(e){for(let t in e){if(BS.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ga)||typeof r=="object"&&Ga(r))return!0}return!1}function _m(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!VS.has(r)&&(typeof e[r]=="object"&&(0,ZS.eachItem)(e[r],n=>t+=_m(n)),t===1/0))return 1/0}return t}function ym(e,t="",r){r!==!1&&(t=Ar(t));let n=e.parse(t);return vm(e,n)}je.getFullPath=ym;function vm(e,t){return e.serialize(t).split("#")[0]+"#"}je._getFullPath=vm;var KS=/#\/?$/;function Ar(e){return e?e.replace(KS,""):""}je.normalizeId=Ar;function JS(e,t,r){return r=Ar(r),e.resolve(t,r)}je.resolveUrl=JS;var GS=/^[a-z_][-a-z0-9._]*$/i;function WS(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ar(e[r]||t),s={"":o},i=ym(n,o,!1),a={},c=new Set;return FS(e,{allKeys:!0},(d,p,m,h)=>{if(h===void 0)return;let g=i+p,y=s[h];typeof d[r]=="string"&&(y=b.call(this,d[r])),$.call(this,d.$anchor),$.call(this,d.$dynamicAnchor),s[p]=y;function b(S){let P=this.opts.uriResolver.resolve;if(S=Ar(y?P(y,S):S),c.has(S))throw l(S);c.add(S);let v=this.refs[S];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,S):S!==Ar(g)&&(S[0]==="#"?(u(d,a[S],S),a[S]=d):this.refs[S]=g),S}function $(S){if(typeof S=="string"){if(!GS.test(S))throw new Error(`invalid anchor "${S}"`);b.call(this,`#${S}`)}}}),a;function u(d,p,m){if(p!==void 0&&!LS(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}je.getSchemaRefs=WS});var Cn=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getData=At.KeywordCxt=At.validateFunctionCode=void 0;var xm=Qf(),wm=En(),Ya=Za(),ss=En(),YS=im(),An=dm(),Wa=fm(),E=M(),N=gt(),XS=In(),_t=F(),On=Rn();function QS(e){if(Pm(e)&&(Tm(e),zm(e))){r$(e);return}km(e,()=>(0,xm.topBoolOrEmptySchema)(e))}At.validateFunctionCode=QS;function km({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,E._)`${N.default.data}, ${N.default.valCxt}`,n.$async,()=>{e.code((0,E._)`"use strict"; ${bm(r,o)}`),t$(e,o),e.code(s)}):e.func(t,(0,E._)`${N.default.data}, ${e$(o)}`,n.$async,()=>e.code(bm(r,o)).code(s))}function e$(e){return(0,E._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${e.dynamicRef?(0,E._)`, ${N.default.dynamicAnchors}={}`:E.nil}}={}`}function t$(e,t){e.if(N.default.valCxt,()=>{e.var(N.default.instancePath,(0,E._)`${N.default.valCxt}.${N.default.instancePath}`),e.var(N.default.parentData,(0,E._)`${N.default.valCxt}.${N.default.parentData}`),e.var(N.default.parentDataProperty,(0,E._)`${N.default.valCxt}.${N.default.parentDataProperty}`),e.var(N.default.rootData,(0,E._)`${N.default.valCxt}.${N.default.rootData}`),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,E._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{e.var(N.default.instancePath,(0,E._)`""`),e.var(N.default.parentData,(0,E._)`undefined`),e.var(N.default.parentDataProperty,(0,E._)`undefined`),e.var(N.default.rootData,N.default.data),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,E._)`{}`)})}function r$(e){let{schema:t,opts:r,gen:n}=e;km(e,()=>{r.$comment&&t.$comment&&Em(e),a$(e),n.let(N.default.vErrors,null),n.let(N.default.errors,0),r.unevaluated&&n$(e),Rm(e),l$(e)})}function n$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,E._)`${r}.evaluated`),t.if((0,E._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,E._)`${e.evaluated}.props`,(0,E._)`undefined`)),t.if((0,E._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,E._)`${e.evaluated}.items`,(0,E._)`undefined`))}function bm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,E._)`/*# sourceURL=${r} */`:E.nil}function o$(e,t){if(Pm(e)&&(Tm(e),zm(e))){s$(e,t);return}(0,xm.boolOrEmptySchema)(e,t)}function zm({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Pm(e){return typeof e.schema!="boolean"}function s$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Em(e),c$(e),u$(e);let s=n.const("_errs",N.default.errors);Rm(e,s),n.var(t,(0,E._)`${s} === ${N.default.errors}`)}function Tm(e){(0,_t.checkUnknownRules)(e),i$(e)}function Rm(e,t){if(e.opts.jtd)return Sm(e,[],!1,t);let r=(0,wm.getSchemaTypes)(e.schema),n=(0,wm.coerceAndCheckDataType)(e,r);Sm(e,r,!n,t)}function i$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,_t.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function a$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,_t.checkStrictMode)(e,"default is ignored in the schema root")}function c$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,XS.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function u$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Em({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,E._)`${N.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,E.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,E._)`${N.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function l$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,E._)`${N.default.errors} === 0`,()=>t.return(N.default.data),()=>t.throw((0,E._)`new ${o}(${N.default.vErrors})`)):(t.assign((0,E._)`${n}.errors`,N.default.vErrors),s.unevaluated&&d$(e),t.return((0,E._)`${N.default.errors} === 0`))}function d$({gen:e,evaluated:t,props:r,items:n}){r instanceof E.Name&&e.assign((0,E._)`${t}.props`,r),n instanceof E.Name&&e.assign((0,E._)`${t}.items`,n)}function Sm(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_t.schemaHasRulesButRef)(s,l))){o.block(()=>Om(e,"$ref",l.all.$ref.definition));return}c.jtd||p$(e,t),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Ya.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ss.checkDataType)(p.type,i,c.strictNumbers)),$m(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,ss.reportTypeError)(e)),o.endIf()):$m(e,p),a||o.if((0,E._)`${N.default.errors} === ${n||0}`))}}function $m(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,YS.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Ya.shouldUseRule)(n,s)&&Om(e,s.keyword,s.definition,t.type)})}function p$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(f$(e,t),e.opts.allowUnionTypes||m$(e,t),h$(e,e.dataTypes))}function f$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Im(e.dataTypes,r)||Xa(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),_$(e,t)}}function m$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Xa(e,"use allowUnionTypes to allow union type keyword")}function h$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ya.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>g$(t,i))&&Xa(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function g$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Im(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function _$(e,t){let r=[];for(let n of e.dataTypes)Im(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Xa(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,_t.checkStrictMode)(e,t,e.opts.strictTypes)}var is=class{constructor(t,r,n){if((0,An.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,_t.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Am(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,An.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",N.default.errors))}result(t,r,n){this.failResult((0,E.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,E.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,E._)`${r} !== undefined && (${(0,E.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=E.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=E.nil,r=E.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,E.or)((0,E._)`${o} === undefined`,r)),t!==E.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==E.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,E.or)(i(),a());function i(){if(n.length){if(!(r instanceof E.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,E._)`${(0,ss.checkDataTypes)(c,r,s.opts.strictNumbers,ss.DataType.Wrong)}`}return E.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,E._)`!${c}(${r})`}return E.nil}}subschema(t,r){let n=(0,Wa.getSubschema)(this.it,t);(0,Wa.extendSubschemaData)(n,this.it,t),(0,Wa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return o$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=_t.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=_t.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,E.Name)),!0}};At.KeywordCxt=is;function Om(e,t,r,n){let o=new is(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,An.funcKeywordCode)(o,r):"macro"in r?(0,An.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,An.funcKeywordCode)(o,r)}var y$=/^\/(?:[^~]|~0|~1)*$/,v$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Am(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!y$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=N.default.rootData}else{let u=v$.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(s=r[t-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,E._)`${s}${(0,E.getProperty)((0,_t.unescapeJsonPointer)(u))}`,i=(0,E._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}At.getData=Am});var as=T(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Qa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};ec.default=Qa});var Nn=T(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var tc=In(),rc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,tc.resolveUrl)(t,r,n),this.missingSchema=(0,tc.normalizeId)((0,tc.getFullPath)(t,this.missingRef))}};nc.default=rc});var us=T(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var et=M(),w$=as(),er=gt(),tt=In(),Cm=F(),b$=Cn(),Cr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,tt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ke.SchemaEnv=Cr;function sc(e){let t=Nm.call(this,e);if(t)return t;let r=(0,tt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:w$.default,code:(0,et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:er.default.data,parentData:er.default.parentData,parentDataProperty:er.default.parentDataProperty,dataNames:[er.default.data],dataPathArr:[et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,et.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:et.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,et._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,b$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(er.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let m=new Function(`${er.default.self}`,`${er.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof et.Name?void 0:h,items:g instanceof et.Name?void 0:g,dynamicProps:h instanceof et.Name,dynamicItems:g instanceof et.Name},m.source&&(m.source.evaluated=(0,et.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(e)}}Ke.compileSchema=sc;function S$(e,t,r){var n;r=(0,tt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=k$.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Cr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=$$.call(this,s)}Ke.resolveRef=S$;function $$(e){return(0,tt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:sc.call(this,e)}function Nm(e){for(let t of this._compilations)if(x$(t,e))return t}Ke.getCompilingSchema=Nm;function x$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function k$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||cs.call(this,e,t)}function cs(e,t){let r=this.opts.uriResolver.parse(t),n=(0,tt._getFullPath)(this.opts.uriResolver,r),o=(0,tt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return oc.call(this,r,e);let s=(0,tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=cs.call(this,e,i);return typeof a?.schema!="object"?void 0:oc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||sc.call(this,i),s===(0,tt.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,tt.resolveUrl)(this.opts.uriResolver,o,u)),new Cr({schema:a,schemaId:c,root:e,baseId:o})}return oc.call(this,r,i)}}Ke.resolveSchema=cs;var z$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function oc(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Cm.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!z$.has(a)&&u&&(t=(0,tt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,tt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=cs.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Cr({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var jm=T((vC,P$)=>{P$.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 cc=T((wC,Lm)=>{"use strict";var T$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dm=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),ic=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Um=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),R$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ac(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var E$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mm(e){return e.length=0,!0}function I$(e,t,r){if(e.length){let n=ac(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function O$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=I$;for(let c=0;c<e.length;c++){let u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Mm}else{o.push(u);continue}}return o.length&&(a===Mm?r.zone=o.join(""):i?n.push(o.join("")):n.push(ac(o))),r.address=n.join(""),r}function qm(e){if(A$(e,":")<2)return{host:e,isIPV6:!1};let t=O$(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function A$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function C$(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var N$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},j$=/[@/?#:]/g,M$=/[@/?#]/g;function Zm(e,t){let r=t?M$:j$;return r.lastIndex=0,e.replace(r,n=>N$[n])}function D$(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(ic(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Um(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function U$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(ic(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Um(s)?t+=s:t+="%"+o,r+=2;continue}}R$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function q$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(ic(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Z$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Dm(r)){let n=qm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Zm(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}Lm.exports={nonSimpleDomain:E$,recomposeAuthority:Z$,reescapeHostDelimiters:Zm,normalizePercentEncoding:D$,normalizePathEncoding:U$,escapePreservingEscapes:q$,removeDotSegments:C$,isIPv4:Dm,isUUID:T$,normalizeIPv6:qm,stringArrayToHexStripped:ac}});var Km=T((bC,Bm)=>{"use strict";var{isUUID:L$}=cc(),F$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,V$=["http","https","ws","wss","urn","urn:uuid"];function H$(e){return V$.indexOf(e)!==-1}function uc(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Fm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Vm(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function B$(e){return e.secure=uc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function K$(e){if((e.port===(uc(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function J$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(F$);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=lc(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function G$(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,s=lc(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function W$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!L$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Y$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Hm={scheme:"http",domainHost:!0,parse:Fm,serialize:Vm},X$={scheme:"https",domainHost:Hm.domainHost,parse:Fm,serialize:Vm},ls={scheme:"ws",domainHost:!0,parse:B$,serialize:K$},Q$={scheme:"wss",domainHost:ls.domainHost,parse:ls.parse,serialize:ls.serialize},e0={scheme:"urn",parse:J$,serialize:G$,skipNormalize:!0},t0={scheme:"urn:uuid",parse:W$,serialize:Y$,skipNormalize:!0},ds={http:Hm,https:X$,ws:ls,wss:Q$,urn:e0,"urn:uuid":t0};Object.setPrototypeOf(ds,null);function lc(e){return e&&(ds[e]||ds[e.toLowerCase()])||void 0}Bm.exports={wsIsSecure:uc,SCHEMES:ds,isValidSchemeName:H$,getSchemeHandler:lc}});var Qm=T((SC,ps)=>{"use strict";var{normalizeIPv6:r0,removeDotSegments:jn,recomposeAuthority:n0,normalizePercentEncoding:o0,normalizePathEncoding:s0,escapePreservingEscapes:i0,reescapeHostDelimiters:a0,isIPv4:c0,nonSimpleDomain:u0}=cc(),{SCHEMES:l0,getSchemeHandler:Gm}=Km();function d0(e,t){return typeof e=="string"?e=_0(e,t):typeof e=="object"&&(e=Nr(tr(e,t),t)),e}function p0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Wm(Nr(e,n),Nr(t,n),n,!0);return n.skipEscape=!0,tr(o,n)}function Wm(e,t,r,n){let o={};return n||(e=Nr(tr(e,r),r),t=Nr(tr(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=jn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=jn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=jn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=jn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function f0(e,t,r){let n=Jm(e,r),o=Jm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function tr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],s=Gm(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=o0(r.path):(r.path=i0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=n0(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=jn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var m0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,h0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function g0(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Ym(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(h0);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=e.match(m0);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=g0(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(c0(n.host)===!1){let d=r0(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Gm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&u0(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=a0(unescape(n.host),s))),n.path&&(n.path=s0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Nr(e,t){return Ym(e,t).parsed}function _0(e,t){return Xm(e,t).normalized}function Xm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Ym(e,t);return{normalized:n?e:tr(r,t),malformedAuthorityOrPort:n}}function Jm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Xm(e,t);return n?void 0:r}if(typeof e=="object")return tr(e,t)}var dc={SCHEMES:l0,normalize:d0,resolve:p0,resolveComponent:Wm,equal:f0,serialize:tr,parse:Nr};ps.exports=dc;ps.exports.default=dc;ps.exports.fastUri=dc});var th=T(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var eh=Qm();eh.code='require("ajv/dist/runtime/uri").default';pc.default=eh});var uh=T(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=void 0;var y0=Cn();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return y0.KeywordCxt}});var jr=M();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return jr._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return jr.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return jr.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return jr.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return jr.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return jr.CodeGen}});var v0=as(),ih=Nn(),w0=qa(),Mn=us(),b0=M(),Dn=In(),fs=En(),mc=F(),rh=jm(),S0=th(),ah=(e,t)=>new RegExp(e,t);ah.code="new RegExp";var $0=["removeAdditional","useDefaults","coerceTypes"],x0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),k0={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."},z0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},nh=200;function P0(e){var t,r,n,o,s,i,a,c,u,l,d,p,m,h,g,y,b,$,S,P,v,x,O,G,ce;let ge=e.strict,St=(t=e.code)===null||t===void 0?void 0:t.optimize,_o=St===!0||St===void 0?1:St||0,yo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:ah,$t=(o=e.uriResolver)!==null&&o!==void 0?o:S0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:ge)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:ge)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:ge)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:ge)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:ge)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:_o,regExp:yo}:{optimize:_o,regExp:yo},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:nh,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:nh,meta:(b=e.meta)!==null&&b!==void 0?b:!0,messages:($=e.messages)!==null&&$!==void 0?$:!0,inlineRefs:(S=e.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(v=e.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(x=e.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(O=e.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(G=e.unicodeRegExp)!==null&&G!==void 0?G:!0,int32range:(ce=e.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:$t}}var Un=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...P0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new b0.ValueScope({scope:{},prefixes:x0,es5:r,lines:n}),this.logger=A0(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,w0.getRules)(),oh.call(this,k0,t,"NOT SUPPORTED"),oh.call(this,z0,t,"DEPRECATED","warn"),this._metaOpts=I0.call(this),t.formats&&R0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&E0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),T0.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=rh;n==="id"&&(o={...rh},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof ih.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Dn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,t);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let r;for(;typeof(r=sh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Mn.SchemaEnv({schema:{},schemaId:n});if(r=Mn.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=sh.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Dn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(N0.call(this,n,r),!r)return(0,mc.eachItem)(n,s=>fc.call(this,s)),this;M0.call(this,r);let o={...r,type:(0,fs.getJSONTypes)(r.type),schemaType:(0,fs.getJSONTypes)(r.schemaType)};return(0,mc.eachItem)(n,o.type.length===0?s=>fc.call(this,s,o):s=>o.type.forEach(i=>fc.call(this,s,o,i))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=ch(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,Dn.normalizeId)(i||n);let u=Dn.getSchemaRefs.call(this,t,n);return c=new Mn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Mn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Mn.compileSchema.call(this,t)}finally{this.opts=r}}};Un.ValidationError=v0.default;Un.MissingRefError=ih.default;we.default=Un;function oh(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function sh(e){return e=(0,Dn.normalizeId)(e),this.schemas[e]||this.refs[e]}function T0(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function R0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E0(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function I0(){let e={...this.opts};for(let t of $0)delete e[t];return e}var O0={log(){},warn(){},error(){}};function A0(e){if(e===!1)return O0;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var C0=/^[a-z_$][a-z0-9_$:-]*$/i;function N0(e,t){let{RULES:r}=this;if((0,mc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!C0.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function fc(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,fs.getJSONTypes)(t.type),schemaType:(0,fs.getJSONTypes)(t.schemaType)}};t.before?j0.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function j0(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function M0(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ch(t)),e.validateSchema=this.compile(t,!0))}var D0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ch(e){return{anyOf:[e,D0]}}});var lh=T(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var U0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hc.default=U0});var mh=T(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.callRef=rr.getValidate=void 0;var q0=Nn(),dh=Be(),Me=M(),Mr=gt(),ph=us(),ms=F(),Z0={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=ph.resolveRef.call(c,u,o,r);if(l===void 0)throw new q0.default(n.opts.uriResolver,o,r);if(l instanceof ph.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return hs(e,i,s,s.$async);let h=t.scopeValue("root",{ref:u});return hs(e,(0,Me._)`${h}.validate`,u,u.$async)}function p(h){let g=fh(e,h);hs(e,g,h,h.$async)}function m(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Me.stringify)(h)}:{ref:h}),y=t.name("valid"),b=e.subschema({schema:h,dataTypes:[],schemaPath:Me.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(b),e.ok(y)}}};function fh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Me._)`${r.scopeValue("wrapper",{ref:t})}.validate`}rr.getValidate=fh;function hs(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Mr.default.this:Me.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Me._)`await ${(0,dh.callValidateCode)(e,t,u)}`),m(t),i||o.assign(h,!0)},g=>{o.if((0,Me._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,dh.callValidateCode)(e,t,u),()=>m(t),()=>p(t))}function p(h){let g=(0,Me._)`${h}.errors`;o.assign(Mr.default.vErrors,(0,Me._)`${Mr.default.vErrors} === null ? ${g} : ${Mr.default.vErrors}.concat(${g})`),o.assign(Mr.default.errors,(0,Me._)`${Mr.default.vErrors}.length`)}function m(h){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ms.mergeEvaluated.props(o,y.props,s.props));else{let b=o.var("props",(0,Me._)`${h}.evaluated.props`);s.props=ms.mergeEvaluated.props(o,b,s.props,Me.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ms.mergeEvaluated.items(o,y.items,s.items));else{let b=o.var("items",(0,Me._)`${h}.evaluated.items`);s.items=ms.mergeEvaluated.items(o,b,s.items,Me.Name)}}}rr.callRef=hs;rr.default=Z0});var hh=T(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var L0=lh(),F0=mh(),V0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",L0.default,F0.default];gc.default=V0});var gh=T(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var gs=M(),Ct=gs.operators,_s={maximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},minimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},exclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},exclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},H0={message:({keyword:e,schemaCode:t})=>(0,gs.str)`must be ${_s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,gs._)`{comparison: ${_s[e].okStr}, limit: ${t}}`},B0={keyword:Object.keys(_s),type:"number",schemaType:"number",$data:!0,error:H0,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,gs._)`${r} ${_s[t].fail} ${n} || isNaN(${r})`)}};_c.default=B0});var _h=T(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var qn=M(),K0={message:({schemaCode:e})=>(0,qn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,qn._)`{multipleOf: ${e}}`},J0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:K0,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,qn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,qn._)`${i} !== parseInt(${i})`;e.fail$data((0,qn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};yc.default=J0});var vh=T(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});function yh(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}vc.default=yh;yh.code='require("ajv/dist/runtime/ucs2length").default'});var wh=T(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var nr=M(),G0=F(),W0=vh(),Y0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,nr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,nr._)`{limit: ${e}}`},X0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Y0,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?nr.operators.GT:nr.operators.LT,i=o.opts.unicode===!1?(0,nr._)`${r}.length`:(0,nr._)`${(0,G0.useFunc)(e.gen,W0.default)}(${r})`;e.fail$data((0,nr._)`${i} ${s} ${n}`)}};wc.default=X0});var bh=T(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var Q0=Be(),ex=F(),Dr=M(),tx={message:({schemaCode:e})=>(0,Dr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Dr._)`{pattern: ${e}}`},rx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:tx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Dr._)`new RegExp`:(0,ex.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Dr._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,Dr._)`!${l}`)}else{let c=(0,Q0.usePattern)(e,o);e.fail$data((0,Dr._)`!${c}.test(${r})`)}}};bc.default=rx});var Sh=T(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Zn=M(),nx={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Zn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Zn._)`{limit: ${e}}`},ox={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:nx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?Zn.operators.GT:Zn.operators.LT;e.fail$data((0,Zn._)`Object.keys(${r}).length ${o} ${n}`)}};Sc.default=ox});var $h=T($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Ln=Be(),Fn=M(),sx=F(),ix={message:({params:{missingProperty:e}})=>(0,Fn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Fn._)`{missingProperty: ${e}}`},ax={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ix,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,b=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,sx.checkStrictMode)(i,b,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Fn.nil,d);else for(let m of r)(0,Ln.checkReportMissingProp)(e,m)}function l(){let m=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>p(m,h)),e.ok(h)}else t.if((0,Ln.checkMissingProp)(e,r,m)),(0,Ln.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,Ln.noPropertyInData)(t,o,m,a.ownProperties),()=>e.error())})}function p(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,Ln.propertyInData)(t,o,m,a.ownProperties)),t.if((0,Fn.not)(h),()=>{e.error(),t.break()})},Fn.nil)}}};$c.default=ax});var xh=T(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Vn=M(),cx={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Vn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Vn._)`{limit: ${e}}`},ux={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:cx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Vn.operators.GT:Vn.operators.LT;e.fail$data((0,Vn._)`${r}.length ${o} ${n}`)}};xc.default=ux});var ys=T(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var kh=Ja();kh.code='require("ajv/dist/runtime/equal").default';kc.default=kh});var zh=T(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var zc=En(),be=M(),lx=F(),dx=ys(),px={message:({params:{i:e,j:t}})=>(0,be.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,be._)`{i: ${e}, j: ${t}}`},fx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:px,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),u=s.items?(0,zc.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,be._)`${i} === false`),e.ok(c);function l(){let h=t.let("i",(0,be._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,be._)`${h} > 1`,()=>(d()?p:m)(h,g))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let y=t.name("item"),b=(0,zc.checkDataTypes)(u,y,a.opts.strictNumbers,zc.DataType.Wrong),$=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${h}--;`,()=>{t.let(y,(0,be._)`${r}[${h}]`),t.if(b,(0,be._)`continue`),u.length>1&&t.if((0,be._)`typeof ${y} == "string"`,(0,be._)`${y} += "_"`),t.if((0,be._)`typeof ${$}[${y}] == "number"`,()=>{t.assign(g,(0,be._)`${$}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,be._)`${$}[${y}] = ${h}`)})}function m(h,g){let y=(0,lx.useFunc)(t,dx.default),b=t.name("outer");t.label(b).for((0,be._)`;${h}--;`,()=>t.for((0,be._)`${g} = ${h}; ${g}--;`,()=>t.if((0,be._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(b)})))}}};Pc.default=fx});var Ph=T(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Tc=M(),mx=F(),hx=ys(),gx={message:"must be equal to constant",params:({schemaCode:e})=>(0,Tc._)`{allowedValue: ${e}}`},_x={keyword:"const",$data:!0,error:gx,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Tc._)`!${(0,mx.useFunc)(t,hx.default)}(${r}, ${o})`):e.fail((0,Tc._)`${s} !== ${r}`)}};Rc.default=_x});var Th=T(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Hn=M(),yx=F(),vx=ys(),wx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Hn._)`{allowedValues: ${e}}`},bx={keyword:"enum",schemaType:"array",$data:!0,error:wx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,yx.useFunc)(t,vx.default)),l;if(a||n)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=t.const("vSchema",s);l=(0,Hn.or)(...o.map((h,g)=>p(m,g)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,m=>t.if((0,Hn._)`${u()}(${r}, ${m})`,()=>t.assign(l,!0).break()))}function p(m,h){let g=o[h];return typeof g=="object"&&g!==null?(0,Hn._)`${u()}(${r}, ${m}[${h}])`:(0,Hn._)`${r} === ${g}`}}};Ec.default=bx});var Rh=T(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Sx=gh(),$x=_h(),xx=wh(),kx=bh(),zx=Sh(),Px=$h(),Tx=xh(),Rx=zh(),Ex=Ph(),Ix=Th(),Ox=[Sx.default,$x.default,xx.default,kx.default,zx.default,Px.default,Tx.default,Rx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ex.default,Ix.default];Ic.default=Ox});var Ac=T(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.validateAdditionalItems=void 0;var or=M(),Oc=F(),Ax={message:({params:{len:e}})=>(0,or.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,or._)`{limit: ${e}}`},Cx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ax,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Oc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Eh(e,n)}};function Eh(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,or._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,or._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Oc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,or._)`${a} <= ${t.length}`);r.if((0,or.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Oc.Type.Num},u),i.allErrors||r.if((0,or.not)(u),()=>r.break())})}}Bn.validateAdditionalItems=Eh;Bn.default=Cx});var Cc=T(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateTuple=void 0;var Ih=M(),vs=F(),Nx=Be(),jx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Oh(e,"additionalItems",t);r.items=!0,!(0,vs.alwaysValidSchema)(r,t)&&e.ok((0,Nx.validateArray)(e))}};function Oh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=vs.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Ih._)`${s}.length`);r.forEach((d,p)=>{(0,vs.alwaysValidSchema)(a,d)||(n.if((0,Ih._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,vs.checkStrictMode)(a,y,p.strictTuples)}}}Kn.validateTuple=Oh;Kn.default=jx});var Ah=T(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Mx=Cc(),Dx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Mx.validateTuple)(e,"items")};Nc.default=Dx});var Nh=T(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Ch=M(),Ux=F(),qx=Be(),Zx=Ac(),Lx={message:({params:{len:e}})=>(0,Ch.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Ch._)`{limit: ${e}}`},Fx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Lx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,Ux.alwaysValidSchema)(n,t)&&(o?(0,Zx.validateAdditionalItems)(e,o):e.ok((0,qx.validateArray)(e)))}};jc.default=Fx});var jh=T(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var Je=M(),ws=F(),Vx={message:({params:{min:e,max:t}})=>t===void 0?(0,Je.str)`must contain at least ${e} valid item(s)`:(0,Je.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Je._)`{minContains: ${e}}`:(0,Je._)`{minContains: ${e}, maxContains: ${t}}`},Hx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Vx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=t.const("len",(0,Je._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,ws.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ws.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ws.alwaysValidSchema)(s,r)){let g=(0,Je._)`${l} >= ${i}`;a!==void 0&&(g=(0,Je._)`${g} && ${l} <= ${a}`),e.pass(g);return}s.items=!0;let d=t.name("valid");a===void 0&&i===1?m(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,!0),a!==void 0&&t.if((0,Je._)`${o}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let g=t.name("_valid"),y=t.let("count",0);m(g,()=>t.if(g,()=>h(y)))}function m(g,y){t.forRange("i",0,l,b=>{e.subschema({keyword:"contains",dataProp:b,dataPropType:ws.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,Je._)`${g}++`),a===void 0?t.if((0,Je._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,Je._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,Je._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Mc.default=Hx});var Uh=T(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.validateSchemaDeps=at.validatePropertyDeps=at.error=void 0;var Dc=M(),Bx=F(),Jn=Be();at.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Dc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Dc._)`{property: ${e},
|
|
8
|
-
missingProperty: ${n},
|
|
9
|
-
depsCount: ${t},
|
|
10
|
-
deps: ${r}}`};var Kx={keyword:"dependencies",type:"object",schemaType:"object",error:at.error,code(e){let[t,r]=Jx(e);Mh(e,t),Dh(e,r)}};function Jx({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Mh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,Jn.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Jn.checkReportMissingProp)(e,u)}):(r.if((0,Dc._)`${c} && (${(0,Jn.checkMissingProp)(e,a,s)})`),(0,Jn.reportMissingProp)(e,s),r.else())}}at.validatePropertyDeps=Mh;function Dh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,Bx.alwaysValidSchema)(s,t[a])||(r.if((0,Jn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i))}at.validateSchemaDeps=Dh;at.default=Kx});var Zh=T(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var qh=M(),Gx=F(),Wx={message:"property name must be valid",params:({params:e})=>(0,qh._)`{propertyName: ${e.propertyName}}`},Yx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Wx,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Gx.alwaysValidSchema)(o,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,qh.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Uc.default=Yx});var Zc=T(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bs=Be(),rt=M(),Xx=gt(),Ss=F(),Qx={message:"must NOT have additional properties",params:({params:e})=>(0,rt._)`{additionalProperty: ${e.additionalProperty}}`},ek={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Qx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Ss.alwaysValidSchema)(i,r))return;let u=(0,bs.allSchemaProperties)(n.properties),l=(0,bs.allSchemaProperties)(n.patternProperties);d(),e.ok((0,rt._)`${s} === ${Xx.default.errors}`);function d(){t.forIn("key",o,y=>{!u.length&&!l.length?h(y):t.if(p(y),()=>h(y))})}function p(y){let b;if(u.length>8){let $=(0,Ss.schemaRefOrVal)(i,n.properties,"properties");b=(0,bs.isOwnProperty)(t,$,y)}else u.length?b=(0,rt.or)(...u.map($=>(0,rt._)`${y} === ${$}`)):b=rt.nil;return l.length&&(b=(0,rt.or)(b,...l.map($=>(0,rt._)`${(0,bs.usePattern)(e,$)}.test(${y})`))),(0,rt.not)(b)}function m(y){t.code((0,rt._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Ss.alwaysValidSchema)(i,r)){let b=t.name("valid");c.removeAdditional==="failing"?(g(y,b,!1),t.if((0,rt.not)(b),()=>{e.reset(),m(y)})):(g(y,b),a||t.if((0,rt.not)(b),()=>t.break()))}}function g(y,b,$){let S={keyword:"additionalProperties",dataProp:y,dataPropType:Ss.Type.Str};$===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(S,b)}}};qc.default=ek});var Vh=T(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var tk=Cn(),Lh=Be(),Lc=F(),Fh=Zc(),rk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Fh.default.code(new tk.KeywordCxt(s,Fh.default,"additionalProperties"));let i=(0,Lh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Lc.mergeEvaluated.props(t,(0,Lc.toHash)(i),s.props));let a=i.filter(d=>!(0,Lc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)u(d)?l(d):(t.if((0,Lh.propertyInData)(t,o,d,s.opts.ownProperties)),l(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Fc.default=rk});var Jh=T(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var Hh=Be(),$s=M(),Bh=F(),Kh=F(),nk={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Hh.allSchemaProperties)(r),c=a.filter(g=>(0,Bh.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof $s.Name)&&(s.props=(0,Kh.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&m(g),s.allErrors?h(g):(t.var(l,!0),h(g),t.if(l))}function m(g){for(let y in u)new RegExp(g).test(y)&&(0,Bh.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,$s._)`${(0,Hh.usePattern)(e,g)}.test(${y})`,()=>{let b=c.includes(g);b||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Kh.Type.Str},l),s.opts.unevaluated&&d!==!0?t.assign((0,$s._)`${d}[${y}]`,!0):!b&&!s.allErrors&&t.if((0,$s.not)(l),()=>t.break())})})}}};Vc.default=nk});var Gh=T(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var ok=F(),sk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,ok.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Hc.default=sk});var Wh=T(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var ik=Be(),ak={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ik.validateUnion,error:{message:"must match a schema in anyOf"}};Bc.default=ak});var Yh=T(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var xs=M(),ck=F(),uk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,xs._)`{passingSchemas: ${e.passing}}`},lk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uk,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;(0,ck.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,xs._)`${c} && ${i}`).assign(i,!1).assign(a,(0,xs._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),p&&e.mergeEvaluated(p,xs.Name)})})}}};Kc.default=lk});var Xh=T(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var dk=F(),pk={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((s,i)=>{if((0,dk.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Jc.default=pk});var tg=T(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ks=M(),eg=F(),fk={message:({params:e})=>(0,ks.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,ks._)`{failingKeyword: ${e.ifClause}}`},mk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:fk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,eg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Qh(n,"then"),s=Qh(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,ks.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),d?t.assign(d,(0,ks._)`${l}`):e.setParams({ifClause:l})}}}};function Qh(e,t){let r=e.schema[t];return r!==void 0&&!(0,eg.alwaysValidSchema)(e,r)}Gc.default=mk});var rg=T(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var hk=F(),gk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,hk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Wc.default=gk});var ng=T(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var _k=Ac(),yk=Ah(),vk=Cc(),wk=Nh(),bk=jh(),Sk=Uh(),$k=Zh(),xk=Zc(),kk=Vh(),zk=Jh(),Pk=Gh(),Tk=Wh(),Rk=Yh(),Ek=Xh(),Ik=tg(),Ok=rg();function Ak(e=!1){let t=[Pk.default,Tk.default,Rk.default,Ek.default,Ik.default,Ok.default,$k.default,xk.default,Sk.default,kk.default,zk.default];return e?t.push(yk.default,wk.default):t.push(_k.default,vk.default),t.push(bk.default),t}Yc.default=Ak});var og=T(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var pe=M(),Ck={message:({schemaCode:e})=>(0,pe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,pe._)`{format: ${e}}`},Nk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Ck,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,pe._)`${h}[${i}]`),y=r.let("fType"),b=r.let("format");r.if((0,pe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,pe._)`${g}.type || "string"`).assign(b,(0,pe._)`${g}.validate`),()=>r.assign(y,(0,pe._)`"string"`).assign(b,g)),e.fail$data((0,pe.or)($(),S()));function $(){return c.strictSchema===!1?pe.nil:(0,pe._)`${i} && !${b}`}function S(){let P=l.$async?(0,pe._)`(${g}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,pe._)`${b}(${n})`,v=(0,pe._)`(typeof ${b} == "function" ? ${P} : ${b}.test(${n}))`;return(0,pe._)`${b} && ${b} !== true && ${y} === ${t} && !${v}`}}function m(){let h=d.formats[s];if(!h){$();return}if(h===!0)return;let[g,y,b]=S(h);g===t&&e.pass(P());function $(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function S(v){let x=v instanceof RegExp?(0,pe.regexpCode)(v):c.code.formats?(0,pe._)`${c.code.formats}${(0,pe.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:v,code:x});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,pe._)`${O}.validate`]:["string",v,O]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,pe._)`await ${b}(${n})`}return typeof y=="function"?(0,pe._)`${b}(${n})`:(0,pe._)`${b}.test(${n})`}}}};Xc.default=Nk});var sg=T(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var jk=og(),Mk=[jk.default];Qc.default=Mk});var ig=T(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.contentVocabulary=Ur.metadataVocabulary=void 0;Ur.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ur.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cg=T(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Dk=hh(),Uk=Rh(),qk=ng(),Zk=sg(),ag=ig(),Lk=[Dk.default,Uk.default,(0,qk.default)(),Zk.default,ag.metadataVocabulary,ag.contentVocabulary];eu.default=Lk});var lg=T(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.DiscrError=void 0;var ug;(function(e){e.Tag="tag",e.Mapping="mapping"})(ug||(zs.DiscrError=ug={}))});var pg=T(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var qr=M(),tu=lg(),dg=us(),Fk=Nn(),Vk=F(),Hk={message:({params:{discrError:e,tagName:t}})=>e===tu.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,qr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Bk={keyword:"discriminator",type:"object",schemaType:"object",error:Hk,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",(0,qr._)`${r}${(0,qr.getProperty)(a)}`);t.if((0,qr._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:tu.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let m=p();t.if(!1);for(let h in m)t.elseIf((0,qr._)`${u} === ${h}`),t.assign(c,d(m[h]));t.else(),e.error(!1,{discrError:tu.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(m){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(g,qr.Name),h}function p(){var m;let h={},g=b(o),y=!0;for(let P=0;P<i.length;P++){let v=i[P];if(v?.$ref&&!(0,Vk.schemaHasRulesButRef)(v,s.self.RULES)){let O=v.$ref;if(v=dg.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),v instanceof dg.SchemaEnv&&(v=v.schema),v===void 0)throw new Fk.default(s.opts.uriResolver,s.baseId,O)}let x=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||b(v)),$(x,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function b({required:P}){return Array.isArray(P)&&P.includes(a)}function $(P,v){if(P.const)S(P.const,v);else if(P.enum)for(let x of P.enum)S(x,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(P,v){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=v}}}};ru.default=Bk});var fg=T((lN,Kk)=>{Kk.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 ou=T((ae,nu)=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.MissingRefError=ae.ValidationError=ae.CodeGen=ae.Name=ae.nil=ae.stringify=ae.str=ae._=ae.KeywordCxt=ae.Ajv=void 0;var Jk=uh(),Gk=cg(),Wk=pg(),mg=fg(),Yk=["/properties"],Ps="http://json-schema.org/draft-07/schema",Zr=class extends Jk.default{_addVocabularies(){super._addVocabularies(),Gk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Wk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(mg,Yk):mg;this.addMetaSchema(t,Ps,!1),this.refs["http://json-schema.org/schema"]=Ps}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ps)?Ps:void 0)}};ae.Ajv=Zr;nu.exports=ae=Zr;nu.exports.Ajv=Zr;Object.defineProperty(ae,"__esModule",{value:!0});ae.default=Zr;var Xk=Cn();Object.defineProperty(ae,"KeywordCxt",{enumerable:!0,get:function(){return Xk.KeywordCxt}});var Lr=M();Object.defineProperty(ae,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(ae,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(ae,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(ae,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(ae,"Name",{enumerable:!0,get:function(){return Lr.Name}});Object.defineProperty(ae,"CodeGen",{enumerable:!0,get:function(){return Lr.CodeGen}});var Qk=as();Object.defineProperty(ae,"ValidationError",{enumerable:!0,get:function(){return Qk.default}});var ez=Nn();Object.defineProperty(ae,"MissingRefError",{enumerable:!0,get:function(){return ez.default}})});var Sg=T(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.formatNames=ut.fastFormats=ut.fullFormats=void 0;function ct(e,t){return{validate:e,compare:t}}ut.fullFormats={date:ct(yg,cu),time:ct(iu(!0),uu),"date-time":ct(hg(!0),wg),"iso-time":ct(iu(),vg),"iso-date-time":ct(hg(),bg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:iz,"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:fz,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:az,int32:{type:"number",validate:lz},int64:{type:"number",validate:dz},float:{type:"number",validate:_g},double:{type:"number",validate:_g},password:!0,binary:!0};ut.fastFormats={...ut.fullFormats,date:ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,cu),time:ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uu),"date-time":ct(/^\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,wg),"iso-time":ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vg),"iso-date-time":ct(/^\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,bg),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};ut.formatNames=Object.keys(ut.fullFormats);function tz(e){return e%4===0&&(e%100!==0||e%400===0)}var rz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,nz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yg(e){let t=rz.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&tz(r)?29:nz[n])}function cu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var su=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function iu(e){return function(r){let n=su.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function uu(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function vg(e,t){if(!(e&&t))return;let r=su.exec(e),n=su.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var au=/t|\s/i;function hg(e){let t=iu(e);return function(n){let o=n.split(au);return o.length===2&&yg(o[0])&&t(o[1])}}function wg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function bg(e,t){if(!(e&&t))return;let[r,n]=e.split(au),[o,s]=t.split(au),i=cu(r,o);if(i!==void 0)return i||uu(n,s)}var oz=/\/|:/,sz=/^(?:[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 iz(e){return oz.test(e)&&sz.test(e)}var gg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function az(e){return gg.lastIndex=0,gg.test(e)}var cz=-(2**31),uz=2**31-1;function lz(e){return Number.isInteger(e)&&e<=uz&&e>=cz}function dz(e){return Number.isInteger(e)}function _g(){return!0}var pz=/[^\\]\\Z/;function fz(e){if(pz.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var $g=T(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.formatLimitDefinition=void 0;var mz=ou(),nt=M(),Nt=nt.operators,Ts={formatMaximum:{okStr:"<=",ok:Nt.LTE,fail:Nt.GT},formatMinimum:{okStr:">=",ok:Nt.GTE,fail:Nt.LT},formatExclusiveMaximum:{okStr:"<",ok:Nt.LT,fail:Nt.GTE},formatExclusiveMinimum:{okStr:">",ok:Nt.GT,fail:Nt.LTE}},hz={message:({keyword:e,schemaCode:t})=>(0,nt.str)`should be ${Ts[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,nt._)`{comparison: ${Ts[e].okStr}, limit: ${t}}`};Fr.formatLimitDefinition={keyword:Object.keys(Ts),type:"string",schemaType:"string",$data:!0,error:hz,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new mz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=t.const("fmt",(0,nt._)`${p}[${c.schemaCode}]`);e.fail$data((0,nt.or)((0,nt._)`typeof ${m} != "object"`,(0,nt._)`${m} instanceof RegExp`,(0,nt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=t.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,nt._)`${i.code.formats}${(0,nt.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,nt._)`${p}.compare(${r}, ${n}) ${Ts[o].fail} 0`}},dependencies:["format"]};var gz=e=>(e.addKeyword(Fr.formatLimitDefinition),e);Fr.default=gz});var Pg=T((Gn,zg)=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});var Vr=Sg(),_z=$g(),lu=M(),xg=new lu.Name("fullFormats"),yz=new lu.Name("fastFormats"),du=(e,t={keywords:!0})=>{if(Array.isArray(t))return kg(e,t,Vr.fullFormats,xg),e;let[r,n]=t.mode==="fast"?[Vr.fastFormats,yz]:[Vr.fullFormats,xg],o=t.formats||Vr.formatNames;return kg(e,o,r,n),t.keywords&&(0,_z.default)(e),e};du.get=(e,t="full")=>{let n=(t==="fast"?Vr.fastFormats:Vr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function kg(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,lu._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}zg.exports=Gn=du;Object.defineProperty(Gn,"__esModule",{value:!0});Gn.default=du});import{spawn as B_,spawnSync as Qr}from"node:child_process";import{connect as GP}from"node:net";import{homedir as K_,userInfo as Fu}from"node:os";import{resolve as J_,join as bt,dirname as Gu}from"node:path";import{fileURLToPath as WP,pathToFileURL as YP}from"node:url";import{createInterface as Fs}from"node:readline/promises";import*as q from"node:fs";var Ws=Object.freeze({status:"aborted"});function _(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var dy=Symbol("zod_brand"),dt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vo={};function Ue(e){return e&&Object.assign(vo,e),vo}var J={};Gs(J,{BIGINT_FORMAT_RANGES:()=>tl,Class:()=>Xs,NUMBER_FORMAT_RANGES:()=>ii,aborted:()=>Ft,allowsEval:()=>ni,assert:()=>gy,assertEqual:()=>py,assertIs:()=>my,assertNever:()=>hy,assertNotEqual:()=>fy,assignProp:()=>ri,cached:()=>nn,captureStackTrace:()=>bo,cleanEnum:()=>Ry,cleanRegex:()=>sn,clone:()=>Ge,createTransparentProxy:()=>Sy,defineLazy:()=>te,esc:()=>Lt,escapeRegex:()=>xt,extend:()=>ky,finalizeIssue:()=>We,floatSafeRemainder:()=>ti,getElementAtPath:()=>_y,getEnumValues:()=>Qs,getLengthableOrigin:()=>an,getParsedType:()=>by,getSizableOrigin:()=>rl,isObject:()=>mr,isPlainObject:()=>hr,issue:()=>ai,joinValues:()=>wo,jsonStringifyReplacer:()=>ei,merge:()=>zy,normalizeParams:()=>I,nullish:()=>on,numKeys:()=>wy,omit:()=>xy,optionalKeys:()=>si,partial:()=>Py,pick:()=>$y,prefixIssues:()=>ot,primitiveTypes:()=>el,promiseAllObject:()=>yy,propertyKeyTypes:()=>oi,randomString:()=>vy,required:()=>Ty,stringifyPrimitive:()=>So,unwrapMessage:()=>rn});function py(e){return e}function fy(e){return e}function my(e){}function hy(e){throw new Error}function gy(e){}function Qs(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function wo(e,t="|"){return e.map(r=>So(r)).join(t)}function ei(e,t){return typeof t=="bigint"?t.toString():t}function nn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function on(e){return e==null}function sn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ti(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function te(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ri(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _y(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function yy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function vy(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Lt(e){return JSON.stringify(e)}var bo=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ni=nn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function hr(e){if(mr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(mr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wy(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var by=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},oi=new Set(["string","number","symbol"]),el=new Set(["string","number","bigint","boolean","symbol","undefined"]);function xt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function I(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Sy(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function So(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function si(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ii={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $y(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function xy(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function ky(e,t){if(!hr(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return ri(this,"shape",n),n},checks:[]};return Ge(e,r)}function zy(e,t){return Ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ri(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Py(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return Ge(t,{...t._zod.def,shape:o,checks:[]})}function Ty(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return Ge(t,{...t._zod.def,shape:o,checks:[]})}function Ft(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ot(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function rn(e){return typeof e=="string"?e:e?.message}function We(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=rn(e.inst?._zod.def?.error?.(e))??rn(t?.error?.(e))??rn(r.customError?.(e))??rn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function rl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function an(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ai(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Ry(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Xs=class{constructor(...t){}};var nl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,ei,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$o=_("$ZodError",nl),ci=_("$ZodError",nl,{Parent:Error});function ui(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function li(e,t){let r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(e),n}var ol=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new dt;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>We(c,s,Ue())));throw bo(a,o?.callee),a}return i.value};var sl=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>We(c,s,Ue())));throw bo(a,o?.callee),a}return i.value};var di=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new dt;return s.issues.length?{success:!1,error:new(e??$o)(s.issues.map(i=>We(i,o,Ue())))}:{success:!0,data:s.value}},cn=di(ci),pi=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>We(i,o,Ue())))}:{success:!0,data:s.value}},xo=pi(ci);var il=/^[cC][^\s-]{8,}$/,al=/^[0-9a-z]+$/,cl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ul=/^[0-9a-vA-V]{20}$/,ll=/^[A-Za-z0-9]{27}$/,dl=/^[a-zA-Z0-9_-]{21}$/,pl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var fl=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var ml=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Iy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hl(){return new RegExp(Iy,"u")}var gl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_l=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,yl=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,vl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mi=/^[A-Za-z0-9_-]*$/,bl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Sl=/^\+(?:[0-9]){6,14}[0-9]$/,$l="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",xl=new RegExp(`^${$l}$`);function kl(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function zl(e){return new RegExp(`^${kl(e)}$`)}function Pl(e){let t=kl({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${$l}T(?:${n})$`)}var Tl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Rl=/^\d+n?$/,El=/^\d+$/,Il=/^-?\d+(?:\.\d+)?/i,Ol=/true|false/i,Al=/null/i;var Cl=/^[^A-Z]*$/,Nl=/^[^a-z]*$/;var xe=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),jl={number:"number",bigint:"bigint",object:"date"},hi=_("$ZodCheckLessThan",(e,t)=>{xe.init(e,t);let r=jl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gi=_("$ZodCheckGreaterThan",(e,t)=>{xe.init(e,t);let r=jl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ml=_("$ZodCheckMultipleOf",(e,t)=>{xe.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ti(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Dl=_("$ZodCheckNumberFormat",(e,t)=>{xe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=ii[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=El)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var Ul=_("$ZodCheckMaxLength",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=an(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ql=_("$ZodCheckMinLength",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=an(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Zl=_("$ZodCheckLengthEquals",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=an(o),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),un=_("$ZodCheckStringFormat",(e,t)=>{var r,n;xe.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Ll=_("$ZodCheckRegex",(e,t)=>{un.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Fl=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Cl),un.init(e,t)}),Vl=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Nl),un.init(e,t)}),Hl=_("$ZodCheckIncludes",(e,t)=>{xe.init(e,t);let r=xt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Bl=_("$ZodCheckStartsWith",(e,t)=>{xe.init(e,t);let r=new RegExp(`^${xt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Kl=_("$ZodCheckEndsWith",(e,t)=>{xe.init(e,t);let r=new RegExp(`.*${xt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Jl=_("$ZodCheckOverwrite",(e,t)=>{xe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var zo=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
11
|
-
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
|
|
12
|
-
`))}};var Wl={major:4,minor:0,patch:0};var W=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Wl;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,i,a)=>{let c=Ft(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new dt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Ft(s,d)))});else{if(s.issues.length===d)continue;c||(c=Ft(s,d))}}return u?u.then(()=>s):s};e._zod.run=(s,i)=>{let a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new dt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=cn(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return xo(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),To=_("$ZodString",(e,t)=>{W.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Tl(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),oe=_("$ZodStringFormat",(e,t)=>{un.init(e,t),To.init(e,t)}),id=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fl),oe.init(e,t)}),ad=_("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=fi(n))}else t.pattern??(t.pattern=fi());oe.init(e,t)}),cd=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ml),oe.init(e,t)}),ud=_("$ZodURL",(e,t)=>{oe.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:bl.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ld=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hl()),oe.init(e,t)}),dd=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=dl),oe.init(e,t)}),pd=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=il),oe.init(e,t)}),fd=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=al),oe.init(e,t)}),md=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cl),oe.init(e,t)}),hd=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ul),oe.init(e,t)}),gd=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ll),oe.init(e,t)}),_d=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Pl(t)),oe.init(e,t)}),yd=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=xl),oe.init(e,t)}),vd=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=zl(t)),oe.init(e,t)}),wd=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=pl),oe.init(e,t)}),bd=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gl),oe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Sd=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_l),oe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),$d=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=yl),oe.init(e,t)}),xd=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=vl),oe.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function kd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var zd=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=wl),oe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{kd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Oy(e){if(!mi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return kd(r)}var Pd=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mi),oe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Oy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Td=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Sl),oe.init(e,t)});function Ay(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Rd=_("$ZodJWT",(e,t)=>{oe.init(e,t),e._zod.check=r=>{Ay(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var yi=_("$ZodNumber",(e,t)=>{W.init(e,t),e._zod.pattern=e._zod.bag.pattern??Il,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Ed=_("$ZodNumber",(e,t)=>{Dl.init(e,t),yi.init(e,t)}),Id=_("$ZodBoolean",(e,t)=>{W.init(e,t),e._zod.pattern=Ol,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Od=_("$ZodBigInt",(e,t)=>{W.init(e,t),e._zod.pattern=Rl,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var Ad=_("$ZodNull",(e,t)=>{W.init(e,t),e._zod.pattern=Al,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),Cd=_("$ZodAny",(e,t)=>{W.init(e,t),e._zod.parse=r=>r}),Nd=_("$ZodUnknown",(e,t)=>{W.init(e,t),e._zod.parse=r=>r}),jd=_("$ZodNever",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var Md=_("$ZodDate",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),r}});function Yl(e,t,r){e.issues.length&&t.issues.push(...ot(r,e.issues)),t.value[r]=e.value}var Dd=_("$ZodArray",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Yl(u,r,i))):Yl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Po(e,t,r){e.issues.length&&t.issues.push(...ot(r,e.issues)),t.value[r]=e.value}function Xl(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...ot(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Ud=_("$ZodObject",(e,t)=>{W.init(e,t);let r=nn(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof W))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=si(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});te(e._zod,"propValues",()=>{let d=t.shape,p={};for(let m in d){let h=d[m]._zod;if(h.values){p[m]??(p[m]=new Set);for(let g of h.values)p[m].add(g)}}return p});let n=d=>{let p=new zo(["shape","payload","ctx"]),m=r.value,h=$=>{let S=Lt($);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let $ of m.keys)g[$]=`key_${y++}`;p.write("const newResult = {}");for(let $ of m.keys)if(m.optionalKeys.has($)){let S=g[$];p.write(`const ${S} = ${h($)};`);let P=Lt($);p.write(`
|
|
13
|
-
if (${S}.issues.length) {
|
|
14
|
-
if (input[${P}] === undefined) {
|
|
15
|
-
if (${P} in input) {
|
|
16
|
-
newResult[${P}] = undefined;
|
|
17
|
-
}
|
|
18
|
-
} else {
|
|
19
|
-
payload.issues = payload.issues.concat(
|
|
20
|
-
${S}.issues.map((iss) => ({
|
|
21
|
-
...iss,
|
|
22
|
-
path: iss.path ? [${P}, ...iss.path] : [${P}],
|
|
23
|
-
}))
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
} else if (${S}.value === undefined) {
|
|
27
|
-
if (${P} in input) newResult[${P}] = undefined;
|
|
28
|
-
} else {
|
|
29
|
-
newResult[${P}] = ${S}.value;
|
|
30
|
-
}
|
|
31
|
-
`)}else{let S=g[$];p.write(`const ${S} = ${h($)};`),p.write(`
|
|
32
|
-
if (${S}.issues.length) payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
|
|
33
|
-
...iss,
|
|
34
|
-
path: iss.path ? [${Lt($)}, ...iss.path] : [${Lt($)}]
|
|
35
|
-
})));`),p.write(`newResult[${Lt($)}] = ${S}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return($,S)=>b(d,$,S)},o,s=mr,i=!vo.jitless,c=i&&ni.value,u=t.catchall,l;e._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;let h=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let S=l.shape;for(let P of l.keys){let v=S[P],x=v._zod.run({value:m[P],issues:[]},p),O=v._zod.optin==="optional"&&v._zod.optout==="optional";x instanceof Promise?h.push(x.then(G=>O?Xl(G,d,P,m):Po(G,d,P))):O?Xl(x,d,P,m):Po(x,d,P)}}if(!u)return h.length?Promise.all(h).then(()=>d):d;let g=[],y=l.keySet,b=u._zod,$=b.def.type;for(let S of Object.keys(m)){if(y.has(S))continue;if($==="never"){g.push(S);continue}let P=b.run({value:m[S],issues:[]},p);P instanceof Promise?h.push(P.then(v=>Po(v,d,S))):Po(P,d,S)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function Ql(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>We(s,n,Ue())))}),t}var vi=_("$ZodUnion",(e,t)=>{W.init(e,t),te(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),te(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),te(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),te(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>sn(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of t.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Ql(i,r,e,n)):Ql(s,r,e,n)}}),qd=_("$ZodDiscriminatedUnion",(e,t)=>{vi.init(e,t);let r=e._zod.parse;te(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=nn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!mr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),Zd=_("$ZodIntersection",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ed(r,c,u)):ed(r,s,i)}});function _i(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(hr(e)&&hr(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=_i(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=_i(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ed(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ft(e))return e;let n=_i(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Ld=_("$ZodRecord",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!hr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[];if(t.keyType._zod.values){let i=t.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ot(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ot(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=t.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>We(u,n,Ue())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ot(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ot(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Fd=_("$ZodEnum",(e,t)=>{W.init(e,t);let r=Qs(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>oi.has(typeof n)).map(n=>typeof n=="string"?xt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Vd=_("$ZodLiteral",(e,t)=>{W.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?xt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Hd=_("$ZodTransform",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new dt;return r.value=o,r}}),Bd=_("$ZodOptional",(e,t)=>{W.init(e,t),e._zod.optin="optional",e._zod.optout="optional",te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),te(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${sn(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Kd=_("$ZodNullable",(e,t)=>{W.init(e,t),te(e._zod,"optin",()=>t.innerType._zod.optin),te(e._zod,"optout",()=>t.innerType._zod.optout),te(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${sn(r.source)}|null)$`):void 0}),te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Jd=_("$ZodDefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>td(s,t)):td(o,t)}});function td(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Gd=_("$ZodPrefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Wd=_("$ZodNonOptional",(e,t)=>{W.init(e,t),te(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rd(s,e)):rd(o,e)}});function rd(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Yd=_("$ZodCatch",(e,t)=>{W.init(e,t),e._zod.optin="optional",te(e._zod,"optout",()=>t.innerType._zod.optout),te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>We(i,n,Ue()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>We(s,n,Ue()))},input:r.value}),r.issues=[]),r)}});var Xd=_("$ZodPipe",(e,t)=>{W.init(e,t),te(e._zod,"values",()=>t.in._zod.values),te(e._zod,"optin",()=>t.in._zod.optin),te(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>nd(s,t,n)):nd(o,t,n)}});function nd(e,t,r){return Ft(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Qd=_("$ZodReadonly",(e,t)=>{W.init(e,t),te(e._zod,"propValues",()=>t.innerType._zod.propValues),te(e._zod,"values",()=>t.innerType._zod.values),te(e._zod,"optin",()=>t.innerType._zod.optin),te(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(od):od(o)}});function od(e){return e.value=Object.freeze(e.value),e}var ep=_("$ZodCustom",(e,t)=>{xe.init(e,t),W.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>sd(s,r,n,e));sd(o,r,n,e)}});function sd(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(ai(o))}}var Cy=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Ny=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Cy(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${So(n.values[0])}`:`Invalid option: expected one of ${wo(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${wo(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function tp(){return{localeError:Ny()}}var jy=Symbol("ZodOutput"),My=Symbol("ZodInput"),wi=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function rp(){return new wi}var gr=rp();function np(e,t){return new e({type:"string",...I(t)})}function op(e,t){return new e({type:"string",coerce:!0,...I(t)})}function sp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...I(t)})}function bi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...I(t)})}function ip(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...I(t)})}function ap(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(t)})}function cp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(t)})}function up(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(t)})}function Si(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...I(t)})}function lp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...I(t)})}function dp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(t)})}function pp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...I(t)})}function fp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(t)})}function mp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...I(t)})}function hp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...I(t)})}function gp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(t)})}function _p(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(t)})}function yp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(t)})}function vp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(t)})}function wp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(t)})}function bp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...I(t)})}function Sp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...I(t)})}function $p(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...I(t)})}function xp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...I(t)})}function kp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(t)})}function zp(e,t){return new e({type:"string",format:"date",check:"string_format",...I(t)})}function Pp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...I(t)})}function Tp(e,t){return new e({type:"string",format:"duration",check:"string_format",...I(t)})}function Rp(e,t){return new e({type:"number",checks:[],...I(t)})}function Ep(e,t){return new e({type:"number",coerce:!0,checks:[],...I(t)})}function Ip(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...I(t)})}function Op(e,t){return new e({type:"boolean",...I(t)})}function Ap(e,t){return new e({type:"boolean",coerce:!0,...I(t)})}function Cp(e,t){return new e({type:"bigint",coerce:!0,...I(t)})}function Np(e,t){return new e({type:"null",...I(t)})}function jp(e){return new e({type:"any"})}function Mp(e){return new e({type:"unknown"})}function Dp(e,t){return new e({type:"never",...I(t)})}function Up(e,t){return new e({type:"date",coerce:!0,...I(t)})}function _r(e,t){return new hi({check:"less_than",...I(t),value:e,inclusive:!1})}function pt(e,t){return new hi({check:"less_than",...I(t),value:e,inclusive:!0})}function yr(e,t){return new gi({check:"greater_than",...I(t),value:e,inclusive:!1})}function Ye(e,t){return new gi({check:"greater_than",...I(t),value:e,inclusive:!0})}function ln(e,t){return new Ml({check:"multiple_of",...I(t),value:e})}function Ro(e,t){return new Ul({check:"max_length",...I(t),maximum:e})}function vr(e,t){return new ql({check:"min_length",...I(t),minimum:e})}function Eo(e,t){return new Zl({check:"length_equals",...I(t),length:e})}function $i(e,t){return new Ll({check:"string_format",format:"regex",...I(t),pattern:e})}function xi(e){return new Fl({check:"string_format",format:"lowercase",...I(e)})}function ki(e){return new Vl({check:"string_format",format:"uppercase",...I(e)})}function zi(e,t){return new Hl({check:"string_format",format:"includes",...I(t),includes:e})}function Pi(e,t){return new Bl({check:"string_format",format:"starts_with",...I(t),prefix:e})}function Ti(e,t){return new Kl({check:"string_format",format:"ends_with",...I(t),suffix:e})}function Vt(e){return new Jl({check:"overwrite",tx:e})}function Ri(e){return Vt(t=>t.normalize(e))}function Ei(){return Vt(e=>e.trim())}function Ii(){return Vt(e=>e.toLowerCase())}function Oi(){return Vt(e=>e.toUpperCase())}function qp(e,t,r){return new e({type:"array",element:t,...I(r)})}function Zp(e,t,r){let n=I(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Lp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...I(r)})}function br(e){return!!e._zod}function Xe(e,t){return br(e)?cn(e,t):e.safeParse(t)}function Io(e){if(!e)return;let t;if(br(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Fp(e){if(br(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var dn={};Gs(dn,{ZodISODate:()=>Hp,ZodISODateTime:()=>Vp,ZodISODuration:()=>Kp,ZodISOTime:()=>Bp,date:()=>Ci,datetime:()=>Ai,duration:()=>ji,time:()=>Ni});var Vp=_("ZodISODateTime",(e,t)=>{_d.init(e,t),ue.init(e,t)});function Ai(e){return kp(Vp,e)}var Hp=_("ZodISODate",(e,t)=>{yd.init(e,t),ue.init(e,t)});function Ci(e){return zp(Hp,e)}var Bp=_("ZodISOTime",(e,t)=>{vd.init(e,t),ue.init(e,t)});function Ni(e){return Pp(Bp,e)}var Kp=_("ZodISODuration",(e,t)=>{wd.init(e,t),ue.init(e,t)});function ji(e){return Tp(Kp,e)}var Gp=(e,t)=>{$o.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>li(e,r)},flatten:{value:r=>ui(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},yR=_("ZodError",Gp),pn=_("ZodError",Gp,{Parent:Error});var Wp=ol(pn),Yp=sl(pn),Xp=di(pn),Qp=pi(pn);var re=_("ZodType",(e,t)=>(W.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Ge(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Wp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Xp(e,r,n),e.parseAsync=async(r,n)=>Yp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Qp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Iv(r,n)),e.superRefine=r=>e.check(Ov(r)),e.overwrite=r=>e.check(Vt(r)),e.optional=()=>de(e),e.nullable=()=>rf(e),e.nullish=()=>de(rf(e)),e.nonoptional=r=>xv(e,r),e.array=()=>k(e),e.or=r=>se([e,r]),e.and=r=>Co(e,r),e.transform=r=>Di(e,ff(r)),e.default=r=>bv(e,r),e.prefault=r=>$v(e,r),e.catch=r=>zv(e,r),e.pipe=r=>Di(e,r),e.readonly=()=>Rv(e),e.describe=r=>{let n=e.clone();return gr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return gr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return gr.get(e);let n=e.clone();return gr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),nf=_("_ZodString",(e,t)=>{To.init(e,t),re.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check($i(...n)),e.includes=(...n)=>e.check(zi(...n)),e.startsWith=(...n)=>e.check(Pi(...n)),e.endsWith=(...n)=>e.check(Ti(...n)),e.min=(...n)=>e.check(vr(...n)),e.max=(...n)=>e.check(Ro(...n)),e.length=(...n)=>e.check(Eo(...n)),e.nonempty=(...n)=>e.check(vr(1,...n)),e.lowercase=n=>e.check(xi(n)),e.uppercase=n=>e.check(ki(n)),e.trim=()=>e.check(Ei()),e.normalize=(...n)=>e.check(Ri(...n)),e.toLowerCase=()=>e.check(Ii()),e.toUpperCase=()=>e.check(Oi())}),Ui=_("ZodString",(e,t)=>{To.init(e,t),nf.init(e,t),e.email=r=>e.check(sp(Hy,r)),e.url=r=>e.check(Si(of,r)),e.jwt=r=>e.check(xp(iv,r)),e.emoji=r=>e.check(lp(By,r)),e.guid=r=>e.check(bi(ef,r)),e.uuid=r=>e.check(ip(Oo,r)),e.uuidv4=r=>e.check(ap(Oo,r)),e.uuidv6=r=>e.check(cp(Oo,r)),e.uuidv7=r=>e.check(up(Oo,r)),e.nanoid=r=>e.check(dp(Ky,r)),e.guid=r=>e.check(bi(ef,r)),e.cuid=r=>e.check(pp(Jy,r)),e.cuid2=r=>e.check(fp(Gy,r)),e.ulid=r=>e.check(mp(Wy,r)),e.base64=r=>e.check(bp(nv,r)),e.base64url=r=>e.check(Sp(ov,r)),e.xid=r=>e.check(hp(Yy,r)),e.ksuid=r=>e.check(gp(Xy,r)),e.ipv4=r=>e.check(_p(Qy,r)),e.ipv6=r=>e.check(yp(ev,r)),e.cidrv4=r=>e.check(vp(tv,r)),e.cidrv6=r=>e.check(wp(rv,r)),e.e164=r=>e.check($p(sv,r)),e.datetime=r=>e.check(Ai(r)),e.date=r=>e.check(Ci(r)),e.time=r=>e.check(Ni(r)),e.duration=r=>e.check(ji(r))});function f(e){return np(Ui,e)}var ue=_("ZodStringFormat",(e,t)=>{oe.init(e,t),nf.init(e,t)}),Hy=_("ZodEmail",(e,t)=>{cd.init(e,t),ue.init(e,t)});var ef=_("ZodGUID",(e,t)=>{id.init(e,t),ue.init(e,t)});var Oo=_("ZodUUID",(e,t)=>{ad.init(e,t),ue.init(e,t)});var of=_("ZodURL",(e,t)=>{ud.init(e,t),ue.init(e,t)});function sf(e){return Si(of,e)}var By=_("ZodEmoji",(e,t)=>{ld.init(e,t),ue.init(e,t)});var Ky=_("ZodNanoID",(e,t)=>{dd.init(e,t),ue.init(e,t)});var Jy=_("ZodCUID",(e,t)=>{pd.init(e,t),ue.init(e,t)});var Gy=_("ZodCUID2",(e,t)=>{fd.init(e,t),ue.init(e,t)});var Wy=_("ZodULID",(e,t)=>{md.init(e,t),ue.init(e,t)});var Yy=_("ZodXID",(e,t)=>{hd.init(e,t),ue.init(e,t)});var Xy=_("ZodKSUID",(e,t)=>{gd.init(e,t),ue.init(e,t)});var Qy=_("ZodIPv4",(e,t)=>{bd.init(e,t),ue.init(e,t)});var ev=_("ZodIPv6",(e,t)=>{Sd.init(e,t),ue.init(e,t)});var tv=_("ZodCIDRv4",(e,t)=>{$d.init(e,t),ue.init(e,t)});var rv=_("ZodCIDRv6",(e,t)=>{xd.init(e,t),ue.init(e,t)});var nv=_("ZodBase64",(e,t)=>{zd.init(e,t),ue.init(e,t)});var ov=_("ZodBase64URL",(e,t)=>{Pd.init(e,t),ue.init(e,t)});var sv=_("ZodE164",(e,t)=>{Td.init(e,t),ue.init(e,t)});var iv=_("ZodJWT",(e,t)=>{Rd.init(e,t),ue.init(e,t)});var Ao=_("ZodNumber",(e,t)=>{yi.init(e,t),re.init(e,t),e.gt=(n,o)=>e.check(yr(n,o)),e.gte=(n,o)=>e.check(Ye(n,o)),e.min=(n,o)=>e.check(Ye(n,o)),e.lt=(n,o)=>e.check(_r(n,o)),e.lte=(n,o)=>e.check(pt(n,o)),e.max=(n,o)=>e.check(pt(n,o)),e.int=n=>e.check(tf(n)),e.safe=n=>e.check(tf(n)),e.positive=n=>e.check(yr(0,n)),e.nonnegative=n=>e.check(Ye(0,n)),e.negative=n=>e.check(_r(0,n)),e.nonpositive=n=>e.check(pt(0,n)),e.multipleOf=(n,o)=>e.check(ln(n,o)),e.step=(n,o)=>e.check(ln(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function H(e){return Rp(Ao,e)}var av=_("ZodNumberFormat",(e,t)=>{Ed.init(e,t),Ao.init(e,t)});function tf(e){return Ip(av,e)}var qi=_("ZodBoolean",(e,t)=>{Id.init(e,t),re.init(e,t)});function X(e){return Op(qi,e)}var af=_("ZodBigInt",(e,t)=>{Od.init(e,t),re.init(e,t),e.gte=(n,o)=>e.check(Ye(n,o)),e.min=(n,o)=>e.check(Ye(n,o)),e.gt=(n,o)=>e.check(yr(n,o)),e.gte=(n,o)=>e.check(Ye(n,o)),e.min=(n,o)=>e.check(Ye(n,o)),e.lt=(n,o)=>e.check(_r(n,o)),e.lte=(n,o)=>e.check(pt(n,o)),e.max=(n,o)=>e.check(pt(n,o)),e.positive=n=>e.check(yr(BigInt(0),n)),e.negative=n=>e.check(_r(BigInt(0),n)),e.nonpositive=n=>e.check(pt(BigInt(0),n)),e.nonnegative=n=>e.check(Ye(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(ln(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var cv=_("ZodNull",(e,t)=>{Ad.init(e,t),re.init(e,t)});function cf(e){return Np(cv,e)}var uv=_("ZodAny",(e,t)=>{Cd.init(e,t),re.init(e,t)});function uf(){return jp(uv)}var lv=_("ZodUnknown",(e,t)=>{Nd.init(e,t),re.init(e,t)});function le(){return Mp(lv)}var dv=_("ZodNever",(e,t)=>{jd.init(e,t),re.init(e,t)});function pv(e){return Dp(dv,e)}var lf=_("ZodDate",(e,t)=>{Md.init(e,t),re.init(e,t),e.min=(n,o)=>e.check(Ye(n,o)),e.max=(n,o)=>e.check(pt(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var fv=_("ZodArray",(e,t)=>{Dd.init(e,t),re.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(vr(r,n)),e.nonempty=r=>e.check(vr(1,r)),e.max=(r,n)=>e.check(Ro(r,n)),e.length=(r,n)=>e.check(Eo(r,n)),e.unwrap=()=>e.element});function k(e,t){return qp(fv,e,t)}var df=_("ZodObject",(e,t)=>{Ud.init(e,t),re.init(e,t),J.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Ae(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:le()}),e.loose=()=>e.clone({...e._zod.def,catchall:le()}),e.strict=()=>e.clone({...e._zod.def,catchall:pv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>J.extend(e,r),e.merge=r=>J.merge(e,r),e.pick=r=>J.pick(e,r),e.omit=r=>J.omit(e,r),e.partial=(...r)=>J.partial(mf,e,r[0]),e.required=(...r)=>J.required(hf,e,r[0])});function z(e,t){let r={type:"object",get shape(){return J.assignProp(this,"shape",{...e}),this.shape},...J.normalizeParams(t)};return new df(r)}function me(e,t){return new df({type:"object",get shape(){return J.assignProp(this,"shape",{...e}),this.shape},catchall:le(),...J.normalizeParams(t)})}var pf=_("ZodUnion",(e,t)=>{vi.init(e,t),re.init(e,t),e.options=t.options});function se(e,t){return new pf({type:"union",options:e,...J.normalizeParams(t)})}var mv=_("ZodDiscriminatedUnion",(e,t)=>{pf.init(e,t),qd.init(e,t)});function Zi(e,t,r){return new mv({type:"union",options:t,discriminator:e,...J.normalizeParams(r)})}var hv=_("ZodIntersection",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Co(e,t){return new hv({type:"intersection",left:e,right:t})}var gv=_("ZodRecord",(e,t)=>{Ld.init(e,t),re.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ne(e,t,r){return new gv({type:"record",keyType:e,valueType:t,...J.normalizeParams(r)})}var Mi=_("ZodEnum",(e,t)=>{Fd.init(e,t),re.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Mi({...t,checks:[],...J.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Mi({...t,checks:[],...J.normalizeParams(o),entries:s})}});function Ae(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Mi({type:"enum",entries:r,...J.normalizeParams(t)})}var _v=_("ZodLiteral",(e,t)=>{Vd.init(e,t),re.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new _v({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var yv=_("ZodTransform",(e,t)=>{Hd.init(e,t),re.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(J.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(J.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function ff(e){return new yv({type:"transform",transform:e})}var mf=_("ZodOptional",(e,t)=>{Bd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function de(e){return new mf({type:"optional",innerType:e})}var vv=_("ZodNullable",(e,t)=>{Kd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rf(e){return new vv({type:"nullable",innerType:e})}var wv=_("ZodDefault",(e,t)=>{Jd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function bv(e,t){return new wv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Sv=_("ZodPrefault",(e,t)=>{Gd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $v(e,t){return new Sv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var hf=_("ZodNonOptional",(e,t)=>{Wd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function xv(e,t){return new hf({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var kv=_("ZodCatch",(e,t)=>{Yd.init(e,t),re.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function zv(e,t){return new kv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Pv=_("ZodPipe",(e,t)=>{Xd.init(e,t),re.init(e,t),e.in=t.in,e.out=t.out});function Di(e,t){return new Pv({type:"pipe",in:e,out:t})}var Tv=_("ZodReadonly",(e,t)=>{Qd.init(e,t),re.init(e,t)});function Rv(e){return new Tv({type:"readonly",innerType:e})}var gf=_("ZodCustom",(e,t)=>{ep.init(e,t),re.init(e,t)});function Ev(e){let t=new xe({check:"custom"});return t._zod.check=e,t}function _f(e,t){return Zp(gf,e??(()=>!0),t)}function Iv(e,t={}){return Lp(gf,e,t)}function Ov(e){let t=Ev(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(J.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(J.issue(o))}},e(r.value,r)));return t}function Li(e,t){return Di(ff(e),t)}var yf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var No={};Gs(No,{bigint:()=>jv,boolean:()=>Nv,date:()=>Mv,number:()=>Cv,string:()=>Av});function Av(e){return op(Ui,e)}function Cv(e){return Ep(Ao,e)}function Nv(e){return Ap(qi,e)}function jv(e){return Cp(af,e)}function Mv(e){return Up(lf,e)}Ue(tp());var $r="2025-11-25";var Vi=[$r,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],kt="io.modelcontextprotocol/related-task",Mo="2.0",he=_f(e=>e!==null&&(typeof e=="object"||typeof e=="function")),vf=se([f(),H().int()]),wf=f(),pE=me({ttl:H().optional(),pollInterval:H().optional()}),Uv=z({ttl:H().optional()}),qv=z({taskId:f()}),Hi=me({progressToken:vf.optional(),[kt]:qv.optional()}),qe=z({_meta:Hi.optional()}),fn=qe.extend({task:Uv.optional()}),bf=e=>fn.safeParse(e).success,_e=z({method:f(),params:qe.loose().optional()}),Fe=z({_meta:Hi.optional()}),Ve=z({method:f(),params:Fe.loose().optional()}),ye=me({_meta:Hi.optional()}),Do=se([f(),H().int()]),Sf=z({jsonrpc:R(Mo),id:Do,..._e.shape}).strict(),xr=e=>Sf.safeParse(e).success,$f=z({jsonrpc:R(Mo),...Ve.shape}).strict(),xf=e=>$f.safeParse(e).success,Bi=z({jsonrpc:R(Mo),id:Do,result:ye}).strict(),zt=e=>Bi.safeParse(e).success;var C;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var Ki=z({jsonrpc:R(Mo),id:Do.optional(),error:z({code:H().int(),message:f(),data:le().optional()})}).strict();var Ji=e=>Ki.safeParse(e).success;var Ht=se([Sf,$f,Bi,Ki]),fE=se([Bi,Ki]),Bt=ye.strict(),Zv=Fe.extend({requestId:Do.optional(),reason:f().optional()}),Uo=Ve.extend({method:R("notifications/cancelled"),params:Zv}),Lv=z({src:f(),mimeType:f().optional(),sizes:k(f()).optional(),theme:Ae(["light","dark"]).optional()}),mn=z({icons:k(Lv).optional()}),Sr=z({name:f(),title:f().optional()}),kf=Sr.extend({...Sr.shape,...mn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),Fv=Co(z({applyDefaults:X().optional()}),ne(f(),le())),Vv=Li(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Co(z({form:Fv.optional(),url:he.optional()}),ne(f(),le()).optional())),Hv=me({list:he.optional(),cancel:he.optional(),requests:me({sampling:me({createMessage:he.optional()}).optional(),elicitation:me({create:he.optional()}).optional()}).optional()}),Bv=me({list:he.optional(),cancel:he.optional(),requests:me({tools:me({call:he.optional()}).optional()}).optional()}),Kv=z({experimental:ne(f(),he).optional(),sampling:z({context:he.optional(),tools:he.optional()}).optional(),elicitation:Vv.optional(),roots:z({listChanged:X().optional()}).optional(),tasks:Hv.optional(),extensions:ne(f(),he).optional()}),Jv=qe.extend({protocolVersion:f(),capabilities:Kv,clientInfo:kf}),Gv=_e.extend({method:R("initialize"),params:Jv});var Wv=z({experimental:ne(f(),he).optional(),logging:he.optional(),completions:he.optional(),prompts:z({listChanged:X().optional()}).optional(),resources:z({subscribe:X().optional(),listChanged:X().optional()}).optional(),tools:z({listChanged:X().optional()}).optional(),tasks:Bv.optional(),extensions:ne(f(),he).optional()}),Gi=ye.extend({protocolVersion:f(),capabilities:Wv,serverInfo:kf,instructions:f().optional()}),zf=Ve.extend({method:R("notifications/initialized"),params:Fe.optional()}),Pf=e=>zf.safeParse(e).success,qo=_e.extend({method:R("ping"),params:qe.optional()}),Yv=z({progress:H(),total:de(H()),message:de(f())}),Xv=z({...Fe.shape,...Yv.shape,progressToken:vf}),Zo=Ve.extend({method:R("notifications/progress"),params:Xv}),Qv=qe.extend({cursor:wf.optional()}),hn=_e.extend({params:Qv.optional()}),gn=ye.extend({nextCursor:wf.optional()}),ew=Ae(["working","input_required","completed","failed","cancelled"]),_n=z({taskId:f(),status:ew,ttl:se([H(),cf()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:de(H()),statusMessage:de(f())}),Kt=ye.extend({task:_n}),tw=Fe.merge(_n),yn=Ve.extend({method:R("notifications/tasks/status"),params:tw}),Lo=_e.extend({method:R("tasks/get"),params:qe.extend({taskId:f()})}),Fo=ye.merge(_n),Vo=_e.extend({method:R("tasks/result"),params:qe.extend({taskId:f()})}),mE=ye.loose(),Ho=hn.extend({method:R("tasks/list")}),Bo=gn.extend({tasks:k(_n)}),Ko=_e.extend({method:R("tasks/cancel"),params:qe.extend({taskId:f()})}),Tf=ye.merge(_n),Rf=z({uri:f(),mimeType:de(f()),_meta:ne(f(),le()).optional()}),Ef=Rf.extend({text:f()}),Wi=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),If=Rf.extend({blob:Wi}),vn=Ae(["user","assistant"]),kr=z({audience:k(vn).optional(),priority:H().min(0).max(1).optional(),lastModified:dn.datetime({offset:!0}).optional()}),Of=z({...Sr.shape,...mn.shape,uri:f(),description:de(f()),mimeType:de(f()),size:de(H()),annotations:kr.optional(),_meta:de(me({}))}),rw=z({...Sr.shape,...mn.shape,uriTemplate:f(),description:de(f()),mimeType:de(f()),annotations:kr.optional(),_meta:de(me({}))}),nw=hn.extend({method:R("resources/list")}),Yi=gn.extend({resources:k(Of)}),ow=hn.extend({method:R("resources/templates/list")}),Xi=gn.extend({resourceTemplates:k(rw)}),Qi=qe.extend({uri:f()}),sw=Qi,iw=_e.extend({method:R("resources/read"),params:sw}),ea=ye.extend({contents:k(se([Ef,If]))}),ta=Ve.extend({method:R("notifications/resources/list_changed"),params:Fe.optional()}),aw=Qi,cw=_e.extend({method:R("resources/subscribe"),params:aw}),uw=Qi,lw=_e.extend({method:R("resources/unsubscribe"),params:uw}),dw=Fe.extend({uri:f()}),pw=Ve.extend({method:R("notifications/resources/updated"),params:dw}),fw=z({name:f(),description:de(f()),required:de(X())}),mw=z({...Sr.shape,...mn.shape,description:de(f()),arguments:de(k(fw)),_meta:de(me({}))}),hw=hn.extend({method:R("prompts/list")}),ra=gn.extend({prompts:k(mw)}),gw=qe.extend({name:f(),arguments:ne(f(),f()).optional()}),_w=_e.extend({method:R("prompts/get"),params:gw}),na=z({type:R("text"),text:f(),annotations:kr.optional(),_meta:ne(f(),le()).optional()}),oa=z({type:R("image"),data:Wi,mimeType:f(),annotations:kr.optional(),_meta:ne(f(),le()).optional()}),sa=z({type:R("audio"),data:Wi,mimeType:f(),annotations:kr.optional(),_meta:ne(f(),le()).optional()}),yw=z({type:R("tool_use"),name:f(),id:f(),input:ne(f(),le()),_meta:ne(f(),le()).optional()}),vw=z({type:R("resource"),resource:se([Ef,If]),annotations:kr.optional(),_meta:ne(f(),le()).optional()}),ww=Of.extend({type:R("resource_link")}),ia=se([na,oa,sa,ww,vw]),bw=z({role:vn,content:ia}),aa=ye.extend({description:f().optional(),messages:k(bw)}),ca=Ve.extend({method:R("notifications/prompts/list_changed"),params:Fe.optional()}),Sw=z({title:f().optional(),readOnlyHint:X().optional(),destructiveHint:X().optional(),idempotentHint:X().optional(),openWorldHint:X().optional()}),$w=z({taskSupport:Ae(["required","optional","forbidden"]).optional()}),Af=z({...Sr.shape,...mn.shape,description:f().optional(),inputSchema:z({type:R("object"),properties:ne(f(),he).optional(),required:k(f()).optional()}).catchall(le()),outputSchema:z({type:R("object"),properties:ne(f(),he).optional(),required:k(f()).optional()}).catchall(le()).optional(),annotations:Sw.optional(),execution:$w.optional(),_meta:ne(f(),le()).optional()}),xw=hn.extend({method:R("tools/list")}),ua=gn.extend({tools:k(Af)}),zr=ye.extend({content:k(ia).default([]),structuredContent:ne(f(),le()).optional(),isError:X().optional()}),hE=zr.or(ye.extend({toolResult:le()})),kw=fn.extend({name:f(),arguments:ne(f(),le()).optional()}),zw=_e.extend({method:R("tools/call"),params:kw}),la=Ve.extend({method:R("notifications/tools/list_changed"),params:Fe.optional()}),Cf=z({autoRefresh:X().default(!0),debounceMs:H().int().nonnegative().default(300)}),Nf=Ae(["debug","info","notice","warning","error","critical","alert","emergency"]),Pw=qe.extend({level:Nf}),Tw=_e.extend({method:R("logging/setLevel"),params:Pw}),Rw=Fe.extend({level:Nf,logger:f().optional(),data:le()}),Ew=Ve.extend({method:R("notifications/message"),params:Rw}),Iw=z({name:f().optional()}),Ow=z({hints:k(Iw).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Aw=z({mode:Ae(["auto","required","none"]).optional()}),Cw=z({type:R("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:k(ia).default([]),structuredContent:z({}).loose().optional(),isError:X().optional(),_meta:ne(f(),le()).optional()}),Nw=Zi("type",[na,oa,sa]),jo=Zi("type",[na,oa,sa,yw,Cw]),jw=z({role:vn,content:se([jo,k(jo)]),_meta:ne(f(),le()).optional()}),Mw=fn.extend({messages:k(jw),modelPreferences:Ow.optional(),systemPrompt:f().optional(),includeContext:Ae(["none","thisServer","allServers"]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:k(f()).optional(),metadata:he.optional(),tools:k(Af).optional(),toolChoice:Aw.optional()}),da=_e.extend({method:R("sampling/createMessage"),params:Mw}),pa=ye.extend({model:f(),stopReason:de(Ae(["endTurn","stopSequence","maxTokens"]).or(f())),role:vn,content:Nw}),fa=ye.extend({model:f(),stopReason:de(Ae(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:vn,content:se([jo,k(jo)])}),Dw=z({type:R("boolean"),title:f().optional(),description:f().optional(),default:X().optional()}),Uw=z({type:R("string"),title:f().optional(),description:f().optional(),minLength:H().optional(),maxLength:H().optional(),format:Ae(["email","uri","date","date-time"]).optional(),default:f().optional()}),qw=z({type:Ae(["number","integer"]),title:f().optional(),description:f().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),Zw=z({type:R("string"),title:f().optional(),description:f().optional(),enum:k(f()),default:f().optional()}),Lw=z({type:R("string"),title:f().optional(),description:f().optional(),oneOf:k(z({const:f(),title:f()})),default:f().optional()}),Fw=z({type:R("string"),title:f().optional(),description:f().optional(),enum:k(f()),enumNames:k(f()).optional(),default:f().optional()}),Vw=se([Zw,Lw]),Hw=z({type:R("array"),title:f().optional(),description:f().optional(),minItems:H().optional(),maxItems:H().optional(),items:z({type:R("string"),enum:k(f())}),default:k(f()).optional()}),Bw=z({type:R("array"),title:f().optional(),description:f().optional(),minItems:H().optional(),maxItems:H().optional(),items:z({anyOf:k(z({const:f(),title:f()}))}),default:k(f()).optional()}),Kw=se([Hw,Bw]),Jw=se([Fw,Vw,Kw]),Gw=se([Jw,Dw,Uw,qw]),Ww=fn.extend({mode:R("form").optional(),message:f(),requestedSchema:z({type:R("object"),properties:ne(f(),Gw),required:k(f()).optional()})}),Yw=fn.extend({mode:R("url"),message:f(),elicitationId:f(),url:f().url()}),Xw=se([Ww,Yw]),ma=_e.extend({method:R("elicitation/create"),params:Xw}),Qw=Fe.extend({elicitationId:f()}),eb=Ve.extend({method:R("notifications/elicitation/complete"),params:Qw}),ha=ye.extend({action:Ae(["accept","decline","cancel"]),content:Li(e=>e===null?void 0:e,ne(f(),se([f(),H(),X(),k(f())])).optional())}),tb=z({type:R("ref/resource"),uri:f()});var rb=z({type:R("ref/prompt"),name:f()}),nb=qe.extend({ref:se([rb,tb]),argument:z({name:f(),value:f()}),context:z({arguments:ne(f(),f()).optional()}).optional()}),ob=_e.extend({method:R("completion/complete"),params:nb});var ga=ye.extend({completion:me({values:k(f()).max(100),total:de(H().int()),hasMore:de(X())})}),sb=z({uri:f().startsWith("file://"),name:f().optional(),_meta:ne(f(),le()).optional()}),ib=_e.extend({method:R("roots/list"),params:qe.optional()}),ab=ye.extend({roots:k(sb)}),cb=Ve.extend({method:R("notifications/roots/list_changed"),params:Fe.optional()}),gE=se([qo,Gv,ob,Tw,_w,hw,nw,ow,iw,cw,lw,zw,xw,Lo,Vo,Ho,Ko]),_E=se([Uo,Zo,zf,cb,yn]),yE=se([Bt,pa,fa,ha,ab,Fo,Bo,Kt]),vE=se([qo,da,ma,ib,Lo,Vo,Ho,Ko]),wE=se([Uo,Zo,Ew,pw,ta,la,ca,yn,eb]),bE=se([Bt,Gi,ga,aa,ra,Yi,Xi,ea,zr,ua,Fo,Bo,Kt]),A=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===C.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Fi(o.elicitations,r)}return new e(t,r,n)}},Fi=class extends A{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Pt(e){return e==="completed"||e==="failed"||e==="cancelled"}var ub=Symbol("Let zodToJsonSchema decide on which parser to use");var eI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _a(e){let r=Io(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ya(e,t){let r=Xe(e,t);if(!r.success)throw r.error;return r.data}var hb=6e4,Jo=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Uo,r=>{this._oncancel(r)}),this.setNotificationHandler(Zo,r=>{this._onprogress(r)}),this.setRequestHandler(qo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Lo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new A(C.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Vo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new A(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new A(C.InvalidParams,`Task not found: ${s}`);if(!Pt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Pt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[kt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ho,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new A(C.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ko,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new A(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(Pt(o.status))throw new A(C.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new A(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof A?o:new A(C.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),A.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),zt(s)||Ji(s)?this._onresponse(s):xr(s)?this._onrequest(s,i):xf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=A.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[kt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:C.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let a=bf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new A(C.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:t.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:C.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===i&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),zt(t))n(t);else{let i=new A(t.error.code,t.error.message,t.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(zt(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),zt(t))o(t);else{let i=A.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof A?i:new A(C.InternalError,String(i))}}return}let s;try{let i=await this.request(t,Kt,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new A(C.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Pt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new A(C.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new A(C.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof A?i:new A(C.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch($){d($);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[kt]:c}});let h=$=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String($)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let S=$ instanceof A?$:new A(C.RequestTimeout,String($));l(S)};this._responseHandlers.set(p,$=>{if(!n?.signal?.aborted){if($ instanceof Error)return l($);try{let S=Xe(r,$.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??hb,y=()=>h(A.fromError(C.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let $=S=>{let P=this._responseHandlers.get(p);P?P(S):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,$),this._enqueueTaskMessage(b,{type:"request",message:m,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(p),l(S)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>{this._cleanupTimeout(p),l($)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Fo,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Bo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Tf,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[kt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[kt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[kt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=_a(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ya(t,o);return Promise.resolve(r(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=_a(t);this._notificationHandlers.set(n,o=>{let s=ya(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&xr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new A(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new A(C.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new A(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new A(C.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=yn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Pt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new A(C.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Pt(a.status))throw new A(C.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=yn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Pt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function jf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mf(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];jf(i)&&jf(s)?r[o]={...i,...s}:r[o]=s}return r}var Tg=Qu(ou(),1),Rg=Qu(Pg(),1);function vz(){let e=new Tg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Rg.default)(e),e}var Rs=class{constructor(t){this._ajv=t??vz()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Es=class{constructor(t){this._client=t}async*callToolStream(t,r=zr,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new A(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new A(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof A){yield{type:"error",error:l};return}yield{type:"error",error:new A(C.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Eg(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Ig(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Is(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Is(s,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Is(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Is(r,t)}}function wz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var Os=class extends Jo{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Rs,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",la,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ca,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ta,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Es(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Mf(this._capabilities,t)}setRequestHandler(t,r){let o=Io(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(br(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=Xe(ma,c);if(!l.success){let $=l.error instanceof Error?l.error.message:String(l.error);throw new A(C.InvalidParams,`Invalid elicitation request: ${$}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:m}=wz(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new A(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!m)throw new A(C.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let $=Xe(Kt,h);if(!$.success){let S=$.error instanceof Error?$.error.message:String($.error);throw new A(C.InvalidParams,`Invalid task creation result: ${S}`)}return $.data}let g=Xe(ha,h);if(!g.success){let $=g.error instanceof Error?g.error.message:String(g.error);throw new A(C.InvalidParams,`Invalid elicitation result: ${$}`)}let y=g.data,b=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&b&&this._capabilities.elicitation?.form?.applyDefaults)try{Is(b,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Xe(da,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new A(C.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let y=Xe(Kt,p);if(!y.success){let b=y.error instanceof Error?y.error.message:String(y.error);throw new A(C.InvalidParams,`Invalid task creation result: ${b}`)}return y.data}let h=d.tools||d.toolChoice?fa:pa,g=Xe(h,p);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new A(C.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:$r,capabilities:this._capabilities,clientInfo:this._clientInfo}},Gi,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Vi.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Eg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Ig(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Bt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},ga,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Bt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},aa,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},ra,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Yi,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Xi,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},ea,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Bt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Bt,r)}async callTool(t,r=zr,n){if(this.isToolTaskRequired(t.name))throw new A(C.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new A(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new A(C.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof A?i:new A(C.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},ua,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=Cf.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(t,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function As(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Og(e=fetch,t){return t?async(r,n)=>{let o={...t,...n,headers:n?.headers?{...As(t.headers),...As(n.headers)}:t.headers};return e(r,o)}:e}var pu;pu=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function bz(e){return(await pu).getRandomValues(new Uint8Array(e))}async function Sz(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await bz(e-n.length);for(let s of o)s<r&&(n+=t[s%t.length])}return n}async function $z(e){return await Sz(e)}async function xz(e){let t=await(await pu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function fu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await $z(e),r=await xz(t);return{code_verifier:t,code_challenge:r}}var Se=sf().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:yf.custom,message:"URL must be parseable",fatal:!0}),Ws}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Cg=me({resource:f().url(),authorization_servers:k(Se).optional(),jwks_uri:f().url().optional(),scopes_supported:k(f()).optional(),bearer_methods_supported:k(f()).optional(),resource_signing_alg_values_supported:k(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:X().optional(),authorization_details_types_supported:k(f()).optional(),dpop_signing_alg_values_supported:k(f()).optional(),dpop_bound_access_tokens_required:X().optional()}),mu=me({issuer:f(),authorization_endpoint:Se,token_endpoint:Se,registration_endpoint:Se.optional(),scopes_supported:k(f()).optional(),response_types_supported:k(f()),response_modes_supported:k(f()).optional(),grant_types_supported:k(f()).optional(),token_endpoint_auth_methods_supported:k(f()).optional(),token_endpoint_auth_signing_alg_values_supported:k(f()).optional(),service_documentation:Se.optional(),revocation_endpoint:Se.optional(),revocation_endpoint_auth_methods_supported:k(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:k(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:k(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:k(f()).optional(),code_challenge_methods_supported:k(f()).optional(),client_id_metadata_document_supported:X().optional()}),kz=me({issuer:f(),authorization_endpoint:Se,token_endpoint:Se,userinfo_endpoint:Se.optional(),jwks_uri:Se,registration_endpoint:Se.optional(),scopes_supported:k(f()).optional(),response_types_supported:k(f()),response_modes_supported:k(f()).optional(),grant_types_supported:k(f()).optional(),acr_values_supported:k(f()).optional(),subject_types_supported:k(f()),id_token_signing_alg_values_supported:k(f()),id_token_encryption_alg_values_supported:k(f()).optional(),id_token_encryption_enc_values_supported:k(f()).optional(),userinfo_signing_alg_values_supported:k(f()).optional(),userinfo_encryption_alg_values_supported:k(f()).optional(),userinfo_encryption_enc_values_supported:k(f()).optional(),request_object_signing_alg_values_supported:k(f()).optional(),request_object_encryption_alg_values_supported:k(f()).optional(),request_object_encryption_enc_values_supported:k(f()).optional(),token_endpoint_auth_methods_supported:k(f()).optional(),token_endpoint_auth_signing_alg_values_supported:k(f()).optional(),display_values_supported:k(f()).optional(),claim_types_supported:k(f()).optional(),claims_supported:k(f()).optional(),service_documentation:f().optional(),claims_locales_supported:k(f()).optional(),ui_locales_supported:k(f()).optional(),claims_parameter_supported:X().optional(),request_parameter_supported:X().optional(),request_uri_parameter_supported:X().optional(),require_request_uri_registration:X().optional(),op_policy_uri:Se.optional(),op_tos_uri:Se.optional(),client_id_metadata_document_supported:X().optional()}),Ng=z({...kz.shape,...mu.pick({code_challenge_methods_supported:!0}).shape}),jg=z({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:No.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Mg=z({error:f(),error_description:f().optional(),error_uri:f().optional()}),Ag=Se.optional().or(R("").transform(()=>{})),zz=z({redirect_uris:k(Se),token_endpoint_auth_method:f().optional(),grant_types:k(f()).optional(),response_types:k(f()).optional(),client_name:f().optional(),client_uri:Se.optional(),logo_uri:Ag,scope:f().optional(),contacts:k(f()).optional(),tos_uri:Ag,policy_uri:f().optional(),jwks_uri:Se.optional(),jwks:uf().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Pz=z({client_id:f(),client_secret:f().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional()}).strip(),Dg=zz.merge(Pz),zN=z({error:f(),error_description:f().optional()}).strip(),PN=z({token:f(),token_type_hint:f().optional()}).strip();function Ug(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function qg({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var fe=class extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Wn=class extends fe{};Wn.errorCode="invalid_request";var sr=class extends fe{};sr.errorCode="invalid_client";var ir=class extends fe{};ir.errorCode="invalid_grant";var ar=class extends fe{};ar.errorCode="unauthorized_client";var Yn=class extends fe{};Yn.errorCode="unsupported_grant_type";var Xn=class extends fe{};Xn.errorCode="invalid_scope";var Qn=class extends fe{};Qn.errorCode="access_denied";var yt=class extends fe{};yt.errorCode="server_error";var eo=class extends fe{};eo.errorCode="temporarily_unavailable";var to=class extends fe{};to.errorCode="unsupported_response_type";var ro=class extends fe{};ro.errorCode="unsupported_token_type";var no=class extends fe{};no.errorCode="invalid_token";var oo=class extends fe{};oo.errorCode="method_not_allowed";var so=class extends fe{};so.errorCode="too_many_requests";var cr=class extends fe{};cr.errorCode="invalid_client_metadata";var io=class extends fe{};io.errorCode="insufficient_scope";var ao=class extends fe{};ao.errorCode="invalid_target";var Zg={[Wn.errorCode]:Wn,[sr.errorCode]:sr,[ir.errorCode]:ir,[ar.errorCode]:ar,[Yn.errorCode]:Yn,[Xn.errorCode]:Xn,[Qn.errorCode]:Qn,[yt.errorCode]:yt,[eo.errorCode]:eo,[to.errorCode]:to,[ro.errorCode]:ro,[no.errorCode]:no,[oo.errorCode]:oo,[so.errorCode]:so,[cr.errorCode]:cr,[io.errorCode]:io,[ao.errorCode]:ao};var vt=class extends Error{constructor(t){super(t??"Unauthorized")}};function Tz(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var hu="code",gu="S256";function Rz(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Tz(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Ez(e,t,r,n){let{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":Iz(o,s,r);return;case"client_secret_post":Oz(o,s,n);return;case"none":Az(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Iz(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function Oz(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function Az(e,t){t.set("client_id",e)}async function Fg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Mg.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Zg[o]||yt;return new a(s||"",i)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new yt(o)}}async function co(e,t){try{return await _u(e,t)}catch(r){if(r instanceof sr||r instanceof ar)return await e.invalidateCredentials?.("all"),await _u(e,t);if(r instanceof ir)return await e.invalidateCredentials?.("tokens"),await _u(e,t);throw r}}async function _u(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await e.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await Hg(c,{fetchFn:s}),!a)try{a=await Vg(t,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let S=await qz(t,{resourceMetadataUrl:l,fetchFn:s});c=S.authorizationServerUrl,u=S.authorizationServerMetadata,a=S.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await Nz(t,e,a),p=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,m=await Promise.resolve(e.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let S=u?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!Cz(P))throw new cr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if(S&&P)m={client_id:P},await e.saveClientInformation?.(m);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let x=await Hz(c,{metadata:u,clientMetadata:e.clientMetadata,scope:p,fetchFn:s});await e.saveClientInformation(x),m=x}}let h=!e.redirectUrl;if(r!==void 0||h){let S=await Vz(e,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(S),"AUTHORIZED"}let g=await e.tokens();if(g?.refresh_token)try{let S=await Fz(c,{metadata:u,clientInformation:m,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(S),"AUTHORIZED"}catch(S){if(!(!(S instanceof fe)||S instanceof yt))throw S}let y=e.state?await e.state():void 0,{authorizationUrl:b,codeVerifier:$}=await Zz(c,{metadata:u,clientInformation:m,state:y,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier($),await e.redirectToAuthorization(b),"REDIRECT"}function Cz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Nz(e,t,r){let n=Ug(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!qg({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function vu(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=yu(e,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=yu(e,"scope")||void 0,a=yu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function yu(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function Vg(e,t,r=fetch){let n=await Dz(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Cg.parse(await n.json())}async function wu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?wu(e,void 0,r):void 0;throw n}}function jz(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Lg(e,t,r=fetch){return await wu(e,{"MCP-Protocol-Version":t},r)}function Mz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Dz(e,t,r,n){let o=new URL(e),s=n?.protocolVersion??$r,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=jz(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Lg(i,s,r);if(!n?.metadataUrl&&Mz(a,o.pathname)){let c=new URL(`/.well-known/${t}`,o);a=await Lg(c,s,r)}return a}function Uz(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function Hg(e,{fetchFn:t=fetch,protocolVersion:r=$r}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Uz(e);for(let{url:s,type:i}of o){let a=await wu(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?mu.parse(await a.json()):Ng.parse(await a.json())}}}async function qz(e,t){let r,n;try{r=await Vg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));let o=await Hg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Zz(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(hu))throw new Error(`Incompatible auth server: does not support response type ${hu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(gu))throw new Error(`Incompatible auth server: does not support code challenge method ${gu}`)}else a=new URL("/authorize",e);let c=await fu(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",hu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",gu),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function Lz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Bg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){let a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,a,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],d=Rz(n,l);Ez(d,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await Fg(u);return jg.parse(await u.json())}async function Fz(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Bg(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function Vz(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=e.clientMetadata.scope,a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await e.codeVerifier();a=Lz(o,u,e.redirectUrl)}let c=await e.clientInformation();return Bg(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Hz(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await Fg(i);return Dg.parse(await i.json())}var uo=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},Kg=10,Bz=13,ur=32;function bu(e){}function Wg(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=bu,onError:r=bu,onRetry:n=bu,onComment:o,maxBufferSize:s}=e,i=[],a=0,c=!0,u,l="",d=0,p,m=!1;function h(v){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){let G=y(v);G!==""&&(i.push(G),a=G.length),g();return}if(v.indexOf(`
|
|
36
|
-
`)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let x=i.join("");i.length=0,a=0;let O=y(x);O!==""&&(i.push(O),a=O.length),g()}function g(){s!==void 0&&(a+l.length<=s||(m=!0,i.length=0,a=0,u=void 0,l="",d=0,p=void 0,r(new uo(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let x=0;if(v.indexOf("\r")===-1){let O=v.indexOf(`
|
|
37
|
-
`,x);for(;O!==-1;){if(x===O){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0,x=O+1,O=v.indexOf(`
|
|
38
|
-
`,x);continue}let G=v.charCodeAt(x);if(Jg(v,x,G)){let ce=v.charCodeAt(x+5)===ur?x+6:x+5,ge=v.slice(ce,O);if(d===0&&v.charCodeAt(O+1)===Kg){t({id:u,event:p,data:ge}),u=void 0,l="",p=void 0,x=O+2,O=v.indexOf(`
|
|
39
|
-
`,x);continue}l=d===0?ge:`${l}
|
|
40
|
-
${ge}`,d++}else Gg(v,x,G)?p=v.slice(v.charCodeAt(x+6)===ur?x+7:x+6,O)||void 0:b(v,x,O);x=O+1,O=v.indexOf(`
|
|
41
|
-
`,x)}return v.slice(x)}for(;x<v.length;){let O=v.indexOf("\r",x),G=v.indexOf(`
|
|
42
|
-
`,x),ce=-1;if(O!==-1&&G!==-1?ce=O<G?O:G:O!==-1?O===v.length-1?ce=-1:ce=O:G!==-1&&(ce=G),ce===-1)break;b(v,x,ce),x=ce+1,v.charCodeAt(x-1)===Bz&&v.charCodeAt(x)===Kg&&x++}return v.slice(x)}function b(v,x,O){if(x===O){S();return}let G=v.charCodeAt(x);if(Jg(v,x,G)){let $t=v.charCodeAt(x+5)===ur?x+6:x+5,Xu=v.slice($t,O);l=d===0?Xu:`${l}
|
|
43
|
-
${Xu}`,d++;return}if(Gg(v,x,G)){p=v.slice(v.charCodeAt(x+6)===ur?x+7:x+6,O)||void 0;return}if(G===105&&v.charCodeAt(x+1)===100&&v.charCodeAt(x+2)===58){let $t=v.slice(v.charCodeAt(x+3)===ur?x+4:x+3,O);u=$t.includes("\0")?void 0:$t;return}if(G===58){if(o){let $t=v.slice(x,O);o($t.slice(v.charCodeAt(x+1)===ur?2:1))}return}let ce=v.slice(x,O),ge=ce.indexOf(":");if(ge===-1){$(ce,"",ce);return}let St=ce.slice(0,ge),_o=ce.charCodeAt(ge+1)===ur?2:1,yo=ce.slice(ge+_o);$(St,yo,ce)}function $(v,x,O){switch(v){case"event":p=x||void 0;break;case"data":l=d===0?x:`${l}
|
|
44
|
-
${x}`,d++;break;case"id":u=x.includes("\0")?void 0:x;break;case"retry":/^\d+$/.test(x)?n(parseInt(x,10)):r(new uo(`Invalid \`retry\` value: "${x}"`,{type:"invalid-retry",value:x,line:O}));break;default:r(new uo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:x,line:O}));break}}function S(){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function P(v={}){if(v.consume&&i.length>0){let x=i.join("");b(x,0,x.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,m=!1}return{feed:h,reset:P}}function Jg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Gg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Cs=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Wg({onEvent:a=>{i.enqueue(a)},onError(a){typeof t=="function"&&t(a),(t==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var Kz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},jt=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Hr=class{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Og(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Kz}async _authThenStart(){if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=As(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new jt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Cs({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:h}=await l.read();if(h)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let g=Ht.parse(JSON.parse(m.data));zt(g)&&(c=!0,s!==void 0&&(g.id=s)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new vt("No auth provider");if(await co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:xr(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new jt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:h}=vu(a);if(this._resourceMetadataUrl=m,this._scope=h,await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:h,error:g}=vu(a);if(g==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new jt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new vt;return this.send(t)}}throw new jt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Pf(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let l=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,d=a.headers.get("content-type");if(l)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){let p=await a.json(),m=Array.isArray(p)?p.map(h=>Ht.parse(h)):[Ht.parse(p)];for(let h of m)this.onmessage?.(h)}else throw await a.body?.cancel(),new jt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new jt(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};import*as Te from"node:fs";import{randomBytes as eP}from"node:crypto";import{homedir as tP}from"node:os";import{resolve as Ru,join as Eu,dirname as Iu,basename as rP}from"node:path";import*as Br from"node:fs";import{homedir as n_}from"node:os";import{isAbsolute as Gz,join as Wz,normalize as Yz,resolve as Xz}from"node:path";import{homedir as Yg}from"node:os";import{join as Jz,resolve as Xg}from"node:path";var Su=3050;function $u(e=Yg()){return Xg(Jz(e,".ours"))}function xu(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ku(e){return typeof e=="string"?e:void 0}function Qg(e,t=Yg()){return{port:xu(e.port)??Su,stateDir:Xg(ku(e.stateDir)??$u(t))}}var e_=1,o_=["claude-code","codex","hermes"],K=class extends Error{code;constructor(t,r="INVALID_ASSOCIATION"){super(`ours profile association: ${t}. Re-run the Nightly installer to repair this association`),this.name="AssociationError",this.code=r}};function zu(e,t,r){for(let n of Object.keys(e))if(!t.includes(n))throw new K(`${r} contains unsupported field ${JSON.stringify(n)}`)}function s_(e){let t=[],r;for(let n=0;n<e.length;n+=1){let o=e[n],s;if(o==="--application"){if(e[n+1]===void 0)throw new K("--application requires a value","INVALID_APPLICATION");s=e[++n]}else if(o.startsWith("--application="))s=o.slice(14);else{t.push(o);continue}if(!o_.includes(s))throw new K(`unknown application ${JSON.stringify(s)}`,"INVALID_APPLICATION");if(r&&r!==s)throw new K("only one --application value may be supplied","INVALID_APPLICATION");r=s}return{application:r,argv:t}}function i_(e,t){if(e&&t!=="proxy"&&t!=="watch")throw new K(`--application is legal only for client commands proxy and watch, not ${t}`,"APPLICATION_NOT_ALLOWED")}function Qz(e=process.env,t=n_()){return e.OURS_INSTALL_PROFILES?Pu(e.OURS_INSTALL_PROFILES,"OURS_INSTALL_PROFILES"):Wz(t,".ours","installer-profiles.json")}function Pu(e,t){if(typeof e!="string"||!e||e.includes("\0")||!Gz(e)||Yz(e)!==e||e==="/")throw new K(`${t} must be a normalized absolute path`,"UNSAFE_PATH");return e}function t_(e,t){let r=/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,30}[A-Za-z0-9])?$/;if(!r.test(t))throw new K(`invalid profile id ${JSON.stringify(t)}`);if(!e||typeof e!="object"||Array.isArray(e))throw new K(`profile ${JSON.stringify(t)} is not an object`);let n=e;zu(n,["label","host","port","configPath","stateDir","serviceName","ownership"],`profile ${t}`);let o=typeof n.label=="string"?n.label.trim():"";if(!o)throw new K(`profile ${JSON.stringify(t)} has no label`);let s=String(n.host??"").toLowerCase();if(s!=="127.0.0.1"&&s!=="localhost")throw new K(`profile ${JSON.stringify(t)} uses non-loopback host ${JSON.stringify(n.host)}`,"UNSAFE_HOST");let i=Number(n.port);if(!Number.isInteger(i)||i<1||i>65535)throw new K(`profile ${JSON.stringify(t)} has invalid port`,"INVALID_PORT");let a=n.ownership;if(!a||typeof a!="object"||Array.isArray(a))throw new K(`profile ${JSON.stringify(t)} has no explicit ownership`);let c=a;if(zu(c,["config","service","state"],`profile ${t} ownership`),typeof c.config!="boolean"||typeof c.service!="boolean"||typeof c.state!="boolean")throw new K(`profile ${JSON.stringify(t)} has invalid ownership`);let u=typeof n.serviceName=="string"?n.serviceName.trim():"";if(t!=="default"&&!u||u&&!r.test(u))throw new K(`profile ${JSON.stringify(t)} has invalid serviceName`);return{label:o,host:"127.0.0.1",port:i,configPath:Pu(n.configPath,`profile ${t} configPath`),stateDir:Pu(n.stateDir,`profile ${t} stateDir`),serviceName:u,ownership:{config:c.config,service:c.service,state:c.state}}}function r_(e,t){let r;try{r=Br.readFileSync(e,"utf8")}catch(n){throw new K(`cannot read ${t} ${e}: ${n.message}`,"READ_FAILED")}try{let n=JSON.parse(r);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("expected an object");return n}catch(n){throw new K(`${t} ${e} is corrupt JSON: ${n.message}`,"CORRUPT_JSON")}}function Mt(e){try{return Br.realpathSync(e)}catch{return Xz(e)}}function lo(e,t=process.env,r=n_()){if(!e||t.OURS_CONFIG||t.OURS_PORT||t.OURS_STATE_DIR)return null;let n=Qz(t,r);if(!Br.existsSync(n))return null;let o=r_(n,"installer profile registry");if(zu(o,["version","profiles","harnessAssociations"],"registry"),o.version!==e_)throw new K(`registry version is ${JSON.stringify(o.version)}, expected ${e_}`,"UNSUPPORTED_VERSION");let s=o.profiles,i=o.harnessAssociations;if(!s||typeof s!="object"||Array.isArray(s)||!i||typeof i!="object"||Array.isArray(i))throw new K("registry schema is invalid");let a=s,c=i,u=Object.fromEntries(Object.entries(a).map(([y,b])=>[y,t_(b,y)])),l=Object.entries(u);for(let y=0;y<l.length;y+=1){let[b,$]=l[y];for(let[S,P]of l.slice(y+1)){let v=$.port===P.port?"endpoint":Mt($.stateDir)===Mt(P.stateDir)?"stateDir":$.configPath===P.configPath?"configPath":$.serviceName===P.serviceName?"serviceName":"";if(v)throw new K(`profiles ${b} and ${S} collide on ${v}`,"PROFILE_COLLISION")}}for(let[y,b]of Object.entries(c))if(!o_.includes(y)||typeof b!="string"||!(b in a))throw new K(`registry contains invalid association ${JSON.stringify(y)} -> ${JSON.stringify(b)}`);let d=c[e];if(d===void 0)return null;if(typeof d!="string"||!(d in a))throw new K(`${e} names missing profile ${JSON.stringify(d)}`);let p=t_(a[d],d),m=r_(p.configPath,`associated daemon config for ${d}`),h=Qg(m,r),g=Mt(h.stateDir);if(h.port!==p.port)throw new K(`profile ${d} expects port ${p.port} but ${p.configPath} resolves port ${h.port}`,"CONFIG_DRIFT");if(g!==Mt(p.stateDir))throw new K(`profile ${d} expects stateDir ${p.stateDir} but ${p.configPath} resolves ${g}`,"CONFIG_DRIFT");return{application:e,profileId:d,profile:p,registryPath:n}}async function Tu(e,t,r,{fetch:n=globalThis.fetch,timeoutMs:o=2e3}={}){if(!e)return;let{profileId:s,profile:i}=e;if(t.port!==i.port||Mt(t.stateDir)!==Mt(i.stateDir))throw new K(`resolved runtime config drifted from profile ${s}`,"CONFIG_DRIFT");let a=async(d,p)=>{let m=new AbortController,h=setTimeout(()=>m.abort(),o);try{return await n(`http://127.0.0.1:${i.port}${d}`,{headers:p,signal:m.signal})}finally{clearTimeout(h)}},c;try{c=await a("/info")}catch(d){throw new K(`profile ${s} daemon is unreachable on 127.0.0.1:${i.port}: ${d.message}`,"UNREACHABLE")}if(!c.ok)throw new K(`profile ${s} /info returned HTTP ${c.status}`,"INCOMPATIBLE_DAEMON");let u=await c.json();if(u?.name!=="ours"||typeof u?.stateDir!="string")throw new K(`profile ${s} endpoint is not an ours daemon`,"INCOMPATIBLE_DAEMON");if(Mt(u.stateDir)!==Mt(i.stateDir))throw new K(`profile ${s} expects stateDir ${i.stateDir} but the daemon reports ${u.stateDir}`,"DAEMON_DRIFT");let l;try{l=await a("/identities",r?{"x-ours-api-token":r}:void 0)}catch(d){throw new K(`profile ${s} protected API probe failed: ${d.message}`,"AUTH_PROBE_FAILED")}if(l.status===401||l.status===403)throw new K(`profile ${s} rejected its selected authentication`,"AUTH_FAILED");if(!l.ok)throw new K(`profile ${s} protected API returned HTTP ${l.status}`,"INCOMPATIBLE_DAEMON")}var po=["owner","shared","open"],Kr={brokerUrl:"wss://broker1.ours.network",port:Su,stateDir:$u(),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function Dt(e={}){return process.env.OURS_CONFIG?process.env.OURS_CONFIG:lo(e.application)?.profile.configPath??Eu(tP(),".ours","config.json")}function nP(e=Dt()){let t;try{t=Te.readFileSync(e,"utf8")}catch{return{}}let r;try{r=JSON.parse(t)}catch{return{}}let n={};typeof r.brokerUrl=="string"&&(n.brokerUrl=r.brokerUrl);let o=xu(r.port);o!==void 0&&(n.port=o);let s=ku(r.stateDir);if(s!==void 0&&(n.stateDir=Ru(s)),typeof r.gcIntervalMs=="number"&&Number.isFinite(r.gcIntervalMs)&&(n.gcIntervalMs=r.gcIntervalMs),typeof r.autoStart=="boolean"&&(n.autoStart=r.autoStart),typeof r.apiVisibility=="string"&&po.includes(r.apiVisibility)&&(n.apiVisibility=r.apiVisibility),typeof r.apiToken=="string"&&r.apiToken.trim()&&(n.apiToken=r.apiToken.trim()),typeof r.serviceName=="string"&&r.serviceName.trim()&&(n.serviceName=r.serviceName.trim()),r.stt&&typeof r.stt=="object"){let i=r.stt,a={};typeof i.provider=="string"&&(a.provider=i.provider),typeof i.apiKey=="string"&&(a.apiKey=i.apiKey),typeof i.model=="string"&&(a.model=i.model),typeof i.baseUrl=="string"&&(a.baseUrl=i.baseUrl),typeof i.language=="string"&&(a.language=i.language),typeof i.maxBytes=="number"&&Number.isFinite(i.maxBytes)&&(a.maxBytes=i.maxBytes),typeof i.timeoutMs=="number"&&Number.isFinite(i.timeoutMs)&&(a.timeoutMs=i.timeoutMs),i.custom&&typeof i.custom=="object"&&(a.custom=i.custom),n.stt=a}return n}function oP(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&po.includes(e)?e:void 0}function sP(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function a_(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function Ou(e={}){let t=lo(e.application),r=nP(t?.profile.configPath??Dt());return{brokerUrl:process.env.OURS_BROKER_URL??r.brokerUrl??Kr.brokerUrl,port:a_("OURS_PORT")??r.port??Kr.port,stateDir:Ru(process.env.OURS_STATE_DIR??r.stateDir??Kr.stateDir),gcIntervalMs:a_("OURS_GC_INTERVAL_MS")??r.gcIntervalMs??Kr.gcIntervalMs,autoStart:t?!1:sP("OURS_AUTOSTART")??r.autoStart??Kr.autoStart,apiVisibility:oP()??r.apiVisibility??Kr.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||r.apiToken,serviceName:process.env.OURS_SERVICE_NAME?.trim()||r.serviceName,stt:iP(r.stt)}}function iP(e){let t={};process.env.OURS_STT_PROVIDER?.trim()&&(t.provider=process.env.OURS_STT_PROVIDER.trim()),process.env.OURS_STT_API_KEY?.trim()&&(t.apiKey=process.env.OURS_STT_API_KEY.trim()),process.env.OURS_STT_MODEL?.trim()&&(t.model=process.env.OURS_STT_MODEL.trim()),process.env.OURS_STT_BASE_URL?.trim()&&(t.baseUrl=process.env.OURS_STT_BASE_URL.trim()),process.env.OURS_STT_LANGUAGE?.trim()&&(t.language=process.env.OURS_STT_LANGUAGE.trim());let r={...e??{},...t};return Object.keys(r).length?r:void 0}var aP="daemon-token";function cP(e){return Eu(e.stateDir,aP)}function fo(e,t={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let n=e.apiToken?.trim();if(n)return{token:n,source:"config"};let o=cP(e);try{let i=Te.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let s=eP(32).toString("hex");try{Te.mkdirSync(Iu(o),{recursive:!0}),Te.writeFileSync(o,s+`
|
|
45
|
-
`,{mode:384}),Te.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}function c_(e){let t=Dt();Te.mkdirSync(Iu(t),{recursive:!0}),Te.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
46
|
-
`,{mode:384});try{Te.chmodSync(t,384)}catch{}return t}var Ns=".ours-identity";function js(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function Au(e){let t=Ru(e);return rP(t)===Ns?t:Eu(t,Ns)}function u_(e,t,r=!1){let n=js(t),o=Au(e);if(!r&&Te.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Te.mkdirSync(Iu(o),{recursive:!0}),Te.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
47
|
-
`),o}import{runProxy as XP}from"@ours.network/sdk/connector";import d_ from"node:process";var Ms=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
48
|
-
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),uP(r)}clear(){this._buffer=void 0}};function uP(e){return Ht.parse(JSON.parse(e))}function l_(e){return JSON.stringify(e)+`
|
|
49
|
-
`}var Ds=class{constructor(t=d_.stdin,r=d_.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Ms,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=l_(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{Readable as p_}from"stream";import gP from"crypto";var lP=global.Request,ju=class extends lP{constructor(e,t){typeof e=="object"&&Gr in e&&(e=e[Gr]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},dP=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},pP=Symbol("wrapBodyStream"),fP=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ju(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[pP]){let i;s.body=new ReadableStream({async pull(a){try{i||=p_.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else s.body=p_.toWeb(n);return new ju(t,s)},Gr=Symbol("getRequestCache"),m_=Symbol("requestCache"),Cu=Symbol("incomingKey"),f_=Symbol("urlKey"),mP=Symbol("headersKey"),Nu=Symbol("abortControllerKey"),hP=Symbol("getAbortController"),qs={get method(){return this[Cu].method||"GET"},get url(){return this[f_]},get headers(){return this[mP]||=dP(this[Cu])},[hP](){return this[Gr](),this[Nu]},[Gr](){return this[Nu]||=new AbortController,this[m_]||=fP(this.method,this[f_],this.headers,this[Cu],this[Nu])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(qs,e,{get(){return this[Gr]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(qs,e,{value:function(){return this[Gr]()[e]()}})});Object.defineProperty(qs,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[m_]};return`Request (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(qs,ju.prototype);var Mu=Symbol("responseCache"),Jr=Symbol("getResponseCache"),Us=Symbol("cache"),Du=global.Response,mo=class h_{#t;#e;[Jr](){return delete this[Us],this[Mu]||=new Du(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof h_){let o=r[Mu];if(o){this.#e=o,this[Jr]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[Us]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[Us];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[Jr]().headers}get status(){return this[Us]?.[0]??this[Jr]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(mo.prototype,e,{get(){return this[Jr]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(mo.prototype,e,{value:function(){return this[Jr]()[e]()}})});Object.defineProperty(mo.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Mu]};return`Response (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(mo,Du);Object.setPrototypeOf(mo.prototype,Du.prototype);typeof global.crypto>"u"&&(global.crypto=gP);var p1=Symbol("outgoingEnded"),f1=Symbol("incomingDraining");var m1=64*1024*1024;var g_={createStdioServer:()=>new Ds,createHttpClient:(e,t)=>new Hr(e,t)};import{accessSync as yP,constants as vP}from"node:fs";var __=e=>{try{return yP(e,vP.R_OK),!0}catch{return!1}};var wP=e=>` \u2022 ${e.filename} \u2014 ${e.mime||"application/octet-stream"}, ${e.size} B, sha256 ${e.sha256} \u2014 from ${e.sender} \u2014 wire_id ${e.wire_id}`;function bP(e,t){let r=e;if(!r||r.isError)return!1;let n=r.structuredContent?.files;if(!Array.isArray(n))return!1;let o=n.filter(a=>!!a&&typeof a=="object"&&typeof a.path=="string"&&typeof a.wire_id=="string");if(o.length===0)return!1;let s=o.filter(a=>a.kind!=="voice_message"&&!t(a.path));for(let a of o)a.readable=t(a.path);if(s.length===0)return!1;let i=[`${s.length} of ${o.length} received file(s) are NOT readable by your OS user: the ours daemon runs as a different OS user and keeps its files dir private. Nothing was lost \u2014 the bytes are safely on disk. IGNORE the on-disk paths reported below for these files; you cannot open them.`,"","TELL THE USER what arrived (details below) and ASK WHERE TO SAVE each file on this filesystem. Then call save_file({ wire_id, dest_path }) with the path they choose: the ours connector streams the bytes daemon\u2192proxy\u2192disk and writes them as YOUR OS user. The bytes never enter this conversation.","","Awaiting a destination:",...s.map(wP)];return r.content=[{type:"text",text:i.join(`
|
|
50
|
-
`)},...r.content??[]],!0}function y_(e,t){let r=e;return!r||typeof r!="object"||!("result"in r)?!1:bP(r.result,t)}var Uu=["openai-compatible","elevenlabs","deepgram","custom"],A1=5*1024*1024;function ho(e){let t="configure it in config.json `stt: {}` or via OURS_STT_* env";if(!e?.provider)return{ready:!1,reason:`no STT provider configured (stt.provider: ${Uu.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!Uu.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${Uu.join(" | ")})`};if(!e.apiKey?.trim())return{ready:!1,reason:`STT provider "${r}" is set but the API key is missing (stt.apiKey / OURS_STT_API_KEY)`};if(r==="openai-compatible"){if(!e.baseUrl?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.baseUrl / OURS_STT_BASE_URL (e.g. your provider's /v1 root) \u2014 no endpoint is assumed"};if(!e.model?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.model / OURS_STT_MODEL (passed to the provider verbatim) \u2014 no model is assumed"}}if(r==="elevenlabs"&&!e.model?.trim())return{ready:!1,reason:"elevenlabs STT needs stt.model / OURS_STT_MODEL (the model_id, e.g. from your ElevenLabs account) \u2014 no model is assumed"};if(r==="custom"){if(!e.custom?.url?.trim())return{ready:!1,reason:"custom STT needs stt.custom.url (the full endpoint URL of your provider)"};if((e.custom.url.includes("{model}")||e.custom.modelField!==void 0&&e.custom.modelField!=="")&&!e.model?.trim())return{ready:!1,reason:"the custom STT template references a model (url {model} or modelField) but stt.model / OURS_STT_MODEL is not set"}}return{ready:!0,provider:r}}function SP(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trimStart();return/^[A-Za-z](?:\s|$)/.test(r)?r[0]:null}function v_(e){let t=SP(e);return t==="Z"||t==="X"||t==="x"}var $P="ours.service",w_="solutions.adaptframework.ours",xP=/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,30}[A-Za-z0-9])?$/;function lr(e){let t=typeof e=="string"?e.trim():"";return t?t.length>32?{ok:!1,name:"",reason:"service name must be 32 characters or fewer"}:xP.test(t)?{ok:!0,name:t}:{ok:!1,name:"",reason:"service name must be 1\u201332 characters of letters, digits, hyphen or underscore, starting and ending with a letter or digit"}:{ok:!0,name:""}}function b_(e=""){let{ok:t,name:r}=lr(e);return!t||!r?$P:`ours-${r}.service`}function qu(e=""){let{ok:t,name:r}=lr(e);return!t||!r?w_:`${w_}.${r}`}function kP(e=""){let{ok:t,name:r}=lr(e);return t&&r?`ours MCP daemon (instance "${r}") \u2014 secure agent-to-agent messaging over ADAPT`:"ours MCP daemon (secure agent-to-agent messaging over ADAPT)"}function S_(e){let t=lr(e.instance).name,r=t?`Environment=OURS_SERVICE_NAME=${t}
|
|
3
|
+
import{spawn as Lt,spawnSync as ee}from"node:child_process";import{connect as Fr}from"node:net";import{homedir as Dt,userInfo as Ne}from"node:os";import{resolve as Ft,join as E,dirname as de}from"node:path";import{fileURLToPath as Mr,pathToFileURL as Pt}from"node:url";import{createInterface as pe}from"node:readline/promises";import*as m from"node:fs";import{OursClient as Vr,OursError as kt}from"@ours.network/sdk/client";import*as T from"node:fs";import{randomBytes as rr}from"node:crypto";import{homedir as nr}from"node:os";import{resolve as Ae,join as Pe,dirname as ke,basename as or}from"node:path";import*as q from"node:fs";import{homedir as Xe}from"node:os";import{isAbsolute as Zt,join as Xt,normalize as Qt,resolve as er}from"node:path";import{homedir as He}from"node:os";import{join as Wt,resolve as Ye}from"node:path";var he=3050;function ve(e=He()){return Ye(Wt(e,".ours"))}function be(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function we(e){return typeof e=="string"?e:void 0}function qe(e,t=He()){return{port:be(e.port)??he,stateDir:Ye(we(e.stateDir)??ve(t))}}var ze=1,Qe=["claude-code","codex","hermes"],S=class extends Error{code;constructor(t,r="INVALID_ASSOCIATION"){super(`ours profile association: ${t}. Re-run the Nightly installer to repair this association`),this.name="AssociationError",this.code=r}};function Te(e,t,r){for(let n of Object.keys(e))if(!t.includes(n))throw new S(`${r} contains unsupported field ${JSON.stringify(n)}`)}function et(e){let t=[],r;for(let n=0;n<e.length;n+=1){let s=e[n],o;if(s==="--application"){if(e[n+1]===void 0)throw new S("--application requires a value","INVALID_APPLICATION");o=e[++n]}else if(s.startsWith("--application="))o=s.slice(14);else{t.push(s);continue}if(!Qe.includes(o))throw new S(`unknown application ${JSON.stringify(o)}`,"INVALID_APPLICATION");if(r&&r!==o)throw new S("only one --application value may be supplied","INVALID_APPLICATION");r=o}return{application:r,argv:t}}function tt(e,t){if(e&&t!=="proxy"&&t!=="watch")throw new S(`--application is legal only for client commands proxy and watch, not ${t}`,"APPLICATION_NOT_ALLOWED")}function tr(e=process.env,t=Xe()){return e.OURS_INSTALL_PROFILES?_e(e.OURS_INSTALL_PROFILES,"OURS_INSTALL_PROFILES"):Xt(t,".ours","installer-profiles.json")}function _e(e,t){if(typeof e!="string"||!e||e.includes("\0")||!Zt(e)||Qt(e)!==e||e==="/")throw new S(`${t} must be a normalized absolute path`,"UNSAFE_PATH");return e}function We(e,t){let r=/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,30}[A-Za-z0-9])?$/;if(!r.test(t))throw new S(`invalid profile id ${JSON.stringify(t)}`);if(!e||typeof e!="object"||Array.isArray(e))throw new S(`profile ${JSON.stringify(t)} is not an object`);let n=e;Te(n,["label","host","port","configPath","stateDir","serviceName","ownership"],`profile ${t}`);let s=typeof n.label=="string"?n.label.trim():"";if(!s)throw new S(`profile ${JSON.stringify(t)} has no label`);let o=String(n.host??"").toLowerCase();if(o!=="127.0.0.1"&&o!=="localhost")throw new S(`profile ${JSON.stringify(t)} uses non-loopback host ${JSON.stringify(n.host)}`,"UNSAFE_HOST");let i=Number(n.port);if(!Number.isInteger(i)||i<1||i>65535)throw new S(`profile ${JSON.stringify(t)} has invalid port`,"INVALID_PORT");let c=n.ownership;if(!c||typeof c!="object"||Array.isArray(c))throw new S(`profile ${JSON.stringify(t)} has no explicit ownership`);let l=c;if(Te(l,["config","service","state"],`profile ${t} ownership`),typeof l.config!="boolean"||typeof l.service!="boolean"||typeof l.state!="boolean")throw new S(`profile ${JSON.stringify(t)} has invalid ownership`);let u=typeof n.serviceName=="string"?n.serviceName.trim():"";if(t!=="default"&&!u||u&&!r.test(u))throw new S(`profile ${JSON.stringify(t)} has invalid serviceName`);return{label:s,host:"127.0.0.1",port:i,configPath:_e(n.configPath,`profile ${t} configPath`),stateDir:_e(n.stateDir,`profile ${t} stateDir`),serviceName:u,ownership:{config:l.config,service:l.service,state:l.state}}}function Ze(e,t){let r;try{r=q.readFileSync(e,"utf8")}catch(n){throw new S(`cannot read ${t} ${e}: ${n.message}`,"READ_FAILED")}try{let n=JSON.parse(r);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("expected an object");return n}catch(n){throw new S(`${t} ${e} is corrupt JSON: ${n.message}`,"CORRUPT_JSON")}}function D(e){try{return q.realpathSync(e)}catch{return er(e)}}function oe(e,t=process.env,r=Xe()){if(!e||t.OURS_CONFIG||t.OURS_PORT||t.OURS_STATE_DIR)return null;let n=tr(t,r);if(!q.existsSync(n))return null;let s=Ze(n,"installer profile registry");if(Te(s,["version","profiles","harnessAssociations"],"registry"),s.version!==ze)throw new S(`registry version is ${JSON.stringify(s.version)}, expected ${ze}`,"UNSUPPORTED_VERSION");let o=s.profiles,i=s.harnessAssociations;if(!o||typeof o!="object"||Array.isArray(o)||!i||typeof i!="object"||Array.isArray(i))throw new S("registry schema is invalid");let c=o,l=i,u=Object.fromEntries(Object.entries(c).map(([b,R])=>[b,We(R,b)])),d=Object.entries(u);for(let b=0;b<d.length;b+=1){let[R,I]=d[b];for(let[C,A]of d.slice(b+1)){let L=I.port===A.port?"endpoint":D(I.stateDir)===D(A.stateDir)?"stateDir":I.configPath===A.configPath?"configPath":I.serviceName===A.serviceName?"serviceName":"";if(L)throw new S(`profiles ${R} and ${C} collide on ${L}`,"PROFILE_COLLISION")}}for(let[b,R]of Object.entries(l))if(!Qe.includes(b)||typeof R!="string"||!(R in c))throw new S(`registry contains invalid association ${JSON.stringify(b)} -> ${JSON.stringify(R)}`);let f=l[e];if(f===void 0)return null;if(typeof f!="string"||!(f in c))throw new S(`${e} names missing profile ${JSON.stringify(f)}`);let p=We(c[f],f),g=Ze(p.configPath,`associated daemon config for ${f}`),v=qe(g,r),j=D(v.stateDir);if(v.port!==p.port)throw new S(`profile ${f} expects port ${p.port} but ${p.configPath} resolves port ${v.port}`,"CONFIG_DRIFT");if(j!==D(p.stateDir))throw new S(`profile ${f} expects stateDir ${p.stateDir} but ${p.configPath} resolves ${j}`,"CONFIG_DRIFT");return{application:e,profileId:f,profile:p,registryPath:n}}async function Re(e,t,r,{fetch:n=globalThis.fetch,timeoutMs:s=2e3}={}){if(!e)return;let{profileId:o,profile:i}=e;if(t.port!==i.port||D(t.stateDir)!==D(i.stateDir))throw new S(`resolved runtime config drifted from profile ${o}`,"CONFIG_DRIFT");let c=async(f,p)=>{let g=new AbortController,v=setTimeout(()=>g.abort(),s);try{return await n(`http://127.0.0.1:${i.port}${f}`,{headers:p,signal:g.signal})}finally{clearTimeout(v)}},l;try{l=await c("/info")}catch(f){throw new S(`profile ${o} daemon is unreachable on 127.0.0.1:${i.port}: ${f.message}`,"UNREACHABLE")}if(!l.ok)throw new S(`profile ${o} /info returned HTTP ${l.status}`,"INCOMPATIBLE_DAEMON");let u=await l.json();if(u?.name!=="ours"||typeof u?.stateDir!="string")throw new S(`profile ${o} endpoint is not an ours daemon`,"INCOMPATIBLE_DAEMON");if(D(u.stateDir)!==D(i.stateDir))throw new S(`profile ${o} expects stateDir ${i.stateDir} but the daemon reports ${u.stateDir}`,"DAEMON_DRIFT");let d;try{d=await c("/identities",r?{"x-ours-api-token":r}:void 0)}catch(f){throw new S(`profile ${o} protected API probe failed: ${f.message}`,"AUTH_PROBE_FAILED")}if(d.status===401||d.status===403)throw new S(`profile ${o} rejected its selected authentication`,"AUTH_FAILED");if(!d.ok)throw new S(`profile ${o} protected API returned HTTP ${d.status}`,"INCOMPATIBLE_DAEMON")}var ie=["owner","shared","open"],z={brokerUrl:"wss://broker1.ours.network",port:he,stateDir:ve(),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function F(e={}){return process.env.OURS_CONFIG?process.env.OURS_CONFIG:oe(e.application)?.profile.configPath??Pe(nr(),".ours","config.json")}function ir(e=F()){let t;try{t=T.readFileSync(e,"utf8")}catch{return{}}let r;try{r=JSON.parse(t)}catch{return{}}let n={};typeof r.brokerUrl=="string"&&(n.brokerUrl=r.brokerUrl);let s=be(r.port);s!==void 0&&(n.port=s);let o=we(r.stateDir);if(o!==void 0&&(n.stateDir=Ae(o)),typeof r.gcIntervalMs=="number"&&Number.isFinite(r.gcIntervalMs)&&(n.gcIntervalMs=r.gcIntervalMs),typeof r.autoStart=="boolean"&&(n.autoStart=r.autoStart),typeof r.apiVisibility=="string"&&ie.includes(r.apiVisibility)&&(n.apiVisibility=r.apiVisibility),typeof r.apiToken=="string"&&r.apiToken.trim()&&(n.apiToken=r.apiToken.trim()),typeof r.serviceName=="string"&&r.serviceName.trim()&&(n.serviceName=r.serviceName.trim()),r.stt&&typeof r.stt=="object"){let i=r.stt,c={};typeof i.provider=="string"&&(c.provider=i.provider),typeof i.apiKey=="string"&&(c.apiKey=i.apiKey),typeof i.model=="string"&&(c.model=i.model),typeof i.baseUrl=="string"&&(c.baseUrl=i.baseUrl),typeof i.language=="string"&&(c.language=i.language),typeof i.maxBytes=="number"&&Number.isFinite(i.maxBytes)&&(c.maxBytes=i.maxBytes),typeof i.timeoutMs=="number"&&Number.isFinite(i.timeoutMs)&&(c.timeoutMs=i.timeoutMs),i.custom&&typeof i.custom=="object"&&(c.custom=i.custom),n.stt=c}return n}function sr(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&ie.includes(e)?e:void 0}function ar(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function rt(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function Oe(e={}){let t=oe(e.application),r=ir(t?.profile.configPath??F());return{brokerUrl:process.env.OURS_BROKER_URL??r.brokerUrl??z.brokerUrl,port:rt("OURS_PORT")??r.port??z.port,stateDir:Ae(process.env.OURS_STATE_DIR??r.stateDir??z.stateDir),gcIntervalMs:rt("OURS_GC_INTERVAL_MS")??r.gcIntervalMs??z.gcIntervalMs,autoStart:t?!1:ar("OURS_AUTOSTART")??r.autoStart??z.autoStart,apiVisibility:sr()??r.apiVisibility??z.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||r.apiToken,serviceName:process.env.OURS_SERVICE_NAME?.trim()||r.serviceName,stt:cr(r.stt)}}function cr(e){let t={};process.env.OURS_STT_PROVIDER?.trim()&&(t.provider=process.env.OURS_STT_PROVIDER.trim()),process.env.OURS_STT_API_KEY?.trim()&&(t.apiKey=process.env.OURS_STT_API_KEY.trim()),process.env.OURS_STT_MODEL?.trim()&&(t.model=process.env.OURS_STT_MODEL.trim()),process.env.OURS_STT_BASE_URL?.trim()&&(t.baseUrl=process.env.OURS_STT_BASE_URL.trim()),process.env.OURS_STT_LANGUAGE?.trim()&&(t.language=process.env.OURS_STT_LANGUAGE.trim());let r={...e??{},...t};return Object.keys(r).length?r:void 0}var lr="daemon-token";function ur(e){return Pe(e.stateDir,lr)}function W(e,t={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let n=e.apiToken?.trim();if(n)return{token:n,source:"config"};let s=ur(e);try{let i=T.readFileSync(s,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let o=rr(32).toString("hex");try{T.mkdirSync(ke(s),{recursive:!0}),T.writeFileSync(s,o+`
|
|
4
|
+
`,{mode:384}),T.chmodSync(s,384)}catch{}return{token:o,source:"generated"}}function nt(e){let t=F();T.mkdirSync(ke(t),{recursive:!0}),T.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384});try{T.chmodSync(t,384)}catch{}return t}var ae=".ours-identity";function ce(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function $e(e){let t=Ae(e);return or(t)===ae?t:Pe(t,ae)}function ot(e,t,r=!1){let n=ce(t),s=$e(e);if(!r&&T.existsSync(s))throw new Error(`${s} already exists \u2014 pass overwrite to replace it`);return T.mkdirSync(ke(s),{recursive:!0}),T.writeFileSync(s,JSON.stringify(n,null,2)+`
|
|
6
|
+
`),s}var Ie=["openai-compatible","elevenlabs","deepgram","custom"],On=5*1024*1024;function se(e){let t="configure it in config.json `stt: {}` or via OURS_STT_* env";if(!e?.provider)return{ready:!1,reason:`no STT provider configured (stt.provider: ${Ie.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!Ie.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${Ie.join(" | ")})`};if(!e.apiKey?.trim())return{ready:!1,reason:`STT provider "${r}" is set but the API key is missing (stt.apiKey / OURS_STT_API_KEY)`};if(r==="openai-compatible"){if(!e.baseUrl?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.baseUrl / OURS_STT_BASE_URL (e.g. your provider's /v1 root) \u2014 no endpoint is assumed"};if(!e.model?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.model / OURS_STT_MODEL (passed to the provider verbatim) \u2014 no model is assumed"}}if(r==="elevenlabs"&&!e.model?.trim())return{ready:!1,reason:"elevenlabs STT needs stt.model / OURS_STT_MODEL (the model_id, e.g. from your ElevenLabs account) \u2014 no model is assumed"};if(r==="custom"){if(!e.custom?.url?.trim())return{ready:!1,reason:"custom STT needs stt.custom.url (the full endpoint URL of your provider)"};if((e.custom.url.includes("{model}")||e.custom.modelField!==void 0&&e.custom.modelField!=="")&&!e.model?.trim())return{ready:!1,reason:"the custom STT template references a model (url {model} or modelField) but stt.model / OURS_STT_MODEL is not set"}}return{ready:!0,provider:r}}function dr(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trimStart();return/^[A-Za-z](?:\s|$)/.test(r)?r[0]:null}function it(e){let t=dr(e);return t==="Z"||t==="X"||t==="x"}var pr="ours.service",st="solutions.adaptframework.ours",fr=/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,30}[A-Za-z0-9])?$/;function B(e){let t=typeof e=="string"?e.trim():"";return t?t.length>32?{ok:!1,name:"",reason:"service name must be 32 characters or fewer"}:fr.test(t)?{ok:!0,name:t}:{ok:!1,name:"",reason:"service name must be 1\u201332 characters of letters, digits, hyphen or underscore, starting and ending with a letter or digit"}:{ok:!0,name:""}}function at(e=""){let{ok:t,name:r}=B(e);return!t||!r?pr:`ours-${r}.service`}function xe(e=""){let{ok:t,name:r}=B(e);return!t||!r?st:`${st}.${r}`}function mr(e=""){let{ok:t,name:r}=B(e);return t&&r?`ours MCP daemon (instance "${r}") \u2014 secure agent-to-agent messaging over ADAPT`:"ours MCP daemon (secure agent-to-agent messaging over ADAPT)"}function ct(e){let t=B(e.instance).name,r=t?`Environment=OURS_SERVICE_NAME=${t}
|
|
51
7
|
`:"",n=t&&e.configPath?`Environment=OURS_CONFIG=${e.configPath}
|
|
52
8
|
`:"";return`[Unit]
|
|
53
|
-
Description=${
|
|
9
|
+
Description=${mr(t)}
|
|
54
10
|
After=network-online.target
|
|
55
11
|
Wants=network-online.target
|
|
56
12
|
|
|
@@ -66,44 +22,44 @@ RestartSec=2
|
|
|
66
22
|
|
|
67
23
|
[Install]
|
|
68
24
|
WantedBy=default.target
|
|
69
|
-
`}function
|
|
70
|
-
`:"",n=t&&e.configPath?` <key>OURS_CONFIG</key><string>${
|
|
25
|
+
`}function U(e){return String(e).replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function lt(e){let t=B(e.instance).name,r=t?` <key>OURS_SERVICE_NAME</key><string>${U(t)}</string>
|
|
26
|
+
`:"",n=t&&e.configPath?` <key>OURS_CONFIG</key><string>${U(e.configPath)}</string>
|
|
71
27
|
`:"";return`<?xml version="1.0" encoding="UTF-8"?>
|
|
72
28
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
73
29
|
<plist version="1.0">
|
|
74
30
|
<dict>
|
|
75
|
-
<key>Label</key><string>${
|
|
31
|
+
<key>Label</key><string>${U(xe(t))}</string>
|
|
76
32
|
<key>ProgramArguments</key>
|
|
77
33
|
<array>
|
|
78
|
-
<string>${
|
|
79
|
-
<string>${
|
|
34
|
+
<string>${U(e.execPath)}</string>
|
|
35
|
+
<string>${U(e.self)}</string>
|
|
80
36
|
<string>serve</string>
|
|
81
37
|
</array>
|
|
82
38
|
<key>EnvironmentVariables</key>
|
|
83
39
|
<dict>
|
|
84
40
|
<key>OURS_TRANSPORT</key><string>http</string>
|
|
85
41
|
<key>OURS_PORT</key><string>${e.port}</string>
|
|
86
|
-
<key>OURS_BROKER_URL</key><string>${
|
|
87
|
-
<key>OURS_STATE_DIR</key><string>${
|
|
42
|
+
<key>OURS_BROKER_URL</key><string>${U(e.brokerUrl)}</string>
|
|
43
|
+
<key>OURS_STATE_DIR</key><string>${U(e.stateDir)}</string>
|
|
88
44
|
${n}${r} </dict>
|
|
89
45
|
<key>RunAtLoad</key><true/>
|
|
90
46
|
<key>KeepAlive</key><true/>
|
|
91
|
-
<key>StandardOutPath</key><string>${
|
|
92
|
-
<key>StandardErrorPath</key><string>${
|
|
47
|
+
<key>StandardOutPath</key><string>${U(e.logPath??"")}</string>
|
|
48
|
+
<key>StandardErrorPath</key><string>${U(e.logPath??"")}</string>
|
|
93
49
|
</dict>
|
|
94
50
|
</plist>
|
|
95
|
-
`}import{chmodSync as
|
|
96
|
-
`,384)}function
|
|
97
|
-
`);break}if(i===127||i===8){
|
|
98
|
-
`);let n=!1,
|
|
99
|
-
`)})};for(
|
|
100
|
-
`),
|
|
101
|
-
`),
|
|
102
|
-
`)});let
|
|
103
|
-
`),
|
|
51
|
+
`}import{chmodSync as ut,closeSync as gr,existsSync as ft,mkdirSync as yr,openSync as dt,readFileSync as mt,readSync as gt,renameSync as Sr,statSync as hr,unlinkSync as yt,writeFileSync as vr,writeSync as br}from"node:fs";import{spawnSync as le}from"node:child_process";import{dirname as wr}from"node:path";var O=[{value:"openai-compatible",label:"OpenAI-compatible",detail:"an OpenAI-style /v1 transcription endpoint"},{value:"elevenlabs",label:"ElevenLabs",detail:"ElevenLabs speech-to-text"},{value:"deepgram",label:"Deepgram",detail:"Deepgram speech-to-text"},{value:"custom",label:"Custom HTTP endpoint",detail:"a fully specified transcription URL"}],w=class extends Error{constructor(r){super(r);this.reason=r}};function Tr(e){if(!ft(e))return{};let t=JSON.parse(mt(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("config root must be a JSON object");return t}function _r(e){return ft(e)?{exists:!0,text:mt(e,"utf8"),mode:hr(e).mode&511}:{exists:!1}}function Rr(e,t){St(e,`${JSON.stringify(t,null,2)}
|
|
52
|
+
`,384)}function St(e,t,r){yr(wr(e),{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${Date.now()}`;try{vr(n,t,{encoding:"utf8",mode:r,flag:"wx"}),ut(n,r),Sr(n,e),ut(e,r)}catch(s){try{yt(n)}catch{}throw s}}function Ar(e,t){if(!t.exists){try{yt(e)}catch{}return}St(e,t.text,t.mode)}async function Pr(e,t,r,n){let s=_r(e);try{Rr(e,t)}catch{return{ok:!1,stage:"write",rolledBack:!0,daemonRestored:!0}}if(r!=="managed")return{ok:!0,stage:"write"};let o;try{o=n?await n():{ok:!1}}catch{o={ok:!1}}if(o.ok)return{ok:!0,stage:"apply"};try{Ar(e,s)}catch{return{ok:!1,stage:"rollback",rolledBack:!1,daemonRestored:!1}}let i;try{i=n?await n():{ok:!1}}catch{i={ok:!1}}return{ok:!1,stage:i.ok?"apply":"rollback",rolledBack:!0,daemonRestored:i.ok}}function pt(e,t){let r={...e},n=[["provider",t.OURS_STT_PROVIDER],["apiKey",t.OURS_STT_API_KEY],["model",t.OURS_STT_MODEL],["baseUrl",t.OURS_STT_BASE_URL],["language",t.OURS_STT_LANGUAGE]];for(let[s,o]of n)o?.trim()&&(r[s]=o.trim());return r}function kr(e){let t=e.trim();return t.length<8?{ok:!1,reason:"API key must contain at least 8 characters"}:/[\s\x00-\x1f\x7f]/.test(t)?{ok:!1,reason:"API key must not contain whitespace or control characters"}:{ok:!0,value:t}}function Or(){try{return dt("/dev/tty","r+")}catch{if(process.stdin.isTTY&&process.stdout.isTTY)try{return dt("/dev/stdin","r+")}catch{}return null}}function $(e,t){br(e,t)}function Ee(e){let t=Buffer.alloc(1);try{return gt(e,t,0,1,null)===1?t[0]:null}catch(r){throw r.code==="EINTR"?new w("cancel"):r}}function ht(e){let t="";for(let r=0;r<12;r++){let n=Ee(e);if(n===null)break;let s=String.fromCharCode(n);if(t+=s,/[A-Za-z~]$/.test(t))break}return t}function vt(e,t){let r=le("stty",["-g"],{stdio:[e,"pipe","ignore"],encoding:"utf8"}),n=(r.stdout||"").trim();if(r.status!==0||!n)throw new w("unavailable");if(le("stty",["-icanon","-echo","-isig","min","1","time","0"],{stdio:[e,"ignore","ignore"]}).status!==0)throw new w("unavailable");let o=!1,i=()=>{if(o)return;o=!0,le("stty",[n],{stdio:[e,"ignore","ignore"]}).status!==0&&le("stty",["sane"],{stdio:[e,"ignore","ignore"]})};process.once("exit",i);try{return t()}finally{process.removeListener("exit",i),i()}}function $r(e,t,r,n){return vt(e,()=>{$(e,t);let s="";for(;;){let i=Ee(e);if(i===null||i===4)throw new w("eof");if(i===3)throw new w("cancel");if(i===10||i===13){$(e,`
|
|
53
|
+
`);break}if(i===127||i===8){s.length&&(s=s.slice(0,-1),n||$(e,"\b \b"));continue}if(i===27){ht(e);continue}if(i<32||s.length>=16384)continue;let c=String.fromCharCode(i);s+=c,n||$(e,c)}let o=s.trim();return o===""?r:o})}function ue(e,t,r=""){$(e,t);let n=[],s=0;for(;;){let i=Buffer.alloc(1024),c;try{c=gt(e,i,0,i.length,null)}catch(d){throw d.code==="EINTR"?new w("cancel"):d}if(c===0)throw new w("eof");let l=i.subarray(0,c).indexOf(10),u=l>=0?i.subarray(0,l):i.subarray(0,c);if(n.push(u),s+=u.length,s>16384)throw new Error("prompt input too long");if(l>=0)break}let o=Buffer.concat(n).toString("utf8").replace(/\r$/,"").trim();return o===""?r:o}function x(e,t,r="",n=!1){try{return $r(e,t,r,n)}catch(s){if(s instanceof w&&s.reason==="unavailable"&&!n)return ue(e,t,r);throw s}}function Ir(e,t,r){let n=x(e,`${t} ${r?"[Y/n]":"[y/N]"} `,r?"y":"n");return/^y(?:es)?$/i.test(n)}function xr(e,t){let r=O.findIndex(n=>n.value===t);r<0&&(r=0);try{return vt(e,()=>{$(e,`Choose one transcription provider (\u2191/\u2193 or j/k, then Enter; q cancels):
|
|
54
|
+
`);let n=!1,s=()=>{n&&$(e,`\x1B[${O.length}A`),n=!0,O.forEach((o,i)=>{$(e,`\r\x1B[K ${i===r?">":" "} ${i===r?"(*)":"( )"} ${o.label} \u2014 ${o.detail}
|
|
55
|
+
`)})};for(s();;){let o=Ee(e);if(o===null||o===4)throw new w("eof");if(o===3||o===113||o===81)throw new w("cancel");if(o===10||o===13)return $(e,`
|
|
56
|
+
`),O[r].value;if(o>=49&&o<=52)r=o-49;else if(o===107||o===75)r=(r-1+O.length)%O.length;else if(o===106||o===74)r=(r+1)%O.length;else if(o===27){let i=ht(e);i==="[A"||i==="OA"?r=(r-1+O.length)%O.length:(i==="[B"||i==="OB")&&(r=(r+1)%O.length)}else continue;s()}})}catch(n){if(!(n instanceof w)||n.reason!=="unavailable")throw n;$(e,`Choose one transcription provider:
|
|
57
|
+
`),O.forEach((o,i)=>{$(e,` ${i+1}. ${o.label} \u2014 ${o.detail}
|
|
58
|
+
`)});let s=ue(e,`Select 1-${O.length}: `);if(!/^[1-4]$/.test(s))throw new w("cancel");return O[Number(s)-1].value}}function Er(e){let t=e.stt;return t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{}}async function bt(e){let t=e.env??process.env,r=e.stdout??(i=>process.stdout.write(i)),n=(i="")=>r(`${i}
|
|
59
|
+
`),s=e.daemonState??"stopped",o=null;try{let i;try{i=Tr(e.configFile)}catch{return n(`voice setup: ${e.configFile} is not valid JSON; no changes made.`),1}let c=Er(i),l=se(pt(c,t)),u=t.OURS_STT_API_KEY?.trim()?"environment":c.apiKey?.trim()?"config":"missing";if(o=t.OURS_ASSUME_YES?null:Or(),n(`ours-mcp voice-setup \u2014 ${e.configFile}`),l.ready){if(n(`voice transcription is already ready (${l.provider}; API key from ${u}).`),o===null)return 0;if(!Ir(o,"Change the current voice settings?",!1))return n("kept the current voice settings; no changes made."),0}else if(n("Voice transcription is not ready. This command keeps the provider key hidden."),o===null)return n("No interactive terminal is available; no changes made."),n("Run `ours-mcp voice-setup` in a terminal, or configure OURS_STT_* environment values."),0;n("");let d=String(t.OURS_STT_PROVIDER||c.provider||"").trim().toLowerCase(),f=xr(o,d),p=String(t.OURS_STT_MODEL||c.model||"").trim(),g=String(t.OURS_STT_BASE_URL||c.baseUrl||"").trim(),v=String(c.custom?.url||"").trim();f==="openai-compatible"?(g=x(o,`Provider /v1 base URL${g?` [${g}]`:""}: `,g),p=x(o,`Model name (sent verbatim)${p?` [${p}]`:""}: `,p)):f==="elevenlabs"?(p=x(o,`ElevenLabs model id${p?` [${p}]`:""}: `,p),g=x(o,`Custom base URL (Enter for provider default)${g?` [${g}]`:""}: `,g)):f==="deepgram"?(p=x(o,`Model (optional; Enter for provider default)${p?` [${p}]`:""}: `,p),g=x(o,`Custom base URL (optional)${g?` [${g}]`:""}: `,g)):(v=x(o,`Full transcription endpoint URL${v?` [${v}]`:""}: `,v),p=x(o,`Model (optional unless URL contains {model})${p?` [${p}]`:""}: `,p));let j=t.OURS_STT_API_KEY?.trim(),b=String(c.apiKey||"").trim();if(j)n("API key: using OURS_STT_API_KEY from the environment; it will not be copied to config.");else{let L=b?"Provider API key [configured; Enter keeps it]: ":"Provider API key (input hidden): ",ne;try{ne=x(o,L,b,!0)}catch(Y){if(!(Y instanceof w)||Y.reason!=="unavailable")throw Y;if($(o,`
|
|
104
60
|
Secure hidden input is unavailable on this terminal.
|
|
105
|
-
`)
|
|
106
|
-
`),
|
|
61
|
+
`),$(o,`Visible fallback will echo the token on screen and may leave it in scrollback.
|
|
62
|
+
`),ue(o,"Type SHOW to enter the token visibly, or press Enter to cancel: ")!=="SHOW")throw new w("cancel");ne=ue(o,"Provider API key (VISIBLE): ",b)}let H=kr(ne);if(!H.ok)return n(`Voice setup was not saved: ${H.reason}.`),1;b=H.value}let R={...c,provider:f,...b?{apiKey:b}:{},...p?{model:p}:{},...g?{baseUrl:g}:{},...f==="custom"&&v?{custom:{...c.custom??{},url:v}}:{}},I=se(pt(R,t));if(!I.ready)return n(`Voice setup was not saved: ${I.reason}.`),1;if(e.dryRun)return n(`voice transcription would be configured (${f}); API key stays hidden.`),n("dry-run: config, daemon, and existing settings were not changed."),0;let C={...i,stt:R};s==="managed"&&n("Restarting ours-mcp to apply and verify voice transcription\u2026");let A=await Pr(e.configFile,C,s,e.apply);return!A.ok&&A.stage==="write"?(n(`Could not write ${e.configFile}; the prior config is intact.`),1):s==="stopped"?(n(`voice transcription configured (${f}); API key saved in mode-0600 config.`),n("The daemon is stopped; run `ours-mcp start` to apply it."),0):s==="external"?(n(`voice transcription configured (${f}); API key saved in mode-0600 config.`),n("The daemon has no managed PID; restart its external launcher to apply the new settings."),0):A.ok?(n(`voice transcription: ready (${f}).`),n("API key saved in mode-0600 config and never displayed."),0):A.rolledBack?(n("Voice readiness check failed; restored the exact prior config."),A.daemonRestored?(n("The prior config and daemon state were restored; voice setup was not changed."),2):(n("The prior config is restored, but the daemon did not restart; run `ours-mcp status`."),2)):(n("Voice setup failed and automatic config rollback also failed; inspect the config before restarting."),2)}catch(i){return i instanceof w?i.reason==="cancel"?(n(""),n("voice setup cancelled; no configuration changes were made."),130):i.reason==="eof"?(n(""),n("voice setup ended at EOF; no configuration changes were made."),1):(n("Secure interactive input is unavailable on this terminal; no changes made."),1):(n("voice setup failed unexpectedly; no credential was displayed."),1)}finally{if(o!==null)try{gr(o)}catch{}}}var wt=`ours-mcp voice-setup \u2014 configure voice transcription securely
|
|
107
63
|
|
|
108
64
|
Usage: ours-mcp voice-setup [--dry-run]
|
|
109
65
|
|
|
@@ -118,12 +74,12 @@ exact prior config.
|
|
|
118
74
|
|
|
119
75
|
Headless automation remains environment-driven through OURS_STT_PROVIDER,
|
|
120
76
|
OURS_STT_API_KEY, OURS_STT_MODEL, OURS_STT_BASE_URL, and OURS_STT_LANGUAGE.
|
|
121
|
-
Exit 2 means restart/readiness failed after a write and rollback was attempted.`;import*as
|
|
122
|
-
`}async function
|
|
123
|
-
`),
|
|
124
|
-
`),
|
|
125
|
-
`),
|
|
126
|
-
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();
|
|
127
|
-
${
|
|
128
|
-
`))if(
|
|
129
|
-
`),
|
|
77
|
+
Exit 2 means restart/readiness failed after a write and rollback was attempted.`;import*as K from"node:fs";import{join as Ur}from"node:path";var Nr="startup-progress.json",Cr=1,Tt={initializing:"Initializing daemon",wrapper:"Starting protocol runtime",registrar:"Starting local contact book",identities:"Restoring identities",reconciliation:"Reconciling restored identities",server:"Opening local API",ready:"Daemon ready",failed:"Daemon startup failed"};function Lr(e){return Ur(e,Nr)}function Dr(e){return typeof e=="string"&&Object.hasOwn(Tt,e)}function _t(e){try{let t=JSON.parse(K.readFileSync(Lr(e),"utf8"));return t.version!==Cr||!Number.isInteger(t.pid)||(t.pid??0)<=0||typeof t.bootId!="string"||!t.bootId||!Dr(t.phase)||!Number.isFinite(t.startedAt)||!Number.isFinite(t.updatedAt)||(t.completed!==void 0||t.total!==void 0)&&(!Number.isInteger(t.completed)||!Number.isInteger(t.total)||(t.completed??-1)<0||(t.total??-1)<0||(t.completed??0)>(t.total??0))?null:t}catch{return null}}function Ue(e){let t=Tt[e.phase];return e.phase==="identities"&&e.completed!==void 0&&e.total!==void 0?`${t} ${e.completed}/${e.total}`:t}function Rt(e,t){let r=`startup: ${Ue(e)}`;return t?`\r${r}\x1B[K`:`${r}
|
|
78
|
+
`}async function At(e){let t=e.now??Date.now,r=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),n=t(),s=n,o=-1,i="",c=null;for(;;){if(await e.isReady())return{ok:!0,elapsedMs:t()-n,lastProgress:c};let l=e.readProgress();if(l?.pid===e.pid){c=l,l.updatedAt>o&&(o=l.updatedAt,s=t());let p=`${l.phase}:${l.completed??""}:${l.total??""}`;if(p!==i&&(i=p,e.onProgress?.(l)),l.phase==="failed")return{ok:!1,reason:"daemon-reported-failure",elapsedMs:t()-n,lastProgress:c}}if(!e.isProcessAlive())return{ok:!1,reason:"process-exited",elapsedMs:t()-n,lastProgress:c};let u=t()-n;if(u>=e.absoluteMs)return{ok:!1,reason:"absolute-timeout",elapsedMs:u,lastProgress:c};if(t()-s>=e.inactivityMs)return{ok:!1,reason:"inactivity-timeout",elapsedMs:u,lastProgress:c};let d=e.absoluteMs-u,f=e.inactivityMs-(t()-s);await r(Math.max(1,Math.min(e.pollMs,d,f)))}}if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;m.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var ge,Fe=null;try{let e=et(process.argv.slice(2));ge=e.application,process.argv.splice(2,process.argv.length-2,...e.argv)}catch(e){Fe=e}var Ot=process.argv[2]??"help",Mt=Ot==="proxy"||Ot==="watch",Vt=Mt?oe(ge):null,_=Oe({application:Mt?ge:void 0}),P=_.stateDir,h=_.port,ye=()=>{let e=W(_,{generate:!1})?.token??null;return e?{"x-ours-api-token":e}:{}},te=_.brokerUrl,G=E(P,"daemon.pid"),Z=E(P,"daemon.log"),N=Mr(import.meta.url),a=(...e)=>process.stdout.write(`${e.join(" ")}
|
|
79
|
+
`),y=(...e)=>process.stderr.write(`${e.join(" ")}
|
|
80
|
+
`),J="0.17.0-nightly.18",$t=e=>Number.isInteger(e)&&e>1,It=Number(process.env.OURS_CLIENT_PID),Ve=$t(It)?It:$t(process.ppid)?process.ppid:process.pid,jt=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${Ve}`,jr=(process.env.OURS_BIND_IDENTITY??"").trim()||void 0;async function Me(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),n=await fetch(`http://127.0.0.1:${h}${e}`,{signal:t.signal});if(clearTimeout(r),n.ok){let s=await n.json();if(s&&typeof s.version=="string")return s}}catch{}return null}function xt(e){if(a(` cli: v${J}`),e?.version){let t=e.version!==J;a(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${J}`:""))}else a(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var Se=e=>new Promise(t=>setTimeout(t,e));function Br(){try{let e=parseInt(m.readFileSync(G,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function fe(e){try{if(process.kill(e,0),process.platform==="linux")try{if(it(m.readFileSync(`/proc/${e}/stat`,"utf8")))return!1}catch{try{process.kill(e,0)}catch{return!1}}return!0}catch{return!1}}function re(){let e=Br();if(e&&fe(e))return e;if(e)try{m.rmSync(G,{force:!0})}catch{}return null}function V(e,t=1e3){return new Promise(r=>{let n=Fr({host:"127.0.0.1",port:e}),s=o=>{n.destroy(),r(o)};n.setTimeout(t),n.once("connect",()=>s(!0)),n.once("timeout",()=>s(!1)),n.once("error",()=>s(!1))})}async function Kr(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await V(e))return!0;await Se(400)}return!1}function je(e,t){let r=Number(process.env[e]||"");return Number.isFinite(r)&&r>0?r:t}var Bt=je("OURS_TEST_STARTUP_ABSOLUTE_MS",18e4),Kt=je("OURS_TEST_STARTUP_INACTIVITY_MS",3e4),Jt=je("OURS_TEST_STARTUP_POLL_MS",400);async function Jr(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Math.min(1e3,Jt));try{let n=await fetch(`http://127.0.0.1:${e}/identities`,{signal:t.signal,headers:ye()}),s=n.ok;try{await n.body?.cancel()}catch{}return s}catch{return!1}finally{clearTimeout(r)}}function Et(e){return e<1e3?`${Math.round(e)}ms`:e%6e4===0?`${e/6e4}m`:`${Math.round(e/1e3)}s`}function Gr(e,t){let r=t?` Last phase: ${Ue(t)}.`:"";return e==="process-exited"||e==="daemon-reported-failure"?`daemon exited before becoming ready.${r}`:e==="inactivity-timeout"?`daemon startup made no observable progress for ${Et(Kt)}.${r} The process is still running, but startup is stalled.`:`daemon startup did not finish within ${Et(Bt)}.${r} The bounded wait expired.`}async function Ut(){let e=re();if(e){a(`ours-mcp is already running (pid ${e}, port ${h}).`);return}m.mkdirSync(P,{recursive:!0});let t=m.openSync(Z,"a"),r=Lt(process.execPath,[N,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(h),OURS_BROKER_URL:te,OURS_STATE_DIR:P}});r.unref(),r.pid||(y("failed to spawn the daemon."),process.exit(1)),m.writeFileSync(G,String(r.pid)),a(`starting ours-mcp (pid ${r.pid})\u2026`);let n=!!process.stderr.isTTY,s=!1,o=await At({pid:r.pid,absoluteMs:Bt,inactivityMs:Kt,pollMs:Jt,isProcessAlive:()=>fe(r.pid),isReady:()=>Jr(h),readProgress:()=>_t(P),onProgress:i=>{s=!0,process.stderr.write(Rt(i,n))}});s&&n&&process.stderr.write(`
|
|
81
|
+
`),o.ok?(a(`ours-mcp is up: API on http://localhost:${h} (MCP is the "ours-mcp proxy" connector, not this port)`),a(` broker: ${te}`),a(` state: ${P}`),a(` logs: ${Z}`)):(y(`${Gr(o.reason,o.lastProgress)} Check ${Z}.`),process.exit(1))}async function Hr(){if(!await V(h)){if(!re()){m.mkdirSync(P,{recursive:!0});let e=m.openSync(Z,"a"),t=Lt(process.execPath,[N,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(h),OURS_BROKER_URL:te,OURS_STATE_DIR:P}});if(t.unref(),t.pid)try{m.writeFileSync(G,String(t.pid))}catch{}}await Kr(h)}}async function me(){let e=re();if(!e){a("ours-mcp is not running.");return}a(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){y(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&fe(e);t++)await Se(200);if(fe(e)){y(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{m.rmSync(G,{force:!0})}catch{}a("stopped.")}async function Yr(){let e=re();if(!e){if(await V(h)){let n=await Me();a("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),a(` api: http://localhost:${h} (reachable)`),xt(n);return}a("ours-mcp: stopped"),a(` cli: v${J}`),process.exitCode=1;return}let t=await V(h),r=t?await Me():null;a("ours-mcp: running"),a(` pid: ${e}`),a(` api: http://localhost:${h} ${t?"(reachable)":"(port not answering!)"}`),a(` broker: ${te}`),a(` state: ${P}`),a(` logs: ${Z}`),xt(r)}async function qr(){if(a(`ours-mcp v${J}`),await V(h)){let e=await Me();e?.version?a(`running daemon: v${e.version}`+(e.version!==J?" (differs \u2014 restart to update)":"")):a("running daemon: version unknown (predates /version)")}else a("daemon: not running")}async function zr(){let e=Oe(),t=F();a(`ours-mcp setup \u2014 ${t}`),a("Enter a value, or press Enter to keep the current [bracketed] one."),a("");let r=pe({input:process.stdin,output:process.stdout}),n;try{let d=async(Ke,Je)=>{let Ge=(await r.question(` ${Ke} [${Je}]: `)).trim();return Ge===""?Je:Ge},f=await d("broker URL",e.brokerUrl),p=await d("HTTP port",String(e.port)),g=await d("state dir",e.stateDir),v=await d("GC interval (ms)",String(e.gcIntervalMs)),j=await d("proxy auto-starts daemon (true/false)",String(e.autoStart)),b=await d("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility);a(""),a(" Voice-message transcription (STT). Leave provider empty to keep it off \u2014"),a(" agents then deterministically tell users voice messages cannot be read."),a(" No provider or model is assumed; model strings pass to your provider verbatim.");let R=(await r.question(` STT provider (openai-compatible / elevenlabs / deepgram / custom, empty=off) [${e.stt?.provider??""}]: `)).trim()||(e.stt?.provider??""),I=e.stt?.model??"",C=e.stt?.baseUrl??"";R&&(I=await d("STT model (verbatim, e.g. whisper-large-v3-turbo / scribe_v1 / nova-2)",I),C=await d("STT base URL (required for openai-compatible; empty = provider default)",C),a(" (API key is not echoed here. Run `ours-mcp voice-setup` for guided hidden input,"),a(" or set OURS_STT_API_KEY for environment-only secret injection.)"));let A=parseInt(p,10);(!Number.isFinite(A)||A<=0)&&(y(`invalid port: ${p}`),process.exit(1));let L=parseInt(v,10);(!Number.isFinite(L)||L<=0)&&(y(`invalid GC interval: ${v}`),process.exit(1));let ne=j.toLowerCase()==="true"||j==="1",H=b.trim().toLowerCase();ie.includes(H)||(y(`invalid visibility: ${b} (expected one of ${ie.join(", ")})`),process.exit(1));let Y=R?{...e.stt??{},provider:R,...I?{model:I}:{},...C?{baseUrl:C}:{}}:e.stt;n={brokerUrl:f,port:A,stateDir:Ft(g),gcIntervalMs:L,autoStart:ne,apiVisibility:H,...e.apiToken?{apiToken:e.apiToken}:{},...Y?{stt:Y}:{}}}finally{r.close()}nt(n),a(""),a(`wrote ${t} (mode 0600):`);let s={...n,...n.apiToken?{apiToken:"[redacted]"}:{},...n.stt?{stt:{...n.stt,...n.stt.apiKey?{apiKey:"[redacted]"}:{}}}:{}};a(JSON.stringify(s,null,2));let o=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART","OURS_API_VISIBILITY","OURS_API_TOKEN","OURS_STT_PROVIDER","OURS_STT_API_KEY","OURS_STT_MODEL","OURS_STT_BASE_URL","OURS_STT_LANGUAGE"].filter(d=>process.env[d]!==void 0);o.length&&(a(""),a(`note: these env vars are set and OVERRIDE the file at runtime: ${o.join(", ")}`));let i=re();if(!i)return;let c=pe({input:process.stdin,output:process.stdout}),l=!1;try{let d=(await c.question(`
|
|
82
|
+
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();l=d==="y"||d==="yes"}finally{c.close()}if(!l){a("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await me();let u=ee(process.execPath,[N,"start"],{stdio:"inherit"});u.status!==0&&process.exit(u.status??1)}function Wr(e){let t=se(_.stt),r=_.stt?.provider?.trim().toLowerCase()||null,n=process.env.OURS_STT_API_KEY?.trim()?"environment":_.stt?.apiKey?.trim()?"config":"missing",s=t.ready?{ready:!0,provider:t.provider,apiKey:"configured",keySource:n}:{ready:!1,provider:r,apiKey:n==="missing"?"missing":"configured",keySource:n,reason:t.reason};if(e.includes("--json")){a(JSON.stringify(s));return}s.ready?a(`voice transcription: ready (${s.provider}; API key from ${s.keySource})`):a(`voice transcription: not ready \u2014 ${s.reason}`)}async function Zr(e){if(e.includes("--help")||e.includes("-h")){a(wt);return}let t=new Set(["--dry-run"]);if(e.filter(i=>!t.has(i)).length){y("voice-setup: unsupported command-line option or argument"),y("The provider key is never accepted as a CLI argument. Run `ours-mcp voice-setup --help`."),process.exitCode=1;return}let n=re()!==null,s=await V(h),o=await bt({configFile:F(),env:process.env,dryRun:e.includes("--dry-run"),daemonState:n?"managed":s?"external":"stopped",apply:async()=>{let i=ee(process.execPath,[N,"restart"],{stdio:"inherit"});if(i.error||i.status!==0)return{ok:!1};let c=ee(process.execPath,[N,"voice-status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(c.error||c.status!==0)return{ok:!1};try{return{ok:JSON.parse(c.stdout||"{}").ready===!0}}catch{return{ok:!1}}}});o!==0&&(process.exitCode=o)}function Ce(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Le(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function Xr(e){let t=Le(e,"--name"),r=Ce(e,"--force-bind","--no-force-bind"),n=Ce(e,"--local-book","--no-local-book"),s=Ce(e,"--auto-accept-local","--no-auto-accept-local"),o=e.includes("--overwrite"),i=e.includes("--print"),c=Le(e,"--path")??Le(e,"--dir")??process.cwd(),l=t!==void 0||r.set||n.set||s.set||i,u;if(l?((!t||!t.trim())&&(y("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),u={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:s.value??!0}):u=await Qr(),i){a(JSON.stringify(ce(u),null,2));return}let d=$e(c);if(!o&&m.existsSync(d)){l&&(y(`define-local-identity-file: ${d} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let p=pe({input:process.stdin,output:process.stdout}),g=!1;try{let v=(await p.question(`
|
|
83
|
+
${d} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();g=v==="y"||v==="yes"}finally{p.close()}if(!g){a("aborted \u2014 nothing written.");return}}let f=ot(c,u,!0);a(""),a(`wrote ${f}:`),a(JSON.stringify(ce(u),null,2))}async function Qr(){a("ours-mcp define-local-identity-file \u2014 interactive"),a(`Answer the prompts; the result is written to ${E(process.cwd(),ae)}.`),a("");let e=pe({input:process.stdin,output:process.stdout});try{let t=async(i,c)=>{let l=c?"Y/n":"y/N",u=(await e.question(` ${i} [${l}]: `)).trim().toLowerCase();return u===""?c:u==="y"||u==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||a(" (name is required)");let n=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),s=await t("Add to the host-local contact book?",!0),o=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:n,exposeLocal:s,localAutoAccept:o}}finally{e.close()}}async function en(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(y('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await V(h)||(y(`create-root: the daemon is not running on port ${h} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new Vr({url:`http://127.0.0.1:${h}`,apiToken:W(_,{generate:!1})?.token,leaseToken:jt,clientPid:Ve});try{let n=await r.createRootIdentity({name:t,bio:"",exposeLocal:!1,localAutoAccept:!0,skipIfRootExists:!0}),s=n.adopted.length>0?` Adopted ${n.adopted.length} existing identit${n.adopted.length===1?"y":"ies"} as role(s): ${n.adopted.join(", ")}.`:"",o=n.failed.length>0?` FAILED to adopt: ${n.failed.join(", ")} (see daemon log).`:"";n.hierarchy!=="root"&&(y(`create-root: expected a root, got ${n.hierarchy} under "${n.underRoot??"?"}" \u2014 refusing to report success.`),process.exit(1)),a(`Created root identity "${n.info.name}" (${n.info.cid}) and bound it to this session.${s}${o}`)}catch(n){let s=n instanceof kt?n.message.split(/\n\nAsk the user\b/)[0].replace(/^create_root_identity failed: /,"").trim():String(n instanceof Error?n.message:n);if(n instanceof kt&&/a root identity already exists/i.test(s)){a(`create-root: ${s.split("\u2014")[0].trim()} \u2014 nothing to do.`);return}y(`create-root failed: ${s}`),process.exit(1)}}function Gt(e,t){t.event==="message_received"?a(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="file_received"?a(`[${e}] new file ${t.filename??"?"} from ${t.from??"?"}`+(t.bytes!==void 0?` (${t.bytes} B)`:"")+(t.file_id!==void 0?` (#${t.file_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="local_contact_request"?a(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"&&a(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`)}function M(e){y(`ours-mcp watch: ${e}`),process.exit(1)}async function tn(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${h}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?Ft(n.stateDir):P}}catch{}return null}var rn=e=>`http://127.0.0.1:${h}/identities/${encodeURIComponent(e)}/notifications`;async function Nt(e){let t=async s=>{let o=new AbortController,i=setTimeout(()=>o.abort(),35e3),c;try{c=await fetch(`${rn(e)}?since=${s}`,{headers:ye(),signal:o.signal})}finally{clearTimeout(i)}if(c.status===401&&M(`daemon rejected the API token (401) for identity "${e}". Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode).`),!c.ok)throw new Error(`daemon returned HTTP ${c.status}`);return await c.json()},r=null,n=0;for(;;)try{r===null&&(r=(await t("tip")).cursor??0);let s=await t(String(r));if(n=0,Array.isArray(s.events))for(let o of s.events)Gt(e,o);typeof s.cursor=="number"&&(r=s.cursor)}catch(s){n=Math.min(n+1e3,5e3),y(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(s?.message??s)}), retrying\u2026`),await Se(n)}}async function nn(e){if(e){await Nt(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${h}/identities`,{headers:ye()});if(r.status===401&&M("daemon rejected the API token (401). Set OURS_API_TOKEN or run watch as the daemon owner."),r.ok){let n=await r.json();for(let s of n.identities??[]){let o=typeof s?.name=="string"?s.name:void 0;o&&!t.has(o)&&(t.add(o),Nt(o).catch(i=>{t.delete(o),y(`ours-mcp watch: stream for "${o}" ended (${String(i?.message??i)}); will re-arm`)}))}}}catch{}await Se(3e3)}}var De=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function on(e,t){try{m.readdirSync(e)}catch(i){M(`cannot watch \u2014 the daemon API is unreachable AND ${e} is not readable (${i?.code??i}). On a multi-user host, run watch as the daemon owner, or enable the daemon API (start the daemon) so watch can stream over HTTP.`)}if(t)try{m.readdirSync(E(e,t))}catch(i){M(`cannot watch identity "${t}" \u2014 ${E(e,t)} is not readable (${i?.code??i}). Is the daemon running and the name correct?`)}let r=new Map,n=i=>{let c;try{c=m.readdirSync(e,{withFileTypes:!0}).filter(l=>l.isDirectory()).map(l=>l.name)}catch(l){De(l)&&M(`lost read access to ${e} (${l.code}) \u2014 cannot watch.`);return}for(let l of c){if(t&&l!==t)continue;let u=E(e,l,"notifications.log"),d;try{d=m.statSync(u).size}catch(g){De(g)&&M(`cannot read ${u} (${g.code}) \u2014 cannot watch identity "${l}".`);continue}let f=r.get(u);if(f===void 0&&(f=i?d:0,r.set(u,f),i))continue;if(d<=f){d<f&&r.set(u,d);continue}let p;try{let g=m.openSync(u,"r"),v=Buffer.alloc(d-f);m.readSync(g,v,0,v.length,f),m.closeSync(g),p=v.toString("utf8")}catch(g){De(g)&&M(`cannot read ${u} (${g.code}) \u2014 cannot watch identity "${l}".`);continue}r.set(u,d);for(let g of p.split(`
|
|
84
|
+
`))if(g.trim())try{Gt(l,JSON.parse(g))}catch{}}};y(`ours-mcp watch: daemon API unreachable \u2014 falling back to file poll of ${e} (Ctrl-C to stop)`),n(!0);let s=setInterval(()=>n(!1),1e3),o=()=>{clearInterval(s),process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o)}async function sn(){try{let e=await fetch(`http://127.0.0.1:${h}/identities`,{headers:ye()});return e.status===401&&M("daemon rejected the API token (401). Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode)."),e.status===404?"file":e.ok?"api":"file"}catch{return"file"}}async function an(e){await Re(Vt,_,W(_,{generate:!1})?.token);let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await tn()!==null&&await sn()==="api"){y(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${h} (Ctrl-C to stop)`),await nn(e);return}on(P,e)}var k=_.serviceName??"",X=at(k),Be=xe(k);function Ht(){let e=B(k);return e.ok||(y(`invalid service name ${JSON.stringify(k)}: ${e.reason}`),y(' set OURS_SERVICE_NAME (or "serviceName" in config.json) to a valid name, or unset it for the shared daemon.'),process.exit(1)),e.name}function Yt(){return E(Dt(),".config","systemd","user",X)}function qt(){return E(Dt(),"Library","LaunchAgents",`${Be}.plist`)}function Q(e,t){return ee(e,t,{stdio:"inherit"}).status===0}function cn(){let e=Yt();m.mkdirSync(de(e),{recursive:!0});let t=ct({instance:k,configPath:k?F():void 0,port:h,brokerUrl:te,stateDir:P,execPath:process.execPath,self:N});m.writeFileSync(e,t),a(`wrote ${e}`),Q("systemctl",["--user","daemon-reload"]),Q("systemctl",["--user","enable","--now",X])||(y("failed to enable/start the service via systemctl --user."),process.env.XDG_RUNTIME_DIR||(y(`hint: no user runtime dir \u2014 enable linger: sudo loginctl enable-linger ${Ne().username}`),y(" (if linger is already on: export XDG_RUNTIME_DIR=/run/user/$(id -u))")),process.exit(1)),Q("loginctl",["enable-linger",Ne().username])||(y("warning: could not enable linger \u2014 the daemon may not start until you log in."),y(` run manually: loginctl enable-linger ${Ne().username}`)),a(""),a("ours-mcp installed as a systemd user service and started."),k&&a(` instance: ${k} (its own unit \u2014 the shared ours.service is untouched)`),a(` status: systemctl --user status ${X}`),a(` logs: journalctl --user -u ${X} -f`),a(` remove: ${zt()}`)}function zt(){return k?`OURS_SERVICE_NAME=${k} ours-mcp uninstall-service`:"ours-mcp uninstall-service"}function ln(){Q("systemctl",["--user","disable","--now",X]);let e=Yt();try{m.rmSync(e,{force:!0}),a(`removed ${e}`)}catch(t){y(`failed to remove ${e}: ${String(t)}`)}Q("systemctl",["--user","daemon-reload"]),a(`ours-mcp service uninstalled (${X}).`)}function un(){let e=qt();m.mkdirSync(de(e),{recursive:!0});let t=lt({instance:k,configPath:k?F():void 0,port:h,brokerUrl:te,stateDir:P,execPath:process.execPath,self:N,logPath:Z});m.writeFileSync(e,t),a(`wrote ${e}`);let r=`gui/${process.getuid()}`;ee("launchctl",["bootout",r,e],{stdio:"ignore"}),Q("launchctl",["bootstrap",r,e])||(y("failed to load the launchd agent."),process.exit(1)),a(""),a("ours-mcp installed as a launchd agent and started."),k&&a(` instance: ${k} (label ${Be} \u2014 the shared agent is untouched)`),a(` remove: ${zt()}`)}function dn(){let e=qt(),t=`gui/${process.getuid()}`;ee("launchctl",["bootout",t,e],{stdio:"ignore"});try{m.rmSync(e,{force:!0}),a(`removed ${e}`)}catch(r){y(`failed to remove ${e}: ${String(r)}`)}a(`ours-mcp service uninstalled (${Be}).`)}async function pn(){if(Ht(),await me(),process.platform==="linux")return cn();if(process.platform==="darwin")return un();y(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function fn(){if(Ht(),process.platform==="linux")return ln();if(process.platform==="darwin")return dn();y(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function Ct(){a("ours-mcp \u2014 daemon for the ours MCP server"),a(""),a("Usage: ours-mcp <command>"),a(" start start in the background; show structured progress until ready"),a(" stop stop the running daemon"),a(" restart stop then start; healthy slow restores may take up to 3 minutes"),a(" status show whether the daemon is running (incl. CLI + running-daemon version)"),a(" version print the CLI version and the running daemon version (GET /version)"),a(" setup interactively edit the config file (broker / port / state dir / gc)"),a(" voice-setup [--dry-run] securely choose a provider and configure its hidden API key"),a(" voice-status [--json] check voice-transcription readiness (never prints the API key)"),a(" serve run in the foreground (used by start; handy for debugging)"),a(" watch [--application claude-code|codex|hermes] [identity] stream new inbound wake lines"),a(" proxy [--application claude-code|codex|hermes] per-session stdio shim \u2192 daemon"),a(""),a(' create-root "<name>" create THE root human identity (one per host) via the running'),a(" daemon \u2014 quiet no-op if a root already exists (installer seam)"),a(""),a(" define-local-identity-file write a .ours-identity workspace pin"),a(" interactive (default): 4-question survey, writes to CWD"),a(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),a(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),a(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),a(""),a(" install-service install + start a boot-persistent service (systemd/launchd)"),a(" uninstall-service stop + remove that service"),a(" a named instance (OURS_SERVICE_NAME / config serviceName) owns its OWN unit,"),a(" so an isolated second daemon never overwrites the shared one. Default: shared."),a(""),a("Config precedence (per field): env var > config.json > default."),a(" Client --application: explicit env > Nightly registry association > legacy config/default."),a(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),a(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000), OURS_AUTOSTART (off), OURS_SERVICE_NAME (none)"),a("(install-service bakes the resolved config values into the service definition.)")}async function mn(){if(Fe)throw Fe;let e=process.argv[2]??"help";switch(tt(ge,e),e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),m.mkdirSync(P,{recursive:!0}),m.writeFileSync(G,String(process.pid));{let r=()=>{try{m.rmSync(G,{force:!0})}catch{}};process.on("exit",r);for(let n of["SIGTERM","SIGINT"])process.on(n,()=>{r(),process.exit(0)})}await import(Pt(E(de(N),"index.js")).href);break;case"start":await Ut();break;case"stop":await me();break;case"restart":await me(),await Ut();break;case"status":await Yr();break;case"version":case"--version":case"-v":await qr();break;case"setup":await zr();break;case"voice-status":case"stt-status":Wr(process.argv.slice(3));break;case"voice-setup":case"stt-setup":await Zr(process.argv.slice(3));break;case"create-root":await en(process.argv.slice(3));break;case"define-local-identity-file":await Xr(process.argv.slice(3));break;case"watch":await an(process.argv[3]);break;case"proxy":await Re(Vt,_,W(_,{generate:!1})?.token),!_.autoStart&&!await V(h)&&(y(`ours-mcp daemon is not running on port ${h} \u2014 start it with \`ours-mcp start\`.`),y("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1));let{runConnector:t}=await import(Pt(E(de(N),"connector.js")).href);await t({url:`http://127.0.0.1:${h}`,ensureDaemon:_.autoStart?Hr:void 0,apiToken:W(_,{generate:!1})?.token,leaseToken:jt,clientPid:Ve,version:J,bindIdentity:jr});break;case"install-service":await pn();break;case"uninstall-service":fn();break;case"help":case"--help":case"-h":Ct();break;default:y(`unknown command: ${e}
|
|
85
|
+
`),Ct(),process.exit(1)}}mn().catch(e=>{y(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});
|