@reddb-io/red-skills 2.58.0 → 2.59.0

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.
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var c_=Object.create;var Pi=Object.defineProperty;var u_=Object.getOwnPropertyDescriptor;var l_=Object.getOwnPropertyNames;var d_=Object.getPrototypeOf,f_=Object.prototype.hasOwnProperty;var dt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ou=(e,t)=>{for(var r in t)Pi(e,r,{get:t[r],enumerable:!0})},p_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of l_(t))!f_.call(e,o)&&o!==r&&Pi(e,o,{get:()=>t[o],enumerable:!(n=u_(t,o))||n.enumerable});return e};var zi=(e,t,r)=>(r=e!=null?c_(d_(e)):{},p_(t||!e||!e.__esModule?Pi(r,"default",{value:e,enumerable:!0}):r,e));var Yr=w(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Jr=class{};U._CodeOrName=Jr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var It=class extends Jr{constructor(t){if(super(),!U.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}}};U.Name=It;var Ne=class extends Jr{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 It&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Ne;U.nil=new Ne("");function ip(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ws(r,t[n]),r.push(e[++n]);return new Ne(r)}U._=ip;var Gs=new Ne("+");function sp(e,...t){let r=[Qr(e[0])],n=0;for(;n<t.length;)r.push(Gs),Ws(r,t[n]),r.push(Gs,Qr(e[++n]));return hv(r),new Ne(r)}U.str=sp;function Ws(e,t){t instanceof Ne?e.push(...t._items):t instanceof It?e.push(t):e.push(_v(t))}U.addCodeArg=Ws;function hv(e){let t=1;for(;t<e.length-1;){if(e[t]===Gs){let r=gv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function gv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof It||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 It))return`"${e}${t.slice(1)}`}function yv(e,t){return t.emptyStr()?e:e.emptyStr()?t:sp`${e}${t}`}U.strConcat=yv;function _v(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Qr(Array.isArray(e)?e.join(","):e)}function wv(e){return new Ne(Qr(e))}U.stringify=wv;function Qr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Qr;function bv(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new Ne(`.${e}`):ip`[${e}]`}U.getProperty=bv;function vv(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new Ne(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=vv;function $v(e){return new Ne(e.toString())}U.regexpCode=$v});var Ys=w(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.ValueScope=Ee.ValueScopeName=Ee.Scope=Ee.varKinds=Ee.UsedValueState=void 0;var Se=Yr(),Js=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},yo;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(yo||(Ee.UsedValueState=yo={}));Ee.varKinds={const:new Se.Name("const"),let:new Se.Name("let"),var:new Se.Name("var")};var _o=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Se.Name?t:this.name(t)}name(t){return new Se.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}}};Ee.Scope=_o;var wo=class extends Se.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Se._)`.${new Se.Name(r)}[${n}]`}};Ee.ValueScopeName=wo;var xv=(0,Se._)`\n`,Qs=class extends _o{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?xv:Se.nil}}get(){return this._scope}name(t){return new wo(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:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),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,Se._)`${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 i=Se.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,yo.Started);let u=r(l);if(u){let d=this.opts.es5?Ee.varKinds.var:Ee.varKinds.const;i=(0,Se._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Se._)`${i}${u}${this.opts._n}`;else throw new Js(l);c.set(l,yo.Completed)})}return i}};Ee.ValueScope=Qs});var N=w(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.or=C.and=C.not=C.CodeGen=C.operators=C.varKinds=C.ValueScopeName=C.ValueScope=C.Scope=C.Name=C.regexpCode=C.stringify=C.getProperty=C.nil=C.strConcat=C.str=C._=void 0;var B=Yr(),Le=Ys(),gt=Yr();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return gt._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return gt.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return gt.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return gt.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return gt.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return gt.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return gt.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return gt.Name}});var xo=Ys();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return xo.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return xo.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return xo.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return xo.varKinds}});C.operators={GT:new B._Code(">"),GTE:new B._Code(">="),LT:new B._Code("<"),LTE:new B._Code("<="),EQ:new B._Code("==="),NEQ:new B._Code("!=="),NOT:new B._Code("!"),OR:new B._Code("||"),AND:new B._Code("&&"),ADD:new B._Code("+")};var st=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Xs=class extends st{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Le.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=er(this.rhs,t,r)),this}get names(){return this.rhs instanceof B._CodeOrName?this.rhs.names:{}}},bo=class extends st{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 B.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=er(this.rhs,t,r),this}get names(){let t=this.lhs instanceof B.Name?{}:{...this.lhs.names};return $o(t,this.rhs)}},ea=class extends bo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ta=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ra=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},na=class extends st{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},oa=class extends st{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=er(this.code,t,r),this}get names(){return this.code instanceof B._CodeOrName?this.code.names:{}}},Xr=class extends st{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 i=n[o];i.optimizeNames(t,r)||(kv(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Nt(t,r.names),{})}},at=class extends Xr{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ia=class extends Xr{},Xt=class extends at{};Xt.kind="else";var At=class e extends at{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 Xt(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ap(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=er(this.condition,t,r),this}get names(){let t=super.names;return $o(t,this.condition),this.else&&Nt(t,this.else.names),t}};At.kind="if";var Ot=class extends at{};Ot.kind="for";var sa=class extends Ot{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=er(this.iteration,t,r),this}get names(){return Nt(super.names,this.iteration.names)}},aa=class extends Ot{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Le.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=$o(super.names,this.from);return $o(t,this.to)}},vo=class extends Ot{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=er(this.iterable,t,r),this}get names(){return Nt(super.names,this.iterable.names)}},en=class extends at{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)}};en.kind="func";var tn=class extends Xr{render(t){return"return "+super.render(t)}};tn.kind="return";var ca=class extends at{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&&Nt(t,this.catch.names),this.finally&&Nt(t,this.finally.names),t}},rn=class extends at{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};rn.kind="catch";var nn=class extends at{render(t){return"finally"+super.render(t)}};nn.kind="finally";var ua=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new Le.Scope({parent:t}),this._nodes=[new ia]}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 i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new Xs(t,i,n)),i}const(t,r,n){return this._def(Le.varKinds.const,t,r,n)}let(t,r,n){return this._def(Le.varKinds.let,t,r,n)}var(t,r,n){return this._def(Le.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new bo(t,r,n))}add(t,r){return this._leafNode(new ea(t,C.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==B.nil&&this._leafNode(new oa(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,B.addCodeArg)(r,o));return r.push("}"),new B._Code(r)}if(t,r,n){if(this._blockNode(new At(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 At(t))}else(){return this._elseNode(new Xt)}endIf(){return this._endBlockNode(At,Xt)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new sa(t),r)}forRange(t,r,n,o,i=this.opts.es5?Le.varKinds.var:Le.varKinds.let){let s=this._scope.toName(t);return this._for(new aa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Le.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof B.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,B._)`${s}.length`,a=>{this.var(i,(0,B._)`${s}[${a}]`),n(i)})}return this._for(new vo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Le.varKinds.var:Le.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,B._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new vo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Ot)}label(t){return this._leafNode(new ta(t))}break(t){return this._leafNode(new ra(t))}return(t){let r=new tn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(tn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ca;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new rn(i),r(i)}return n&&(this._currNode=o.finally=new nn,this.code(n)),this._endBlockNode(rn,nn)}throw(t){return this._leafNode(new na(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=B.nil,n,o){return this._blockNode(new en(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(en)}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 At))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}};C.CodeGen=ua;function Nt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function $o(e,t){return t instanceof B._CodeOrName?Nt(e,t.names):e}function er(e,t,r){if(e instanceof B.Name)return n(e);if(!o(e))return e;return new B._Code(e._items.reduce((i,s)=>(s instanceof B.Name&&(s=n(s)),s instanceof B._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof B._Code&&i._items.some(s=>s instanceof B.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function kv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ap(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,B._)`!${la(e)}`}C.not=ap;var Sv=cp(C.operators.AND);function Ev(...e){return e.reduce(Sv)}C.and=Ev;var Tv=cp(C.operators.OR);function Pv(...e){return e.reduce(Tv)}C.or=Pv;function cp(e){return(t,r)=>t===B.nil?r:r===B.nil?t:(0,B._)`${la(t)} ${e} ${la(r)}`}function la(e){return e instanceof B.Name?e:(0,B._)`(${e})`}});var L=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;var H=N(),zv=Yr();function Rv(e){let t={};for(let r of e)t[r]=!0;return t}D.toHash=Rv;function Iv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(dp(e,t),!fp(t,e.self.RULES.all))}D.alwaysValidSchema=Iv;function dp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||hp(e,`unknown keyword: "${i}"`)}D.checkUnknownRules=dp;function fp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}D.schemaHasRules=fp;function Av(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}D.schemaHasRulesButRef=Av;function Ov({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,H._)`${r}`}return(0,H._)`${e}${t}${(0,H.getProperty)(n)}`}D.schemaRefOrVal=Ov;function Nv(e){return pp(decodeURIComponent(e))}D.unescapeFragment=Nv;function Cv(e){return encodeURIComponent(fa(e))}D.escapeFragment=Cv;function fa(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=fa;function pp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=pp;function Dv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}D.eachItem=Dv;function up({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof H.Name?(i instanceof H.Name?e(o,i,s):t(o,i,s),s):i instanceof H.Name?(t(o,s,i),i):r(i,s);return a===H.Name&&!(c instanceof H.Name)?n(o,c):c}}D.mergeEvaluated={props:up({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,H._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,H._)`${r} || {}`).code((0,H._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,H._)`${r} || {}`),pa(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:mp}),items:up({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,H._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,H._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function mp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&pa(e,r,t),r}D.evaluatedPropsToName=mp;function pa(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}D.setEvaluated=pa;var lp={};function jv(e,t){return e.scopeValue("func",{ref:t,code:lp[t.code]||(lp[t.code]=new zv._Code(t.code))})}D.useFunc=jv;var da;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(da||(D.Type=da={}));function Mv(e,t,r){if(e instanceof H.Name){let n=t===da.Num;return r?n?(0,H._)`"[" + ${e} + "]"`:(0,H._)`"['" + ${e} + "']"`:n?(0,H._)`"/" + ${e}`:(0,H._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,H.getProperty)(e).toString():"/"+fa(e)}D.getErrorPath=Mv;function hp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=hp});var ct=w(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});var he=N(),qv={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};ma.default=qv});var on=w(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=N(),ko=L(),ve=ct();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Bv(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=_p(e,t,r);n??(s||a)?gp(i,c):yp(o,(0,Z._)`[${c}]`)}ge.reportError=Bv;function Lv(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=_p(e,t,r);gp(o,a),i||s||yp(n,ve.default.vErrors)}ge.reportExtraError=Lv;function Zv(e,t){e.assign(ve.default.errors,t),e.if((0,Z._)`${ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${ve.default.vErrors}.length`,t),()=>e.assign(ve.default.vErrors,null)))}ge.resetErrorsCount=Zv;function Uv({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,ve.default.errors,a=>{e.const(s,(0,Z._)`${ve.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(ve.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=Uv;function gp(e,t){let r=e.const("err",t);e.if((0,Z._)`${ve.default.vErrors} === null`,()=>e.assign(ve.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${ve.default.vErrors}.push(${r})`),e.code((0,Z._)`${ve.default.errors}++`)}function yp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Ct={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function _p(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:Fv(e,t,r)}function Fv(e,t,r={}){let{gen:n,it:o}=e,i=[Vv(o,r),Kv(e,r)];return Hv(e,t,i),n.object(...i)}function Vv({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,ko.getErrorPath)(t,ko.Type.Str)}`:e;return[ve.default.instancePath,(0,Z.strConcat)(ve.default.instancePath,r)]}function Kv({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,ko.getErrorPath)(r,ko.Type.Str)}`),[Ct.schemaPath,o]}function Hv(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Ct.keyword,o],[Ct.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Ct.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ct.schema,s],[Ct.parentSchema,(0,Z._)`${u}${d}`],[ve.default.data,i]),l&&n.push([Ct.propertyName,l])}});var bp=w(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.boolOrEmptySchema=tr.topBoolOrEmptySchema=void 0;var Gv=on(),Wv=N(),Jv=ct(),Qv={message:"boolean schema is false"};function Yv(e){let{gen:t,schema:r,validateName:n}=e;r===!1?wp(e,!1):typeof r=="object"&&r.$async===!0?t.return(Jv.default.data):(t.assign((0,Wv._)`${n}.errors`,null),t.return(!0))}tr.topBoolOrEmptySchema=Yv;function Xv(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),wp(e)):r.var(t,!0)}tr.boolOrEmptySchema=Xv;function wp(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,Gv.reportError)(o,Qv,void 0,t)}});var ha=w(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.getRules=rr.isJSONType=void 0;var e0=["string","number","integer","boolean","null","object","array"],t0=new Set(e0);function r0(e){return typeof e=="string"&&t0.has(e)}rr.isJSONType=r0;function n0(){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:{}}}rr.getRules=n0});var ga=w(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function o0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&vp(e,n)}yt.schemaHasRulesForType=o0;function vp(e,t){return t.rules.some(r=>$p(e,r))}yt.shouldUseGroup=vp;function $p(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))}yt.shouldUseRule=$p});var sn=w(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var i0=ha(),s0=ga(),a0=on(),O=N(),xp=L(),nr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(nr||(ye.DataType=nr={}));function c0(e){let t=kp(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}ye.getSchemaTypes=c0;function kp(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(i0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=kp;function u0(e,t){let{gen:r,data:n,opts:o}=e,i=l0(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,s0.schemaHasRulesForType)(e,t[0]));if(s){let a=_a(t,n,o.strictNumbers,nr.Wrong);r.if(a,()=>{i.length?d0(e,t,i):wa(e)})}return s}ye.coerceAndCheckDataType=u0;var Sp=new Set(["string","number","integer","boolean","null"]);function l0(e,t){return t?e.filter(r=>Sp.has(r)||t==="array"&&r==="array"):[]}function d0(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,O._)`typeof ${o}`),a=n.let("coerced",(0,O._)`undefined`);i.coerceTypes==="array"&&n.if((0,O._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,O._)`${o}[0]`).assign(s,(0,O._)`typeof ${o}`).if(_a(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,O._)`${a} !== undefined`);for(let l of r)(Sp.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),wa(e),n.endIf(),n.if((0,O._)`${a} !== undefined`,()=>{n.assign(o,a),f0(e,a)});function c(l){switch(l){case"string":n.elseIf((0,O._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,O._)`"" + ${o}`).elseIf((0,O._)`${o} === null`).assign(a,(0,O._)`""`);return;case"number":n.elseIf((0,O._)`${s} == "boolean" || ${o} === null
5
- || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,O._)`+${o}`);return;case"integer":n.elseIf((0,O._)`${s} === "boolean" || ${o} === null
6
- || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,O._)`+${o}`);return;case"boolean":n.elseIf((0,O._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,O._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,O._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,O._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,O._)`[${o}]`)}}}function f0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,O._)`${t} !== undefined`,()=>e.assign((0,O._)`${t}[${r}]`,n))}function ya(e,t,r,n=nr.Correct){let o=n===nr.Correct?O.operators.EQ:O.operators.NEQ,i;switch(e){case"null":return(0,O._)`${t} ${o} null`;case"array":i=(0,O._)`Array.isArray(${t})`;break;case"object":i=(0,O._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,O._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,O._)`typeof ${t} ${o} ${e}`}return n===nr.Correct?i:(0,O.not)(i);function s(a=O.nil){return(0,O.and)((0,O._)`typeof ${t} == "number"`,a,r?(0,O._)`isFinite(${t})`:O.nil)}}ye.checkDataType=ya;function _a(e,t,r,n){if(e.length===1)return ya(e[0],t,r,n);let o,i=(0,xp.toHash)(e);if(i.array&&i.object){let s=(0,O._)`typeof ${t} != "object"`;o=i.null?s:(0,O._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=O.nil;i.number&&delete i.integer;for(let s in i)o=(0,O.and)(o,ya(s,t,r,n));return o}ye.checkDataTypes=_a;var p0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,O._)`{type: ${e}}`:(0,O._)`{type: ${t}}`};function wa(e){let t=m0(e);(0,a0.reportError)(t,p0)}ye.reportTypeError=wa;function m0(e){let{gen:t,data:r,schema:n}=e,o=(0,xp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Tp=w(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.assignDefaults=void 0;var or=N(),h0=L();function g0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Ep(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Ep(e,i,o.default))}So.assignDefaults=g0;function Ep(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,or._)`${i}${(0,or.getProperty)(t)}`;if(o){(0,h0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,or._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,or._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,or._)`${a} = ${(0,or.stringify)(r)}`)}});var Ce=w(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=N(),ba=L(),_t=ct(),y0=L();function _0(e,t){let{gen:r,data:n,it:o}=e;r.if($a(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}K.checkReportMissingProp=_0;function w0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)($a(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}K.checkMissingProp=w0;function b0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=b0;function Pp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Pp;function va(e,t,r){return(0,X._)`${Pp(e)}.call(${t}, ${r})`}K.isOwnProperty=va;function v0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${va(e,t,r)}`:o}K.propertyInData=v0;function $a(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(va(e,t,r))):o}K.noPropertyInData=$a;function zp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=zp;function $0(e,t){return zp(t).filter(r=>!(0,ba.alwaysValidSchema)(e,t[r]))}K.schemaProperties=$0;function x0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[_t.default.instancePath,(0,X.strConcat)(_t.default.instancePath,i)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];s.opts.dynamicRef&&d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}K.callValidateCode=x0;var k0=(0,X._)`new RegExp`;function S0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?k0:(0,y0.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=S0;function E0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:ba.Type.Num},i),t.if((0,X.not)(i),a)})}}K.validateArray=E0;function T0(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,ba.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=T0});var Ap=w(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var $e=N(),Dt=ct(),P0=Ce(),z0=on();function R0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Ip(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:$e.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Ye.macroKeywordCode=R0;function I0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;O0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Ip(n,o,l),d=n.let("valid");e.block$data(d,f),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function f(){if(t.errors===!1)h(),t.modifying&&Rp(e),_(()=>e.error());else{let b=t.async?p():m();t.modifying&&Rp(e),_(()=>A0(e,b))}}function p(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,$e._)`await `),v=>n.assign(d,!1).if((0,$e._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,$e._)`${v}.errors`),()=>n.throw(v))),b}function m(){let b=(0,$e._)`${u}.errors`;return n.assign(b,null),h($e.nil),b}function h(b=t.async?(0,$e._)`await `:$e.nil){let v=c.opts.passContext?Dt.default.this:Dt.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,$e._)`${b}${(0,P0.callValidateCode)(e,u,v,$)}`,t.modifying)}function _(b){var v;n.if((0,$e.not)((v=t.valid)!==null&&v!==void 0?v:d),b)}}Ye.funcKeywordCode=I0;function Rp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,$e._)`${n.parentData}[${n.parentDataProperty}]`))}function A0(e,t){let{gen:r}=e;r.if((0,$e._)`Array.isArray(${t})`,()=>{r.assign(Dt.default.vErrors,(0,$e._)`${Dt.default.vErrors} === null ? ${t} : ${Dt.default.vErrors}.concat(${t})`).assign(Dt.default.errors,(0,$e._)`${Dt.default.vErrors}.length`),(0,z0.extendErrors)(e)},()=>e.error())}function O0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ip(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,$e.stringify)(r)})}function N0(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")}Ye.validSchemaType=N0;function C0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ye.validateKeywordUsage=C0});var Np=w(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.extendSubschemaMode=wt.extendSubschemaData=wt.getSubschema=void 0;var Xe=N(),Op=L();function D0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){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,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}${(0,Xe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Op.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}wt.getSubschema=D0;function j0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){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:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,Xe._)`${t.data}${(0,Xe.getProperty)(r)}`,!0);c(f),e.errorPath=(0,Xe.str)`${l}${(0,Op.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Xe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Xe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}wt.extendSubschemaData=j0;function M0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}wt.extendSubschemaMode=M0});var xa=w((Z1,Cp)=>{"use strict";Cp.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,i;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(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var jp=w((U1,Dp)=>{"use strict";var bt=Dp.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(){};Eo(t,n,o,e,"",e)};bt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bt.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 Eo(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in bt.arrayKeywords)for(var f=0;f<d.length;f++)Eo(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in bt.propsKeywords){if(d&&typeof d=="object")for(var p in d)Eo(e,t,r,d[p],o+"/"+u+"/"+q0(p),i,o,u,n,p)}else(u in bt.keywords||e.allKeys&&!(u in bt.skipKeywords))&&Eo(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function q0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var an=w(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var B0=L(),L0=xa(),Z0=jp(),U0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function F0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ka(e):t?Mp(e)<=t:!1}Te.inlineRef=F0;var V0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ka(e){for(let t in e){if(V0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(ka)||typeof r=="object"&&ka(r))return!0}return!1}function Mp(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!U0.has(r)&&(typeof e[r]=="object"&&(0,B0.eachItem)(e[r],n=>t+=Mp(n)),t===1/0))return 1/0}return t}function qp(e,t="",r){r!==!1&&(t=ir(t));let n=e.parse(t);return Bp(e,n)}Te.getFullPath=qp;function Bp(e,t){return e.serialize(t).split("#")[0]+"#"}Te._getFullPath=Bp;var K0=/#\/?$/;function ir(e){return e?e.replace(K0,""):""}Te.normalizeId=ir;function H0(e,t,r){return r=ir(r),e.resolve(t,r)}Te.resolveUrl=H0;var G0=/^[a-z_][-a-z0-9._]*$/i;function W0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ir(e[r]||t),i={"":o},s=qp(n,o,!1),a={},c=new Set;return Z0(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=b.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[f]=_;function b($){let T=this.opts.uriResolver.resolve;if($=ir(_?T(_,$):$),c.has($))throw u($);c.add($);let R=this.refs[$];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?l(d,R.schema,$):$!==ir(h)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=h),$}function v($){if(typeof $=="string"){if(!G0.test($))throw new Error(`invalid anchor "${$}"`);b.call(this,`#${$}`)}}}),a;function l(d,f,p){if(f!==void 0&&!L0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=W0});var ln=w(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getData=vt.KeywordCxt=vt.validateFunctionCode=void 0;var Vp=bp(),Lp=sn(),Ea=ga(),To=sn(),J0=Tp(),un=Ap(),Sa=Np(),S=N(),A=ct(),Q0=an(),ut=L(),cn=on();function Y0(e){if(Gp(e)&&(Wp(e),Hp(e))){t$(e);return}Kp(e,()=>(0,Vp.topBoolOrEmptySchema)(e))}vt.validateFunctionCode=Y0;function Kp({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Zp(r,o)}`),e$(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${X0(o)}`,n.$async,()=>e.code(Zp(r,o)).code(i))}function X0(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function e$(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function t$(e){let{schema:t,opts:r,gen:n}=e;Kp(e,()=>{r.$comment&&t.$comment&&Qp(e),s$(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&r$(e),Jp(e),u$(e)})}function r$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Zp(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function n$(e,t){if(Gp(e)&&(Wp(e),Hp(e))){o$(e,t);return}(0,Vp.boolOrEmptySchema)(e,t)}function Hp({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 Gp(e){return typeof e.schema!="boolean"}function o$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Qp(e),a$(e),c$(e);let i=n.const("_errs",A.default.errors);Jp(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function Wp(e){(0,ut.checkUnknownRules)(e),i$(e)}function Jp(e,t){if(e.opts.jtd)return Up(e,[],!1,t);let r=(0,Lp.getSchemaTypes)(e.schema),n=(0,Lp.coerceAndCheckDataType)(e,r);Up(e,r,!n,t)}function i$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function s$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function a$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Q0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function c$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qp({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function u$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&l$(e),t.return((0,S._)`${A.default.errors} === 0`))}function l$({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function Up(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(i,u))){o.block(()=>Xp(e,"$ref",u.all.$ref.definition));return}c.jtd||d$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ea.shouldUseGroup)(i,f)&&(f.type?(o.if((0,To.checkDataType)(f.type,s,c.strictNumbers)),Fp(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,To.reportTypeError)(e)),o.endIf()):Fp(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Fp(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,J0.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ea.shouldUseRule)(n,i)&&Xp(e,i.keyword,i.definition,t.type)})}function d$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(f$(e,t),e.opts.allowUnionTypes||p$(e,t),m$(e,e.dataTypes))}function f$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Yp(e.dataTypes,r)||Ta(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),g$(e,t)}}function p$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ta(e,"use allowUnionTypes to allow union type keyword")}function m$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ea.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>h$(t,s))&&Ta(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function h$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Yp(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function g$(e,t){let r=[];for(let n of e.dataTypes)Yp(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ta(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}var Po=class{constructor(t,r,n){if((0,un.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,ut.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",em(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,un.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",A.default.errors))}result(t,r,n){this.failResult((0,S.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,S.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,S._)`${r} !== undefined && (${(0,S.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?cn.reportExtraError:cn.reportError)(this,this.def.error,r)}$dataError(){(0,cn.reportError)(this,this.def.$dataError||cn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,cn.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=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,To.checkDataTypes)(c,r,i.opts.strictNumbers,To.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,Sa.getSubschema)(this.it,t);(0,Sa.extendSubschemaData)(n,this.it,t),(0,Sa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return n$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ut.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ut.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,S.Name)),!0}};vt.KeywordCxt=Po;function Xp(e,t,r,n){let o=new Po(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,un.funcKeywordCode)(o,r):"macro"in r?(0,un.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,un.funcKeywordCode)(o,r)}var y$=/^\/(?:[^~]|~0|~1)*$/,_$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function em(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!y$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=_$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ut.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}vt.getData=em});var zo=w(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var Pa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};za.default=Pa});var dn=w(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});var Ra=an(),Ia=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ra.resolveUrl)(t,r,n),this.missingSchema=(0,Ra.normalizeId)((0,Ra.getFullPath)(t,this.missingRef))}};Aa.default=Ia});var Io=w(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.resolveSchema=De.getCompilingSchema=De.resolveRef=De.compileSchema=De.SchemaEnv=void 0;var Ze=N(),w$=zo(),jt=ct(),Ue=an(),tm=L(),b$=ln(),sr=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,Ue.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};De.SchemaEnv=sr;function Na(e){let t=rm.call(this,e);if(t)return t;let r=(0,Ue.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ze.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:w$.default,code:(0,Ze._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:jt.default.data,parentData:jt.default.parentData,parentDataProperty:jt.default.parentDataProperty,dataNames:[jt.default.data],dataPathArr:[Ze.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ze.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ze.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ze._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,b$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(jt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${jt.default.self}`,`${jt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Ze.Name?void 0:m,items:h instanceof Ze.Name?void 0:h,dynamicProps:m instanceof Ze.Name,dynamicItems:h instanceof Ze.Name},p.source&&(p.source.evaluated=(0,Ze.stringify)(p.evaluated))}return e.validate=p,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}De.compileSchema=Na;function v$(e,t,r){var n;r=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=k$.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new sr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=$$.call(this,i)}De.resolveRef=v$;function $$(e){return(0,Ue.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Na.call(this,e)}function rm(e){for(let t of this._compilations)if(x$(t,e))return t}De.getCompilingSchema=rm;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]||Ro.call(this,e,t)}function Ro(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ue._getFullPath)(this.opts.uriResolver,r),o=(0,Ue.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Oa.call(this,r,e);let i=(0,Ue.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Ro.call(this,e,s);return typeof a?.schema!="object"?void 0:Oa.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Na.call(this,s),i===(0,Ue.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ue.resolveUrl)(this.opts.uriResolver,o,l)),new sr({schema:a,schemaId:c,root:e,baseId:o})}return Oa.call(this,r,s)}}De.resolveSchema=Ro;var S$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Oa(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,tm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!S$.has(a)&&l&&(t=(0,Ue.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,tm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Ro.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new sr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var nm=w((W1,E$)=>{E$.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 ja=w((J1,um)=>{"use strict";var T$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),im=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),Ca=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),P$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Da(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 z$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function om(e){return e.length=0,!0}function R$(e,t,r){if(e.length){let n=Da(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function I$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=R$;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=om}else{o.push(l);continue}}return o.length&&(a===om?r.zone=o.join(""):s?n.push(o.join("")):n.push(Da(o))),r.address=n.join(""),r}function am(e){if(A$(e,":")<2)return{host:e,isIPV6:!1};let t=I$(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 O$(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"},C$=/[@/?#:]/g,D$=/[@/?#]/g;function cm(e,t){let r=t?D$:C$;return r.lastIndex=0,e.replace(r,n=>N$[n])}function j$(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(Ca(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&sm(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function M$(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(Ca(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&sm(i)?t+=i:t+="%"+o,r+=2;continue}}P$(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(Ca(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function B$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!im(r)){let n=am(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=cm(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}um.exports={nonSimpleDomain:z$,recomposeAuthority:B$,reescapeHostDelimiters:cm,normalizePercentEncoding:j$,normalizePathEncoding:M$,escapePreservingEscapes:q$,removeDotSegments:O$,isIPv4:im,isUUID:T$,normalizeIPv6:am,stringArrayToHexStripped:Da}});var mm=w((Q1,pm)=>{"use strict";var{isUUID:L$}=ja(),Z$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,U$=["http","https","ws","wss","urn","urn:uuid"];function F$(e){return U$.indexOf(e)!==-1}function Ma(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 lm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function dm(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 V$(e){return e.secure=Ma(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function K$(e){if((e.port===(Ma(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 H$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Z$);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}`,i=qa(o);e.path=void 0,i&&(e=i.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}`,i=qa(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}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 J$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var fm={scheme:"http",domainHost:!0,parse:lm,serialize:dm},Q$={scheme:"https",domainHost:fm.domainHost,parse:lm,serialize:dm},Ao={scheme:"ws",domainHost:!0,parse:V$,serialize:K$},Y$={scheme:"wss",domainHost:Ao.domainHost,parse:Ao.parse,serialize:Ao.serialize},X$={scheme:"urn",parse:H$,serialize:G$,skipNormalize:!0},ex={scheme:"urn:uuid",parse:W$,serialize:J$,skipNormalize:!0},Oo={http:fm,https:Q$,ws:Ao,wss:Y$,urn:X$,"urn:uuid":ex};Object.setPrototypeOf(Oo,null);function qa(e){return e&&(Oo[e]||Oo[e.toLowerCase()])||void 0}pm.exports={wsIsSecure:Ma,SCHEMES:Oo,isValidSchemeName:F$,getSchemeHandler:qa}});var bm=w((Y1,No)=>{"use strict";var{normalizeIPv6:tx,removeDotSegments:fn,recomposeAuthority:rx,normalizePercentEncoding:nx,normalizePathEncoding:ox,escapePreservingEscapes:ix,reescapeHostDelimiters:sx,isIPv4:ax,nonSimpleDomain:cx}=ja(),{SCHEMES:ux,getSchemeHandler:gm}=mm();function lx(e,t){return typeof e=="string"?e=hx(e,t):typeof e=="object"&&(e=ar(Mt(e,t),t)),e}function dx(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=ym(ar(e,n),ar(t,n),n,!0);return n.skipEscape=!0,Mt(o,n)}function ym(e,t,r,n){let o={};return n||(e=ar(Mt(e,r),r),t=ar(Mt(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=fn(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=fn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=fn(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=fn(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 fx(e,t,r){let n=hm(e,r),o=hm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Mt(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=[],i=gm(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=nx(r.path):(r.path=ix(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=rx(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=fn(a)),s===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 px=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mx(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 _m(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,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(px);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=mx(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(ax(n.host)===!1){let u=tx(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=gm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&cx(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=sx(unescape(n.host),i))),n.path&&(n.path=ox(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function ar(e,t){return _m(e,t).parsed}function hx(e,t){return wm(e,t).normalized}function wm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=_m(e,t);return{normalized:n?e:Mt(r,t),malformedAuthorityOrPort:n}}function hm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=wm(e,t);return n?void 0:r}if(typeof e=="object")return Mt(e,t)}var Ba={SCHEMES:ux,normalize:lx,resolve:dx,resolveComponent:ym,equal:fx,serialize:Mt,parse:ar};No.exports=Ba;No.exports.default=Ba;No.exports.fastUri=Ba});var $m=w(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var vm=bm();vm.code='require("ajv/dist/runtime/uri").default';La.default=vm});var Rm=w(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var gx=ln();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return gx.KeywordCxt}});var cr=N();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return cr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return cr.CodeGen}});var yx=zo(),Tm=dn(),_x=ha(),pn=Io(),wx=N(),mn=an(),Co=sn(),Ua=L(),xm=nm(),bx=$m(),Pm=(e,t)=>new RegExp(e,t);Pm.code="new RegExp";var vx=["removeAdditional","useDefaults","coerceTypes"],$x=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xx={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."},kx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},km=200;function Sx(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,b,v,$,T,R,we,Re,Kt,Ei;let Tr=e.strict,Ti=(t=e.code)===null||t===void 0?void 0:t.optimize,Iu=Ti===!0||Ti===void 0?1:Ti||0,Au=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Pm,a_=(o=e.uriResolver)!==null&&o!==void 0?o:bx.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Tr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Tr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Tr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Tr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Tr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Iu,regExp:Au}:{optimize:Iu,regExp:Au},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:km,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:km,meta:(b=e.meta)!==null&&b!==void 0?b:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(T=e.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(we=e.validateSchema)!==null&&we!==void 0?we:!0,validateFormats:(Re=e.validateFormats)!==null&&Re!==void 0?Re:!0,unicodeRegExp:(Kt=e.unicodeRegExp)!==null&&Kt!==void 0?Kt:!0,int32range:(Ei=e.int32range)!==null&&Ei!==void 0?Ei:!0,uriResolver:a_}}var hn=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,...Sx(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new wx.ValueScope({scope:{},prefixes:$x,es5:r,lines:n}),this.logger=Ix(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,_x.getRules)(),Sm.call(this,xx,t,"NOT SUPPORTED"),Sm.call(this,kx,t,"DEPRECATED","warn"),this._metaOpts=zx.call(this),t.formats&&Tx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Px.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Ex.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=xm;n==="id"&&(o={...xm},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(u,d){await i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Tm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,mn.normalizeId)(r||i),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 i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=Em.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new pn.SchemaEnv({schema:{},schemaId:n});if(r=pn.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=Em.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,mn.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(Ox.call(this,n,r),!r)return(0,Ua.eachItem)(n,i=>Za.call(this,i)),this;Cx.call(this,r);let o={...r,type:(0,Co.getJSONTypes)(r.type),schemaType:(0,Co.getJSONTypes)(r.schemaType)};return(0,Ua.eachItem)(n,o.type.length===0?i=>Za.call(this,i,o):i=>o.type.forEach(s=>Za.call(this,i,o,s))),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(i=>i.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,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=zm(u))}}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,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=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,mn.normalizeId)(s||n);let l=mn.getSchemaRefs.call(this,t,n);return c=new pn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!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):pn.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{pn.compileSchema.call(this,t)}finally{this.opts=r}}};hn.ValidationError=yx.default;hn.MissingRefError=Tm.default;fe.default=hn;function Sm(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function Em(e){return e=(0,mn.normalizeId)(e),this.schemas[e]||this.refs[e]}function Ex(){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 Tx(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Px(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 zx(){let e={...this.opts};for(let t of vx)delete e[t];return e}var Rx={log(){},warn(){},error(){}};function Ix(e){if(e===!1)return Rx;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 Ax=/^[a-z_$][a-z0-9_$:-]*$/i;function Ox(e,t){let{RULES:r}=this;if((0,Ua.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Ax.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 Za(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Co.getJSONTypes)(t.type),schemaType:(0,Co.getJSONTypes)(t.schemaType)}};t.before?Nx.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Nx(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 Cx(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=zm(t)),e.validateSchema=this.compile(t,!0))}var Dx={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function zm(e){return{anyOf:[e,Dx]}}});var Im=w(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var jx={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Fa.default=jx});var Cm=w(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.callRef=qt.getValidate=void 0;var Mx=dn(),Am=Ce(),Pe=N(),ur=ct(),Om=Io(),Do=L(),qx={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=Om.resolveRef.call(c,l,o,r);if(u===void 0)throw new Mx.default(n.opts.uriResolver,o,r);if(u instanceof Om.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return jo(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return jo(e,(0,Pe._)`${m}.validate`,l,l.$async)}function f(m){let h=Nm(e,m);jo(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pe.stringify)(m)}:{ref:m}),_=t.name("valid"),b=e.subschema({schema:m,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(b),e.ok(_)}}};function Nm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}qt.getValidate=Nm;function jo(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?ur.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,Am.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Pe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,Am.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Pe._)`${m}.errors`;o.assign(ur.default.vErrors,(0,Pe._)`${ur.default.vErrors} === null ? ${h} : ${ur.default.vErrors}.concat(${h})`),o.assign(ur.default.errors,(0,Pe._)`${ur.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let _=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=Do.mergeEvaluated.props(o,_.props,i.props));else{let b=o.var("props",(0,Pe._)`${m}.evaluated.props`);i.props=Do.mergeEvaluated.props(o,b,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Do.mergeEvaluated.items(o,_.items,i.items));else{let b=o.var("items",(0,Pe._)`${m}.evaluated.items`);i.items=Do.mergeEvaluated.items(o,b,i.items,Pe.Name)}}}qt.callRef=jo;qt.default=qx});var Dm=w(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var Bx=Im(),Lx=Cm(),Zx=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Bx.default,Lx.default];Va.default=Zx});var jm=w(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Mo=N(),$t=Mo.operators,qo={maximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},minimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},exclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},exclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},Ux={message:({keyword:e,schemaCode:t})=>(0,Mo.str)`must be ${qo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Mo._)`{comparison: ${qo[e].okStr}, limit: ${t}}`},Fx={keyword:Object.keys(qo),type:"number",schemaType:"number",$data:!0,error:Ux,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Mo._)`${r} ${qo[t].fail} ${n} || isNaN(${r})`)}};Ka.default=Fx});var Mm=w(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var gn=N(),Vx={message:({schemaCode:e})=>(0,gn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,gn._)`{multipleOf: ${e}}`},Kx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Vx,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,gn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,gn._)`${s} !== parseInt(${s})`;e.fail$data((0,gn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ha.default=Kx});var Bm=w(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});function qm(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}Ga.default=qm;qm.code='require("ajv/dist/runtime/ucs2length").default'});var Lm=w(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var Bt=N(),Hx=L(),Gx=Bm(),Wx={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Bt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Bt._)`{limit: ${e}}`},Jx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Wx,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Bt.operators.GT:Bt.operators.LT,s=o.opts.unicode===!1?(0,Bt._)`${r}.length`:(0,Bt._)`${(0,Hx.useFunc)(e.gen,Gx.default)}(${r})`;e.fail$data((0,Bt._)`${s} ${i} ${n}`)}};Wa.default=Jx});var Zm=w(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Qx=Ce(),Yx=L(),lr=N(),Xx={message:({schemaCode:e})=>(0,lr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,lr._)`{pattern: ${e}}`},ek={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Xx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,lr._)`new RegExp`:(0,Yx.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,lr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,lr._)`!${u}`)}else{let c=(0,Qx.usePattern)(e,o);e.fail$data((0,lr._)`!${c}.test(${r})`)}}};Ja.default=ek});var Um=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var yn=N(),tk={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,yn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,yn._)`{limit: ${e}}`},rk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:tk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?yn.operators.GT:yn.operators.LT;e.fail$data((0,yn._)`Object.keys(${r}).length ${o} ${n}`)}};Qa.default=rk});var Fm=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var _n=Ce(),wn=N(),nk=L(),ok={message:({params:{missingProperty:e}})=>(0,wn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wn._)`{missingProperty: ${e}}`},ik={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ok,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let _=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,nk.checkStrictMode)(s,b,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(wn.nil,d);else for(let p of r)(0,_n.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>f(p,m)),e.ok(m)}else t.if((0,_n.checkMissingProp)(e,r,p)),(0,_n.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,_n.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,_n.propertyInData)(t,o,p,a.ownProperties)),t.if((0,wn.not)(m),()=>{e.error(),t.break()})},wn.nil)}}};Ya.default=ik});var Vm=w(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var bn=N(),sk={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,bn._)`{limit: ${e}}`},ak={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:sk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?bn.operators.GT:bn.operators.LT;e.fail$data((0,bn._)`${r}.length ${o} ${n}`)}};Xa.default=ak});var Bo=w(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Km=xa();Km.code='require("ajv/dist/runtime/equal").default';ec.default=Km});var Hm=w(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var tc=sn(),pe=N(),ck=L(),uk=Bo(),lk={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},dk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:lk,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,tc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),b=(0,tc.checkDataTypes)(l,_,a.opts.strictNumbers,tc.DataType.Wrong),v=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(b,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${v}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${v}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${v}[${_}] = ${m}`)})}function p(m,h){let _=(0,ck.useFunc)(t,uk.default),b=t.name("outer");t.label(b).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(b)})))}}};rc.default=dk});var Gm=w(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var nc=N(),fk=L(),pk=Bo(),mk={message:"must be equal to constant",params:({schemaCode:e})=>(0,nc._)`{allowedValue: ${e}}`},hk={keyword:"const",$data:!0,error:mk,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,nc._)`!${(0,fk.useFunc)(t,pk.default)}(${r}, ${o})`):e.fail((0,nc._)`${i} !== ${r}`)}};oc.default=hk});var Wm=w(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var vn=N(),gk=L(),yk=Bo(),_k={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,vn._)`{allowedValues: ${e}}`},wk={keyword:"enum",schemaType:"array",$data:!0,error:_k,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,gk.useFunc)(t,yk.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=t.const("vSchema",i);u=(0,vn.or)(...o.map((m,h)=>f(p,h)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,p=>t.if((0,vn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,vn._)`${l()}(${r}, ${p}[${m}])`:(0,vn._)`${r} === ${h}`}}};ic.default=wk});var Jm=w(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var bk=jm(),vk=Mm(),$k=Lm(),xk=Zm(),kk=Um(),Sk=Fm(),Ek=Vm(),Tk=Hm(),Pk=Gm(),zk=Wm(),Rk=[bk.default,vk.default,$k.default,xk.default,kk.default,Sk.default,Ek.default,Tk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Pk.default,zk.default];sc.default=Rk});var cc=w($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.validateAdditionalItems=void 0;var Lt=N(),ac=L(),Ik={message:({params:{len:e}})=>(0,Lt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Lt._)`{limit: ${e}}`},Ak={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ik,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ac.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qm(e,n)}};function Qm(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Lt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Lt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,ac.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Lt._)`${a} <= ${t.length}`);r.if((0,Lt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:ac.Type.Num},l),s.allErrors||r.if((0,Lt.not)(l),()=>r.break())})}}$n.validateAdditionalItems=Qm;$n.default=Ak});var uc=w(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.validateTuple=void 0;var Ym=N(),Lo=L(),Ok=Ce(),Nk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Xm(e,"additionalItems",t);r.items=!0,!(0,Lo.alwaysValidSchema)(r,t)&&e.ok((0,Ok.validateArray)(e))}};function Xm(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Lo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Ym._)`${i}.length`);r.forEach((d,f)=>{(0,Lo.alwaysValidSchema)(a,d)||(n.if((0,Ym._)`${l} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(f.strictTuples&&!h){let _=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,Lo.checkStrictMode)(a,_,f.strictTuples)}}}xn.validateTuple=Xm;xn.default=Nk});var eh=w(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Ck=uc(),Dk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ck.validateTuple)(e,"items")};lc.default=Dk});var rh=w(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var th=N(),jk=L(),Mk=Ce(),qk=cc(),Bk={message:({params:{len:e}})=>(0,th.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,th._)`{limit: ${e}}`},Lk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Bk,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,jk.alwaysValidSchema)(n,t)&&(o?(0,qk.validateAdditionalItems)(e,o):e.ok((0,Mk.validateArray)(e)))}};dc.default=Lk});var nh=w(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var je=N(),Zo=L(),Zk={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}}`},Uk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Zk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,je._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Zo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Zo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Zo.alwaysValidSchema)(i,r)){let h=(0,je._)`${u} >= ${s}`;a!==void 0&&(h=(0,je._)`${h} && ${u} <= ${a}`),e.pass(h);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?p(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,je._)`${o}.length > 0`,f)):(t.let(d,!1),f()),e.result(d,()=>e.reset());function f(){let h=t.name("_valid"),_=t.let("count",0);p(h,()=>t.if(h,()=>m(_)))}function p(h,_){t.forRange("i",0,u,b=>{e.subschema({keyword:"contains",dataProp:b,dataPropType:Zo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,je._)`${h}++`),a===void 0?t.if((0,je._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,je._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,je._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};fc.default=Uk});var sh=w(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateSchemaDeps=et.validatePropertyDeps=et.error=void 0;var pc=N(),Fk=L(),kn=Ce();et.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,pc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,pc._)`{property: ${e},
3
+ var c_=Object.create;var Pi=Object.defineProperty;var u_=Object.getOwnPropertyDescriptor;var l_=Object.getOwnPropertyNames;var d_=Object.getPrototypeOf,f_=Object.prototype.hasOwnProperty;var dt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Au=(e,t)=>{for(var r in t)Pi(e,r,{get:t[r],enumerable:!0})},p_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of l_(t))!f_.call(e,o)&&o!==r&&Pi(e,o,{get:()=>t[o],enumerable:!(n=u_(t,o))||n.enumerable});return e};var zi=(e,t,r)=>(r=e!=null?c_(d_(e)):{},p_(t||!e||!e.__esModule?Pi(r,"default",{value:e,enumerable:!0}):r,e));var Yr=w(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Jr=class{};U._CodeOrName=Jr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var It=class extends Jr{constructor(t){if(super(),!U.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}}};U.Name=It;var Ne=class extends Jr{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 It&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Ne;U.nil=new Ne("");function ip(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ws(r,t[n]),r.push(e[++n]);return new Ne(r)}U._=ip;var Gs=new Ne("+");function sp(e,...t){let r=[Qr(e[0])],n=0;for(;n<t.length;)r.push(Gs),Ws(r,t[n]),r.push(Gs,Qr(e[++n]));return hb(r),new Ne(r)}U.str=sp;function Ws(e,t){t instanceof Ne?e.push(...t._items):t instanceof It?e.push(t):e.push(_b(t))}U.addCodeArg=Ws;function hb(e){let t=1;for(;t<e.length-1;){if(e[t]===Gs){let r=gb(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function gb(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof It||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 It))return`"${e}${t.slice(1)}`}function yb(e,t){return t.emptyStr()?e:e.emptyStr()?t:sp`${e}${t}`}U.strConcat=yb;function _b(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Qr(Array.isArray(e)?e.join(","):e)}function wb(e){return new Ne(Qr(e))}U.stringify=wb;function Qr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Qr;function vb(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new Ne(`.${e}`):ip`[${e}]`}U.getProperty=vb;function bb(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new Ne(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=bb;function $b(e){return new Ne(e.toString())}U.regexpCode=$b});var Ys=w(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.ValueScope=Ee.ValueScopeName=Ee.Scope=Ee.varKinds=Ee.UsedValueState=void 0;var Se=Yr(),Js=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},yo;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(yo||(Ee.UsedValueState=yo={}));Ee.varKinds={const:new Se.Name("const"),let:new Se.Name("let"),var:new Se.Name("var")};var _o=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Se.Name?t:this.name(t)}name(t){return new Se.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}}};Ee.Scope=_o;var wo=class extends Se.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Se._)`.${new Se.Name(r)}[${n}]`}};Ee.ValueScopeName=wo;var xb=(0,Se._)`\n`,Qs=class extends _o{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?xb:Se.nil}}get(){return this._scope}name(t){return new wo(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:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),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,Se._)`${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 i=Se.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,yo.Started);let u=r(l);if(u){let d=this.opts.es5?Ee.varKinds.var:Ee.varKinds.const;i=(0,Se._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Se._)`${i}${u}${this.opts._n}`;else throw new Js(l);c.set(l,yo.Completed)})}return i}};Ee.ValueScope=Qs});var N=w(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.or=C.and=C.not=C.CodeGen=C.operators=C.varKinds=C.ValueScopeName=C.ValueScope=C.Scope=C.Name=C.regexpCode=C.stringify=C.getProperty=C.nil=C.strConcat=C.str=C._=void 0;var L=Yr(),Be=Ys(),gt=Yr();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return gt._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return gt.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return gt.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return gt.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return gt.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return gt.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return gt.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return gt.Name}});var xo=Ys();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return xo.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return xo.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return xo.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return xo.varKinds}});C.operators={GT:new L._Code(">"),GTE:new L._Code(">="),LT:new L._Code("<"),LTE:new L._Code("<="),EQ:new L._Code("==="),NEQ:new L._Code("!=="),NOT:new L._Code("!"),OR:new L._Code("||"),AND:new L._Code("&&"),ADD:new L._Code("+")};var st=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Xs=class extends st{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Be.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=er(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},vo=class extends st{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 L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=er(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return $o(t,this.rhs)}},ea=class extends vo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ta=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ra=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},na=class extends st{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},oa=class extends st{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=er(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},Xr=class extends st{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 i=n[o];i.optimizeNames(t,r)||(kb(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Nt(t,r.names),{})}},at=class extends Xr{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ia=class extends Xr{},Xt=class extends at{};Xt.kind="else";var Ot=class e extends at{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 Xt(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ap(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=er(this.condition,t,r),this}get names(){let t=super.names;return $o(t,this.condition),this.else&&Nt(t,this.else.names),t}};Ot.kind="if";var At=class extends at{};At.kind="for";var sa=class extends At{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=er(this.iteration,t,r),this}get names(){return Nt(super.names,this.iteration.names)}},aa=class extends At{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Be.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=$o(super.names,this.from);return $o(t,this.to)}},bo=class extends At{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=er(this.iterable,t,r),this}get names(){return Nt(super.names,this.iterable.names)}},en=class extends at{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)}};en.kind="func";var tn=class extends Xr{render(t){return"return "+super.render(t)}};tn.kind="return";var ca=class extends at{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&&Nt(t,this.catch.names),this.finally&&Nt(t,this.finally.names),t}},rn=class extends at{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};rn.kind="catch";var nn=class extends at{render(t){return"finally"+super.render(t)}};nn.kind="finally";var ua=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Be.Scope({parent:t}),this._nodes=[new ia]}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 i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new Xs(t,i,n)),i}const(t,r,n){return this._def(Be.varKinds.const,t,r,n)}let(t,r,n){return this._def(Be.varKinds.let,t,r,n)}var(t,r,n){return this._def(Be.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new vo(t,r,n))}add(t,r){return this._leafNode(new ea(t,C.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new oa(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,L.addCodeArg)(r,o));return r.push("}"),new L._Code(r)}if(t,r,n){if(this._blockNode(new Ot(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 Ot(t))}else(){return this._elseNode(new Xt)}endIf(){return this._endBlockNode(Ot,Xt)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new sa(t),r)}forRange(t,r,n,o,i=this.opts.es5?Be.varKinds.var:Be.varKinds.let){let s=this._scope.toName(t);return this._for(new aa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Be.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof L.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,L._)`${s}.length`,a=>{this.var(i,(0,L._)`${s}[${a}]`),n(i)})}return this._for(new bo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Be.varKinds.var:Be.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,L._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new bo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(At)}label(t){return this._leafNode(new ta(t))}break(t){return this._leafNode(new ra(t))}return(t){let r=new tn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(tn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ca;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new rn(i),r(i)}return n&&(this._currNode=o.finally=new nn,this.code(n)),this._endBlockNode(rn,nn)}throw(t){return this._leafNode(new na(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=L.nil,n,o){return this._blockNode(new en(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(en)}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 Ot))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}};C.CodeGen=ua;function Nt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function $o(e,t){return t instanceof L._CodeOrName?Nt(e,t.names):e}function er(e,t,r){if(e instanceof L.Name)return n(e);if(!o(e))return e;return new L._Code(e._items.reduce((i,s)=>(s instanceof L.Name&&(s=n(s)),s instanceof L._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof L._Code&&i._items.some(s=>s instanceof L.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function kb(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ap(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${la(e)}`}C.not=ap;var Sb=cp(C.operators.AND);function Eb(...e){return e.reduce(Sb)}C.and=Eb;var Tb=cp(C.operators.OR);function Pb(...e){return e.reduce(Tb)}C.or=Pb;function cp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${la(t)} ${e} ${la(r)}`}function la(e){return e instanceof L.Name?e:(0,L._)`(${e})`}});var B=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;var H=N(),zb=Yr();function Rb(e){let t={};for(let r of e)t[r]=!0;return t}D.toHash=Rb;function Ib(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(dp(e,t),!fp(t,e.self.RULES.all))}D.alwaysValidSchema=Ib;function dp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||hp(e,`unknown keyword: "${i}"`)}D.checkUnknownRules=dp;function fp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}D.schemaHasRules=fp;function Ob(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}D.schemaHasRulesButRef=Ob;function Ab({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,H._)`${r}`}return(0,H._)`${e}${t}${(0,H.getProperty)(n)}`}D.schemaRefOrVal=Ab;function Nb(e){return pp(decodeURIComponent(e))}D.unescapeFragment=Nb;function Cb(e){return encodeURIComponent(fa(e))}D.escapeFragment=Cb;function fa(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=fa;function pp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=pp;function Db(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}D.eachItem=Db;function up({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof H.Name?(i instanceof H.Name?e(o,i,s):t(o,i,s),s):i instanceof H.Name?(t(o,s,i),i):r(i,s);return a===H.Name&&!(c instanceof H.Name)?n(o,c):c}}D.mergeEvaluated={props:up({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,H._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,H._)`${r} || {}`).code((0,H._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,H._)`${r} || {}`),pa(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:mp}),items:up({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,H._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,H._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function mp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&pa(e,r,t),r}D.evaluatedPropsToName=mp;function pa(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}D.setEvaluated=pa;var lp={};function jb(e,t){return e.scopeValue("func",{ref:t,code:lp[t.code]||(lp[t.code]=new zb._Code(t.code))})}D.useFunc=jb;var da;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(da||(D.Type=da={}));function Mb(e,t,r){if(e instanceof H.Name){let n=t===da.Num;return r?n?(0,H._)`"[" + ${e} + "]"`:(0,H._)`"['" + ${e} + "']"`:n?(0,H._)`"/" + ${e}`:(0,H._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,H.getProperty)(e).toString():"/"+fa(e)}D.getErrorPath=Mb;function hp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=hp});var ct=w(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});var he=N(),qb={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};ma.default=qb});var on=w(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=N(),ko=B(),be=ct();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Lb(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=_p(e,t,r);n??(s||a)?gp(i,c):yp(o,(0,Z._)`[${c}]`)}ge.reportError=Lb;function Bb(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=_p(e,t,r);gp(o,a),i||s||yp(n,be.default.vErrors)}ge.reportExtraError=Bb;function Zb(e,t){e.assign(be.default.errors,t),e.if((0,Z._)`${be.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${be.default.vErrors}.length`,t),()=>e.assign(be.default.vErrors,null)))}ge.resetErrorsCount=Zb;function Ub({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,be.default.errors,a=>{e.const(s,(0,Z._)`${be.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(be.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=Ub;function gp(e,t){let r=e.const("err",t);e.if((0,Z._)`${be.default.vErrors} === null`,()=>e.assign(be.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${be.default.vErrors}.push(${r})`),e.code((0,Z._)`${be.default.errors}++`)}function yp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Ct={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function _p(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:Fb(e,t,r)}function Fb(e,t,r={}){let{gen:n,it:o}=e,i=[Kb(o,r),Vb(e,r)];return Hb(e,t,i),n.object(...i)}function Kb({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,ko.getErrorPath)(t,ko.Type.Str)}`:e;return[be.default.instancePath,(0,Z.strConcat)(be.default.instancePath,r)]}function Vb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,ko.getErrorPath)(r,ko.Type.Str)}`),[Ct.schemaPath,o]}function Hb(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Ct.keyword,o],[Ct.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Ct.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ct.schema,s],[Ct.parentSchema,(0,Z._)`${u}${d}`],[be.default.data,i]),l&&n.push([Ct.propertyName,l])}});var vp=w(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.boolOrEmptySchema=tr.topBoolOrEmptySchema=void 0;var Gb=on(),Wb=N(),Jb=ct(),Qb={message:"boolean schema is false"};function Yb(e){let{gen:t,schema:r,validateName:n}=e;r===!1?wp(e,!1):typeof r=="object"&&r.$async===!0?t.return(Jb.default.data):(t.assign((0,Wb._)`${n}.errors`,null),t.return(!0))}tr.topBoolOrEmptySchema=Yb;function Xb(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),wp(e)):r.var(t,!0)}tr.boolOrEmptySchema=Xb;function wp(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,Qb,void 0,t)}});var ha=w(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.getRules=rr.isJSONType=void 0;var e0=["string","number","integer","boolean","null","object","array"],t0=new Set(e0);function r0(e){return typeof e=="string"&&t0.has(e)}rr.isJSONType=r0;function n0(){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:{}}}rr.getRules=n0});var ga=w(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function o0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&bp(e,n)}yt.schemaHasRulesForType=o0;function bp(e,t){return t.rules.some(r=>$p(e,r))}yt.shouldUseGroup=bp;function $p(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))}yt.shouldUseRule=$p});var sn=w(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var i0=ha(),s0=ga(),a0=on(),A=N(),xp=B(),nr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(nr||(ye.DataType=nr={}));function c0(e){let t=kp(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}ye.getSchemaTypes=c0;function kp(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(i0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=kp;function u0(e,t){let{gen:r,data:n,opts:o}=e,i=l0(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,s0.schemaHasRulesForType)(e,t[0]));if(s){let a=_a(t,n,o.strictNumbers,nr.Wrong);r.if(a,()=>{i.length?d0(e,t,i):wa(e)})}return s}ye.coerceAndCheckDataType=u0;var Sp=new Set(["string","number","integer","boolean","null"]);function l0(e,t){return t?e.filter(r=>Sp.has(r)||t==="array"&&r==="array"):[]}function d0(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,A._)`typeof ${o}`),a=n.let("coerced",(0,A._)`undefined`);i.coerceTypes==="array"&&n.if((0,A._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,A._)`${o}[0]`).assign(s,(0,A._)`typeof ${o}`).if(_a(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,A._)`${a} !== undefined`);for(let l of r)(Sp.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),wa(e),n.endIf(),n.if((0,A._)`${a} !== undefined`,()=>{n.assign(o,a),f0(e,a)});function c(l){switch(l){case"string":n.elseIf((0,A._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":n.elseIf((0,A._)`${s} == "boolean" || ${o} === null
5
+ || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":n.elseIf((0,A._)`${s} === "boolean" || ${o} === null
6
+ || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":n.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,A._)`${s} === "string" || ${s} === "number"
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function f0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,A._)`${t} !== undefined`,()=>e.assign((0,A._)`${t}[${r}]`,n))}function ya(e,t,r,n=nr.Correct){let o=n===nr.Correct?A.operators.EQ:A.operators.NEQ,i;switch(e){case"null":return(0,A._)`${t} ${o} null`;case"array":i=(0,A._)`Array.isArray(${t})`;break;case"object":i=(0,A._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,A._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,A._)`typeof ${t} ${o} ${e}`}return n===nr.Correct?i:(0,A.not)(i);function s(a=A.nil){return(0,A.and)((0,A._)`typeof ${t} == "number"`,a,r?(0,A._)`isFinite(${t})`:A.nil)}}ye.checkDataType=ya;function _a(e,t,r,n){if(e.length===1)return ya(e[0],t,r,n);let o,i=(0,xp.toHash)(e);if(i.array&&i.object){let s=(0,A._)`typeof ${t} != "object"`;o=i.null?s:(0,A._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=A.nil;i.number&&delete i.integer;for(let s in i)o=(0,A.and)(o,ya(s,t,r,n));return o}ye.checkDataTypes=_a;var p0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,A._)`{type: ${e}}`:(0,A._)`{type: ${t}}`};function wa(e){let t=m0(e);(0,a0.reportError)(t,p0)}ye.reportTypeError=wa;function m0(e){let{gen:t,data:r,schema:n}=e,o=(0,xp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Tp=w(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.assignDefaults=void 0;var or=N(),h0=B();function g0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Ep(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Ep(e,i,o.default))}So.assignDefaults=g0;function Ep(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,or._)`${i}${(0,or.getProperty)(t)}`;if(o){(0,h0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,or._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,or._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,or._)`${a} = ${(0,or.stringify)(r)}`)}});var Ce=w(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.validateUnion=V.validateArray=V.usePattern=V.callValidateCode=V.schemaProperties=V.allSchemaProperties=V.noPropertyInData=V.propertyInData=V.isOwnProperty=V.hasPropFunc=V.reportMissingProp=V.checkMissingProp=V.checkReportMissingProp=void 0;var X=N(),va=B(),_t=ct(),y0=B();function _0(e,t){let{gen:r,data:n,it:o}=e;r.if($a(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}V.checkReportMissingProp=_0;function w0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)($a(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}V.checkMissingProp=w0;function v0(e,t){e.setParams({missingProperty:t},!0),e.error()}V.reportMissingProp=v0;function Pp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}V.hasPropFunc=Pp;function ba(e,t,r){return(0,X._)`${Pp(e)}.call(${t}, ${r})`}V.isOwnProperty=ba;function b0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${ba(e,t,r)}`:o}V.propertyInData=b0;function $a(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(ba(e,t,r))):o}V.noPropertyInData=$a;function zp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}V.allSchemaProperties=zp;function $0(e,t){return zp(t).filter(r=>!(0,va.alwaysValidSchema)(e,t[r]))}V.schemaProperties=$0;function x0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[_t.default.instancePath,(0,X.strConcat)(_t.default.instancePath,i)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];s.opts.dynamicRef&&d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}V.callValidateCode=x0;var k0=(0,X._)`new RegExp`;function S0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?k0:(0,y0.useFunc)(e,o)}(${r}, ${n})`})}V.usePattern=S0;function E0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:va.Type.Num},i),t.if((0,X.not)(i),a)})}}V.validateArray=E0;function T0(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,va.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}V.validateUnion=T0});var Op=w(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var $e=N(),Dt=ct(),P0=Ce(),z0=on();function R0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Ip(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:$e.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Ye.macroKeywordCode=R0;function I0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;A0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Ip(n,o,l),d=n.let("valid");e.block$data(d,f),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function f(){if(t.errors===!1)h(),t.modifying&&Rp(e),_(()=>e.error());else{let v=t.async?p():m();t.modifying&&Rp(e),_(()=>O0(e,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,$e._)`await `),b=>n.assign(d,!1).if((0,$e._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,$e._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,$e._)`${u}.errors`;return n.assign(v,null),h($e.nil),v}function h(v=t.async?(0,$e._)`await `:$e.nil){let b=c.opts.passContext?Dt.default.this:Dt.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,$e._)`${v}${(0,P0.callValidateCode)(e,u,b,$)}`,t.modifying)}function _(v){var b;n.if((0,$e.not)((b=t.valid)!==null&&b!==void 0?b:d),v)}}Ye.funcKeywordCode=I0;function Rp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,$e._)`${n.parentData}[${n.parentDataProperty}]`))}function O0(e,t){let{gen:r}=e;r.if((0,$e._)`Array.isArray(${t})`,()=>{r.assign(Dt.default.vErrors,(0,$e._)`${Dt.default.vErrors} === null ? ${t} : ${Dt.default.vErrors}.concat(${t})`).assign(Dt.default.errors,(0,$e._)`${Dt.default.vErrors}.length`),(0,z0.extendErrors)(e)},()=>e.error())}function A0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ip(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,$e.stringify)(r)})}function N0(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")}Ye.validSchemaType=N0;function C0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ye.validateKeywordUsage=C0});var Np=w(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.extendSubschemaMode=wt.extendSubschemaData=wt.getSubschema=void 0;var Xe=N(),Ap=B();function D0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){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,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}${(0,Xe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Ap.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}wt.getSubschema=D0;function j0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){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:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,Xe._)`${t.data}${(0,Xe.getProperty)(r)}`,!0);c(f),e.errorPath=(0,Xe.str)`${l}${(0,Ap.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Xe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Xe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}wt.extendSubschemaData=j0;function M0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}wt.extendSubschemaMode=M0});var xa=w((U1,Cp)=>{"use strict";Cp.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,i;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(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var jp=w((F1,Dp)=>{"use strict";var vt=Dp.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(){};Eo(t,n,o,e,"",e)};vt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vt.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 Eo(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in vt.arrayKeywords)for(var f=0;f<d.length;f++)Eo(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in vt.propsKeywords){if(d&&typeof d=="object")for(var p in d)Eo(e,t,r,d[p],o+"/"+u+"/"+q0(p),i,o,u,n,p)}else(u in vt.keywords||e.allKeys&&!(u in vt.skipKeywords))&&Eo(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function q0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var an=w(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var L0=B(),B0=xa(),Z0=jp(),U0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function F0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ka(e):t?Mp(e)<=t:!1}Te.inlineRef=F0;var K0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ka(e){for(let t in e){if(K0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(ka)||typeof r=="object"&&ka(r))return!0}return!1}function Mp(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!U0.has(r)&&(typeof e[r]=="object"&&(0,L0.eachItem)(e[r],n=>t+=Mp(n)),t===1/0))return 1/0}return t}function qp(e,t="",r){r!==!1&&(t=ir(t));let n=e.parse(t);return Lp(e,n)}Te.getFullPath=qp;function Lp(e,t){return e.serialize(t).split("#")[0]+"#"}Te._getFullPath=Lp;var V0=/#\/?$/;function ir(e){return e?e.replace(V0,""):""}Te.normalizeId=ir;function H0(e,t,r){return r=ir(r),e.resolve(t,r)}Te.resolveUrl=H0;var G0=/^[a-z_][-a-z0-9._]*$/i;function W0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ir(e[r]||t),i={"":o},s=qp(n,o,!1),a={},c=new Set;return Z0(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=v.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[f]=_;function v($){let T=this.opts.uriResolver.resolve;if($=ir(_?T(_,$):$),c.has($))throw u($);c.add($);let R=this.refs[$];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?l(d,R.schema,$):$!==ir(h)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=h),$}function b($){if(typeof $=="string"){if(!G0.test($))throw new Error(`invalid anchor "${$}"`);v.call(this,`#${$}`)}}}),a;function l(d,f,p){if(f!==void 0&&!B0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=W0});var ln=w(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getData=bt.KeywordCxt=bt.validateFunctionCode=void 0;var Kp=vp(),Bp=sn(),Ea=ga(),To=sn(),J0=Tp(),un=Op(),Sa=Np(),S=N(),O=ct(),Q0=an(),ut=B(),cn=on();function Y0(e){if(Gp(e)&&(Wp(e),Hp(e))){t$(e);return}Vp(e,()=>(0,Kp.topBoolOrEmptySchema)(e))}bt.validateFunctionCode=Y0;function Vp({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${O.default.data}, ${O.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Zp(r,o)}`),e$(e,o),e.code(i)}):e.func(t,(0,S._)`${O.default.data}, ${X0(o)}`,n.$async,()=>e.code(Zp(r,o)).code(i))}function X0(e){return(0,S._)`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${e.dynamicRef?(0,S._)`, ${O.default.dynamicAnchors}={}`:S.nil}}={}`}function e$(e,t){e.if(O.default.valCxt,()=>{e.var(O.default.instancePath,(0,S._)`${O.default.valCxt}.${O.default.instancePath}`),e.var(O.default.parentData,(0,S._)`${O.default.valCxt}.${O.default.parentData}`),e.var(O.default.parentDataProperty,(0,S._)`${O.default.valCxt}.${O.default.parentDataProperty}`),e.var(O.default.rootData,(0,S._)`${O.default.valCxt}.${O.default.rootData}`),t.dynamicRef&&e.var(O.default.dynamicAnchors,(0,S._)`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{e.var(O.default.instancePath,(0,S._)`""`),e.var(O.default.parentData,(0,S._)`undefined`),e.var(O.default.parentDataProperty,(0,S._)`undefined`),e.var(O.default.rootData,O.default.data),t.dynamicRef&&e.var(O.default.dynamicAnchors,(0,S._)`{}`)})}function t$(e){let{schema:t,opts:r,gen:n}=e;Vp(e,()=>{r.$comment&&t.$comment&&Qp(e),s$(e),n.let(O.default.vErrors,null),n.let(O.default.errors,0),r.unevaluated&&r$(e),Jp(e),u$(e)})}function r$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Zp(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function n$(e,t){if(Gp(e)&&(Wp(e),Hp(e))){o$(e,t);return}(0,Kp.boolOrEmptySchema)(e,t)}function Hp({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 Gp(e){return typeof e.schema!="boolean"}function o$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Qp(e),a$(e),c$(e);let i=n.const("_errs",O.default.errors);Jp(e,i),n.var(t,(0,S._)`${i} === ${O.default.errors}`)}function Wp(e){(0,ut.checkUnknownRules)(e),i$(e)}function Jp(e,t){if(e.opts.jtd)return Up(e,[],!1,t);let r=(0,Bp.getSchemaTypes)(e.schema),n=(0,Bp.coerceAndCheckDataType)(e,r);Up(e,r,!n,t)}function i$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function s$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function a$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Q0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function c$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qp({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${O.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${O.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function u$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${O.default.errors} === 0`,()=>t.return(O.default.data),()=>t.throw((0,S._)`new ${o}(${O.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,O.default.vErrors),i.unevaluated&&l$(e),t.return((0,S._)`${O.default.errors} === 0`))}function l$({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function Up(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(i,u))){o.block(()=>Xp(e,"$ref",u.all.$ref.definition));return}c.jtd||d$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ea.shouldUseGroup)(i,f)&&(f.type?(o.if((0,To.checkDataType)(f.type,s,c.strictNumbers)),Fp(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,To.reportTypeError)(e)),o.endIf()):Fp(e,f),a||o.if((0,S._)`${O.default.errors} === ${n||0}`))}}function Fp(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,J0.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ea.shouldUseRule)(n,i)&&Xp(e,i.keyword,i.definition,t.type)})}function d$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(f$(e,t),e.opts.allowUnionTypes||p$(e,t),m$(e,e.dataTypes))}function f$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Yp(e.dataTypes,r)||Ta(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),g$(e,t)}}function p$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ta(e,"use allowUnionTypes to allow union type keyword")}function m$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ea.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>h$(t,s))&&Ta(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function h$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Yp(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function g$(e,t){let r=[];for(let n of e.dataTypes)Yp(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ta(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}var Po=class{constructor(t,r,n){if((0,un.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,ut.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",em(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,un.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",O.default.errors))}result(t,r,n){this.failResult((0,S.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,S.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,S._)`${r} !== undefined && (${(0,S.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?cn.reportExtraError:cn.reportError)(this,this.def.error,r)}$dataError(){(0,cn.reportError)(this,this.def.$dataError||cn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,cn.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=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,To.checkDataTypes)(c,r,i.opts.strictNumbers,To.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,Sa.getSubschema)(this.it,t);(0,Sa.extendSubschemaData)(n,this.it,t),(0,Sa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return n$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ut.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ut.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,S.Name)),!0}};bt.KeywordCxt=Po;function Xp(e,t,r,n){let o=new Po(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,un.funcKeywordCode)(o,r):"macro"in r?(0,un.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,un.funcKeywordCode)(o,r)}var y$=/^\/(?:[^~]|~0|~1)*$/,_$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function em(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return O.default.rootData;if(e[0]==="/"){if(!y$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=O.default.rootData}else{let l=_$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ut.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}bt.getData=em});var zo=w(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var Pa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};za.default=Pa});var dn=w(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Ra=an(),Ia=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ra.resolveUrl)(t,r,n),this.missingSchema=(0,Ra.normalizeId)((0,Ra.getFullPath)(t,this.missingRef))}};Oa.default=Ia});var Io=w(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.resolveSchema=De.getCompilingSchema=De.resolveRef=De.compileSchema=De.SchemaEnv=void 0;var Ze=N(),w$=zo(),jt=ct(),Ue=an(),tm=B(),v$=ln(),sr=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,Ue.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};De.SchemaEnv=sr;function Na(e){let t=rm.call(this,e);if(t)return t;let r=(0,Ue.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ze.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:w$.default,code:(0,Ze._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:jt.default.data,parentData:jt.default.parentData,parentDataProperty:jt.default.parentDataProperty,dataNames:[jt.default.data],dataPathArr:[Ze.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ze.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ze.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ze._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,v$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(jt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${jt.default.self}`,`${jt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Ze.Name?void 0:m,items:h instanceof Ze.Name?void 0:h,dynamicProps:m instanceof Ze.Name,dynamicItems:h instanceof Ze.Name},p.source&&(p.source.evaluated=(0,Ze.stringify)(p.evaluated))}return e.validate=p,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}De.compileSchema=Na;function b$(e,t,r){var n;r=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=k$.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new sr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=$$.call(this,i)}De.resolveRef=b$;function $$(e){return(0,Ue.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Na.call(this,e)}function rm(e){for(let t of this._compilations)if(x$(t,e))return t}De.getCompilingSchema=rm;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]||Ro.call(this,e,t)}function Ro(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ue._getFullPath)(this.opts.uriResolver,r),o=(0,Ue.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Aa.call(this,r,e);let i=(0,Ue.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Ro.call(this,e,s);return typeof a?.schema!="object"?void 0:Aa.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Na.call(this,s),i===(0,Ue.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ue.resolveUrl)(this.opts.uriResolver,o,l)),new sr({schema:a,schemaId:c,root:e,baseId:o})}return Aa.call(this,r,s)}}De.resolveSchema=Ro;var S$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Aa(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,tm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!S$.has(a)&&l&&(t=(0,Ue.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,tm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Ro.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new sr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var nm=w((J1,E$)=>{E$.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 ja=w((Q1,um)=>{"use strict";var T$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),im=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),Ca=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),P$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Da(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 z$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function om(e){return e.length=0,!0}function R$(e,t,r){if(e.length){let n=Da(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function I$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=R$;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=om}else{o.push(l);continue}}return o.length&&(a===om?r.zone=o.join(""):s?n.push(o.join("")):n.push(Da(o))),r.address=n.join(""),r}function am(e){if(O$(e,":")<2)return{host:e,isIPV6:!1};let t=I$(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 O$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function A$(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"},C$=/[@/?#:]/g,D$=/[@/?#]/g;function cm(e,t){let r=t?D$:C$;return r.lastIndex=0,e.replace(r,n=>N$[n])}function j$(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(Ca(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&sm(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function M$(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(Ca(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&sm(i)?t+=i:t+="%"+o,r+=2;continue}}P$(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(Ca(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function L$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!im(r)){let n=am(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=cm(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}um.exports={nonSimpleDomain:z$,recomposeAuthority:L$,reescapeHostDelimiters:cm,normalizePercentEncoding:j$,normalizePathEncoding:M$,escapePreservingEscapes:q$,removeDotSegments:A$,isIPv4:im,isUUID:T$,normalizeIPv6:am,stringArrayToHexStripped:Da}});var mm=w((Y1,pm)=>{"use strict";var{isUUID:B$}=ja(),Z$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,U$=["http","https","ws","wss","urn","urn:uuid"];function F$(e){return U$.indexOf(e)!==-1}function Ma(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 lm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function dm(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 K$(e){return e.secure=Ma(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function V$(e){if((e.port===(Ma(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 H$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Z$);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}`,i=qa(o);e.path=void 0,i&&(e=i.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}`,i=qa(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function W$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!B$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function J$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var fm={scheme:"http",domainHost:!0,parse:lm,serialize:dm},Q$={scheme:"https",domainHost:fm.domainHost,parse:lm,serialize:dm},Oo={scheme:"ws",domainHost:!0,parse:K$,serialize:V$},Y$={scheme:"wss",domainHost:Oo.domainHost,parse:Oo.parse,serialize:Oo.serialize},X$={scheme:"urn",parse:H$,serialize:G$,skipNormalize:!0},ex={scheme:"urn:uuid",parse:W$,serialize:J$,skipNormalize:!0},Ao={http:fm,https:Q$,ws:Oo,wss:Y$,urn:X$,"urn:uuid":ex};Object.setPrototypeOf(Ao,null);function qa(e){return e&&(Ao[e]||Ao[e.toLowerCase()])||void 0}pm.exports={wsIsSecure:Ma,SCHEMES:Ao,isValidSchemeName:F$,getSchemeHandler:qa}});var vm=w((X1,No)=>{"use strict";var{normalizeIPv6:tx,removeDotSegments:fn,recomposeAuthority:rx,normalizePercentEncoding:nx,normalizePathEncoding:ox,escapePreservingEscapes:ix,reescapeHostDelimiters:sx,isIPv4:ax,nonSimpleDomain:cx}=ja(),{SCHEMES:ux,getSchemeHandler:gm}=mm();function lx(e,t){return typeof e=="string"?e=hx(e,t):typeof e=="object"&&(e=ar(Mt(e,t),t)),e}function dx(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=ym(ar(e,n),ar(t,n),n,!0);return n.skipEscape=!0,Mt(o,n)}function ym(e,t,r,n){let o={};return n||(e=ar(Mt(e,r),r),t=ar(Mt(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=fn(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=fn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=fn(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=fn(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 fx(e,t,r){let n=hm(e,r),o=hm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Mt(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=[],i=gm(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=nx(r.path):(r.path=ix(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=rx(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=fn(a)),s===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 px=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mx(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 _m(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,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(px);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=mx(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(ax(n.host)===!1){let u=tx(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=gm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&cx(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((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=sx(unescape(n.host),i))),n.path&&(n.path=ox(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function ar(e,t){return _m(e,t).parsed}function hx(e,t){return wm(e,t).normalized}function wm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=_m(e,t);return{normalized:n?e:Mt(r,t),malformedAuthorityOrPort:n}}function hm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=wm(e,t);return n?void 0:r}if(typeof e=="object")return Mt(e,t)}var La={SCHEMES:ux,normalize:lx,resolve:dx,resolveComponent:ym,equal:fx,serialize:Mt,parse:ar};No.exports=La;No.exports.default=La;No.exports.fastUri=La});var $m=w(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var bm=vm();bm.code='require("ajv/dist/runtime/uri").default';Ba.default=bm});var Rm=w(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var gx=ln();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return gx.KeywordCxt}});var cr=N();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return cr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return cr.CodeGen}});var yx=zo(),Tm=dn(),_x=ha(),pn=Io(),wx=N(),mn=an(),Co=sn(),Ua=B(),xm=nm(),vx=$m(),Pm=(e,t)=>new RegExp(e,t);Pm.code="new RegExp";var bx=["removeAdditional","useDefaults","coerceTypes"],$x=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xx={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."},kx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},km=200;function Sx(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,v,b,$,T,R,we,Re,Vt,Ei;let Tr=e.strict,Ti=(t=e.code)===null||t===void 0?void 0:t.optimize,Iu=Ti===!0||Ti===void 0?1:Ti||0,Ou=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Pm,a_=(o=e.uriResolver)!==null&&o!==void 0?o:vx.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Tr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Tr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Tr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Tr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Tr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Iu,regExp:Ou}:{optimize:Iu,regExp:Ou},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:km,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:km,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(T=e.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(we=e.validateSchema)!==null&&we!==void 0?we:!0,validateFormats:(Re=e.validateFormats)!==null&&Re!==void 0?Re:!0,unicodeRegExp:(Vt=e.unicodeRegExp)!==null&&Vt!==void 0?Vt:!0,int32range:(Ei=e.int32range)!==null&&Ei!==void 0?Ei:!0,uriResolver:a_}}var hn=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,...Sx(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new wx.ValueScope({scope:{},prefixes:$x,es5:r,lines:n}),this.logger=Ix(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,_x.getRules)(),Sm.call(this,xx,t,"NOT SUPPORTED"),Sm.call(this,kx,t,"DEPRECATED","warn"),this._metaOpts=zx.call(this),t.formats&&Tx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Px.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Ex.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=xm;n==="id"&&(o={...xm},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(u,d){await i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Tm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,mn.normalizeId)(r||i),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 i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=Em.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new pn.SchemaEnv({schema:{},schemaId:n});if(r=pn.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=Em.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,mn.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(Ax.call(this,n,r),!r)return(0,Ua.eachItem)(n,i=>Za.call(this,i)),this;Cx.call(this,r);let o={...r,type:(0,Co.getJSONTypes)(r.type),schemaType:(0,Co.getJSONTypes)(r.schemaType)};return(0,Ua.eachItem)(n,o.type.length===0?i=>Za.call(this,i,o):i=>o.type.forEach(s=>Za.call(this,i,o,s))),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(i=>i.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,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=zm(u))}}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,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=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,mn.normalizeId)(s||n);let l=mn.getSchemaRefs.call(this,t,n);return c=new pn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!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):pn.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{pn.compileSchema.call(this,t)}finally{this.opts=r}}};hn.ValidationError=yx.default;hn.MissingRefError=Tm.default;fe.default=hn;function Sm(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function Em(e){return e=(0,mn.normalizeId)(e),this.schemas[e]||this.refs[e]}function Ex(){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 Tx(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Px(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 zx(){let e={...this.opts};for(let t of bx)delete e[t];return e}var Rx={log(){},warn(){},error(){}};function Ix(e){if(e===!1)return Rx;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 Ox=/^[a-z_$][a-z0-9_$:-]*$/i;function Ax(e,t){let{RULES:r}=this;if((0,Ua.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Ox.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 Za(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Co.getJSONTypes)(t.type),schemaType:(0,Co.getJSONTypes)(t.schemaType)}};t.before?Nx.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Nx(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 Cx(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=zm(t)),e.validateSchema=this.compile(t,!0))}var Dx={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function zm(e){return{anyOf:[e,Dx]}}});var Im=w(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var jx={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Fa.default=jx});var Cm=w(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.callRef=qt.getValidate=void 0;var Mx=dn(),Om=Ce(),Pe=N(),ur=ct(),Am=Io(),Do=B(),qx={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=Am.resolveRef.call(c,l,o,r);if(u===void 0)throw new Mx.default(n.opts.uriResolver,o,r);if(u instanceof Am.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return jo(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return jo(e,(0,Pe._)`${m}.validate`,l,l.$async)}function f(m){let h=Nm(e,m);jo(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pe.stringify)(m)}:{ref:m}),_=t.name("valid"),v=e.subschema({schema:m,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(v),e.ok(_)}}};function Nm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}qt.getValidate=Nm;function jo(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?ur.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,Om.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Pe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,Om.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Pe._)`${m}.errors`;o.assign(ur.default.vErrors,(0,Pe._)`${ur.default.vErrors} === null ? ${h} : ${ur.default.vErrors}.concat(${h})`),o.assign(ur.default.errors,(0,Pe._)`${ur.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let _=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=Do.mergeEvaluated.props(o,_.props,i.props));else{let v=o.var("props",(0,Pe._)`${m}.evaluated.props`);i.props=Do.mergeEvaluated.props(o,v,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Do.mergeEvaluated.items(o,_.items,i.items));else{let v=o.var("items",(0,Pe._)`${m}.evaluated.items`);i.items=Do.mergeEvaluated.items(o,v,i.items,Pe.Name)}}}qt.callRef=jo;qt.default=qx});var Dm=w(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Lx=Im(),Bx=Cm(),Zx=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Lx.default,Bx.default];Ka.default=Zx});var jm=w(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var Mo=N(),$t=Mo.operators,qo={maximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},minimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},exclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},exclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},Ux={message:({keyword:e,schemaCode:t})=>(0,Mo.str)`must be ${qo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Mo._)`{comparison: ${qo[e].okStr}, limit: ${t}}`},Fx={keyword:Object.keys(qo),type:"number",schemaType:"number",$data:!0,error:Ux,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Mo._)`${r} ${qo[t].fail} ${n} || isNaN(${r})`)}};Va.default=Fx});var Mm=w(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var gn=N(),Kx={message:({schemaCode:e})=>(0,gn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,gn._)`{multipleOf: ${e}}`},Vx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Kx,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,gn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,gn._)`${s} !== parseInt(${s})`;e.fail$data((0,gn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ha.default=Vx});var Lm=w(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});function qm(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}Ga.default=qm;qm.code='require("ajv/dist/runtime/ucs2length").default'});var Bm=w(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var Lt=N(),Hx=B(),Gx=Lm(),Wx={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Lt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Lt._)`{limit: ${e}}`},Jx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Wx,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Lt.operators.GT:Lt.operators.LT,s=o.opts.unicode===!1?(0,Lt._)`${r}.length`:(0,Lt._)`${(0,Hx.useFunc)(e.gen,Gx.default)}(${r})`;e.fail$data((0,Lt._)`${s} ${i} ${n}`)}};Wa.default=Jx});var Zm=w(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Qx=Ce(),Yx=B(),lr=N(),Xx={message:({schemaCode:e})=>(0,lr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,lr._)`{pattern: ${e}}`},ek={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Xx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,lr._)`new RegExp`:(0,Yx.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,lr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,lr._)`!${u}`)}else{let c=(0,Qx.usePattern)(e,o);e.fail$data((0,lr._)`!${c}.test(${r})`)}}};Ja.default=ek});var Um=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var yn=N(),tk={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,yn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,yn._)`{limit: ${e}}`},rk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:tk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?yn.operators.GT:yn.operators.LT;e.fail$data((0,yn._)`Object.keys(${r}).length ${o} ${n}`)}};Qa.default=rk});var Fm=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var _n=Ce(),wn=N(),nk=B(),ok={message:({params:{missingProperty:e}})=>(0,wn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wn._)`{missingProperty: ${e}}`},ik={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ok,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let _=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,nk.checkStrictMode)(s,v,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(wn.nil,d);else for(let p of r)(0,_n.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>f(p,m)),e.ok(m)}else t.if((0,_n.checkMissingProp)(e,r,p)),(0,_n.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,_n.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,_n.propertyInData)(t,o,p,a.ownProperties)),t.if((0,wn.not)(m),()=>{e.error(),t.break()})},wn.nil)}}};Ya.default=ik});var Km=w(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var vn=N(),sk={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}}`},ak={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:sk,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}`)}};Xa.default=ak});var Lo=w(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Vm=xa();Vm.code='require("ajv/dist/runtime/equal").default';ec.default=Vm});var Hm=w(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var tc=sn(),pe=N(),ck=B(),uk=Lo(),lk={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},dk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:lk,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,tc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),v=(0,tc.checkDataTypes)(l,_,a.opts.strictNumbers,tc.DataType.Wrong),b=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(v,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${b}[${_}] = ${m}`)})}function p(m,h){let _=(0,ck.useFunc)(t,uk.default),v=t.name("outer");t.label(v).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};rc.default=dk});var Gm=w(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var nc=N(),fk=B(),pk=Lo(),mk={message:"must be equal to constant",params:({schemaCode:e})=>(0,nc._)`{allowedValue: ${e}}`},hk={keyword:"const",$data:!0,error:mk,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,nc._)`!${(0,fk.useFunc)(t,pk.default)}(${r}, ${o})`):e.fail((0,nc._)`${i} !== ${r}`)}};oc.default=hk});var Wm=w(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var bn=N(),gk=B(),yk=Lo(),_k={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,bn._)`{allowedValues: ${e}}`},wk={keyword:"enum",schemaType:"array",$data:!0,error:_k,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,gk.useFunc)(t,yk.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=t.const("vSchema",i);u=(0,bn.or)(...o.map((m,h)=>f(p,h)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,p=>t.if((0,bn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,bn._)`${l()}(${r}, ${p}[${m}])`:(0,bn._)`${r} === ${h}`}}};ic.default=wk});var Jm=w(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var vk=jm(),bk=Mm(),$k=Bm(),xk=Zm(),kk=Um(),Sk=Fm(),Ek=Km(),Tk=Hm(),Pk=Gm(),zk=Wm(),Rk=[vk.default,bk.default,$k.default,xk.default,kk.default,Sk.default,Ek.default,Tk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Pk.default,zk.default];sc.default=Rk});var cc=w($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.validateAdditionalItems=void 0;var Bt=N(),ac=B(),Ik={message:({params:{len:e}})=>(0,Bt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Bt._)`{limit: ${e}}`},Ok={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ik,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ac.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qm(e,n)}};function Qm(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Bt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Bt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,ac.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Bt._)`${a} <= ${t.length}`);r.if((0,Bt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:ac.Type.Num},l),s.allErrors||r.if((0,Bt.not)(l),()=>r.break())})}}$n.validateAdditionalItems=Qm;$n.default=Ok});var uc=w(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.validateTuple=void 0;var Ym=N(),Bo=B(),Ak=Ce(),Nk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Xm(e,"additionalItems",t);r.items=!0,!(0,Bo.alwaysValidSchema)(r,t)&&e.ok((0,Ak.validateArray)(e))}};function Xm(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Bo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Ym._)`${i}.length`);r.forEach((d,f)=>{(0,Bo.alwaysValidSchema)(a,d)||(n.if((0,Ym._)`${l} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(f.strictTuples&&!h){let _=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,Bo.checkStrictMode)(a,_,f.strictTuples)}}}xn.validateTuple=Xm;xn.default=Nk});var eh=w(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Ck=uc(),Dk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ck.validateTuple)(e,"items")};lc.default=Dk});var rh=w(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var th=N(),jk=B(),Mk=Ce(),qk=cc(),Lk={message:({params:{len:e}})=>(0,th.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,th._)`{limit: ${e}}`},Bk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Lk,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,jk.alwaysValidSchema)(n,t)&&(o?(0,qk.validateAdditionalItems)(e,o):e.ok((0,Mk.validateArray)(e)))}};dc.default=Bk});var nh=w(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var je=N(),Zo=B(),Zk={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}}`},Uk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Zk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,je._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Zo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Zo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Zo.alwaysValidSchema)(i,r)){let h=(0,je._)`${u} >= ${s}`;a!==void 0&&(h=(0,je._)`${h} && ${u} <= ${a}`),e.pass(h);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?p(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,je._)`${o}.length > 0`,f)):(t.let(d,!1),f()),e.result(d,()=>e.reset());function f(){let h=t.name("_valid"),_=t.let("count",0);p(h,()=>t.if(h,()=>m(_)))}function p(h,_){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Zo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,je._)`${h}++`),a===void 0?t.if((0,je._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,je._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,je._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};fc.default=Uk});var sh=w(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateSchemaDeps=et.validatePropertyDeps=et.error=void 0;var pc=N(),Fk=B(),kn=Ce();et.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,pc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,pc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var Vk={keyword:"dependencies",type:"object",schemaType:"object",error:et.error,code(e){let[t,r]=Kk(e);oh(e,t),ih(e,r)}};function Kk({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 oh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,kn.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,kn.checkReportMissingProp)(e,l)}):(r.if((0,pc._)`${c} && (${(0,kn.checkMissingProp)(e,a,i)})`),(0,kn.reportMissingProp)(e,i),r.else())}}et.validatePropertyDeps=oh;function ih(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,Fk.alwaysValidSchema)(i,t[a])||(r.if((0,kn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}et.validateSchemaDeps=ih;et.default=Vk});var ch=w(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ah=N(),Hk=L(),Gk={message:"property name must be valid",params:({params:e})=>(0,ah._)`{propertyName: ${e.propertyName}}`},Wk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Gk,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Hk.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,ah.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};mc.default=Wk});var gc=w(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Uo=Ce(),Fe=N(),Jk=ct(),Fo=L(),Qk={message:"must NOT have additional properties",params:({params:e})=>(0,Fe._)`{additionalProperty: ${e.additionalProperty}}`},Yk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Qk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Fo.alwaysValidSchema)(s,r))return;let l=(0,Uo.allSchemaProperties)(n.properties),u=(0,Uo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Fe._)`${i} === ${Jk.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let b;if(l.length>8){let v=(0,Fo.schemaRefOrVal)(s,n.properties,"properties");b=(0,Uo.isOwnProperty)(t,v,_)}else l.length?b=(0,Fe.or)(...l.map(v=>(0,Fe._)`${_} === ${v}`)):b=Fe.nil;return u.length&&(b=(0,Fe.or)(b,...u.map(v=>(0,Fe._)`${(0,Uo.usePattern)(e,v)}.test(${_})`))),(0,Fe.not)(b)}function p(_){t.code((0,Fe._)`delete ${o}[${_}]`)}function m(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Fo.alwaysValidSchema)(s,r)){let b=t.name("valid");c.removeAdditional==="failing"?(h(_,b,!1),t.if((0,Fe.not)(b),()=>{e.reset(),p(_)})):(h(_,b),a||t.if((0,Fe.not)(b),()=>t.break()))}}function h(_,b,v){let $={keyword:"additionalProperties",dataProp:_,dataPropType:Fo.Type.Str};v===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,b)}}};hc.default=Yk});var dh=w(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Xk=ln(),uh=Ce(),yc=L(),lh=gc(),eS={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&lh.default.code(new Xk.KeywordCxt(i,lh.default,"additionalProperties"));let s=(0,uh.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=yc.mergeEvaluated.props(t,(0,yc.toHash)(s),i.props));let a=s.filter(d=>!(0,yc.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,uh.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};_c.default=eS});var hh=w(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var fh=Ce(),Vo=N(),ph=L(),mh=L(),tS={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,fh.allSchemaProperties)(r),c=a.filter(h=>(0,ph.alwaysValidSchema)(i,r[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof Vo.Name)&&(i.props=(0,mh.evaluatedPropsToName)(t,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(t.var(u,!0),m(h),t.if(u))}function p(h){for(let _ in l)new RegExp(h).test(_)&&(0,ph.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,Vo._)`${(0,fh.usePattern)(e,h)}.test(${_})`,()=>{let b=c.includes(h);b||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:mh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,Vo._)`${d}[${_}]`,!0):!b&&!i.allErrors&&t.if((0,Vo.not)(u),()=>t.break())})})}}};wc.default=tS});var gh=w(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var rS=L(),nS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,rS.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"}};bc.default=nS});var yh=w(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var oS=Ce(),iS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:oS.validateUnion,error:{message:"must match a schema in anyOf"}};vc.default=iS});var _h=w($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Ko=N(),sS=L(),aS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ko._)`{passingSchemas: ${e.passing}}`},cS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:aS,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 i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let f;(0,sS.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Ko._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Ko._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,Ko.Name)})})}}};$c.default=cS});var wh=w(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var uS=L(),lS={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((i,s)=>{if((0,uS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};xc.default=lS});var $h=w(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Ho=N(),vh=L(),dS={message:({params:e})=>(0,Ho.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ho._)`{failingKeyword: ${e.ifClause}}`},fS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:dS,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,vh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=bh(n,"then"),i=bh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,Ho.not)(a),l("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let f=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(f,s),d?t.assign(d,(0,Ho._)`${u}`):e.setParams({ifClause:u})}}}};function bh(e,t){let r=e.schema[t];return r!==void 0&&!(0,vh.alwaysValidSchema)(e,r)}kc.default=fS});var xh=w(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var pS=L(),mS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,pS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Sc.default=mS});var kh=w(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var hS=cc(),gS=eh(),yS=uc(),_S=rh(),wS=nh(),bS=sh(),vS=ch(),$S=gc(),xS=dh(),kS=hh(),SS=gh(),ES=yh(),TS=_h(),PS=wh(),zS=$h(),RS=xh();function IS(e=!1){let t=[SS.default,ES.default,TS.default,PS.default,zS.default,RS.default,vS.default,$S.default,bS.default,xS.default,kS.default];return e?t.push(gS.default,_S.default):t.push(hS.default,yS.default),t.push(wS.default),t}Ec.default=IS});var Sh=w(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var ie=N(),AS={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},OS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:AS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),b=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(b,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(b,h)),e.fail$data((0,ie.or)(v(),$()));function v(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${b}`}function $(){let T=u.$async?(0,ie._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,ie._)`${b}(${n})`,R=(0,ie._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${n}))`;return(0,ie._)`${b} && ${b} !== true && ${_} === ${t} && !${R}`}}function p(){let m=d.formats[i];if(!m){v();return}if(m===!0)return;let[h,_,b]=$(m);h===t&&e.pass(T());function v(){if(c.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function $(R){let we=R instanceof RegExp?(0,ie.regexpCode)(R):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Re=r.scopeValue("formats",{key:i,ref:R,code:we});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,ie._)`${Re}.validate`]:["string",R,Re]}function T(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${b}(${n})`}return typeof _=="function"?(0,ie._)`${b}(${n})`:(0,ie._)`${b}.test(${n})`}}}};Tc.default=OS});var Eh=w(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var NS=Sh(),CS=[NS.default];Pc.default=CS});var Th=w(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.contentVocabulary=dr.metadataVocabulary=void 0;dr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];dr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var zh=w(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var DS=Dm(),jS=Jm(),MS=kh(),qS=Eh(),Ph=Th(),BS=[DS.default,jS.default,(0,MS.default)(),qS.default,Ph.metadataVocabulary,Ph.contentVocabulary];zc.default=BS});var Ih=w(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.DiscrError=void 0;var Rh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Rh||(Go.DiscrError=Rh={}))});var Oh=w(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var fr=N(),Rc=Ih(),Ah=Io(),LS=dn(),ZS=L(),US={message:({params:{discrError:e,tagName:t}})=>e===Rc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,fr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},FS={keyword:"discriminator",type:"object",schemaType:"object",error:US,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.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(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,fr._)`${r}${(0,fr.getProperty)(a)}`);t.if((0,fr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Rc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let p=f();t.if(!1);for(let m in p)t.elseIf((0,fr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Rc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,fr.Name),m}function f(){var p;let m={},h=b(o),_=!0;for(let T=0;T<s.length;T++){let R=s[T];if(R?.$ref&&!(0,ZS.schemaHasRulesButRef)(R,i.self.RULES)){let Re=R.$ref;if(R=Ah.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Re),R instanceof Ah.SchemaEnv&&(R=R.schema),R===void 0)throw new LS.default(i.opts.uriResolver,i.baseId,Re)}let we=(p=R?.properties)===null||p===void 0?void 0:p[a];if(typeof we!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||b(R)),v(we,T)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function b({required:T}){return Array.isArray(T)&&T.includes(a)}function v(T,R){if(T.const)$(T.const,R);else if(T.enum)for(let we of T.enum)$(we,R);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(T,R){if(typeof T!="string"||T in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[T]=R}}}};Ic.default=FS});var Nh=w((BD,VS)=>{VS.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 Oc=w((ee,Ac)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var KS=Rm(),HS=zh(),GS=Oh(),Ch=Nh(),WS=["/properties"],Wo="http://json-schema.org/draft-07/schema",pr=class extends KS.default{_addVocabularies(){super._addVocabularies(),HS.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(GS.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Ch,WS):Ch;this.addMetaSchema(t,Wo,!1),this.refs["http://json-schema.org/schema"]=Wo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wo)?Wo:void 0)}};ee.Ajv=pr;Ac.exports=ee=pr;Ac.exports.Ajv=pr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=pr;var JS=ln();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return JS.KeywordCxt}});var mr=N();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return mr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return mr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return mr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return mr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return mr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return mr.CodeGen}});var QS=zo();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return QS.default}});var YS=dn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return YS.default}})});var Uh=w(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.formatNames=rt.fastFormats=rt.fullFormats=void 0;function tt(e,t){return{validate:e,compare:t}}rt.fullFormats={date:tt(qh,jc),time:tt(Cc(!0),Mc),"date-time":tt(Dh(!0),Lh),"iso-time":tt(Cc(),Bh),"iso-date-time":tt(Dh(),Zh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:oE,"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:dE,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:iE,int32:{type:"number",validate:cE},int64:{type:"number",validate:uE},float:{type:"number",validate:Mh},double:{type:"number",validate:Mh},password:!0,binary:!0};rt.fastFormats={...rt.fullFormats,date:tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jc),time:tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Mc),"date-time":tt(/^\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,Lh),"iso-time":tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Bh),"iso-date-time":tt(/^\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,Zh),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};rt.formatNames=Object.keys(rt.fullFormats);function XS(e){return e%4===0&&(e%100!==0||e%400===0)}var eE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qh(e){let t=eE.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&&XS(r)?29:tE[n])}function jc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Nc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cc(e){return function(r){let n=Nc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&s<61}}function Mc(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 Bh(e,t){if(!(e&&t))return;let r=Nc.exec(e),n=Nc.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 Dc=/t|\s/i;function Dh(e){let t=Cc(e);return function(n){let o=n.split(Dc);return o.length===2&&qh(o[0])&&t(o[1])}}function Lh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Zh(e,t){if(!(e&&t))return;let[r,n]=e.split(Dc),[o,i]=t.split(Dc),s=jc(r,o);if(s!==void 0)return s||Mc(n,i)}var rE=/\/|:/,nE=/^(?:[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 oE(e){return rE.test(e)&&nE.test(e)}var jh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iE(e){return jh.lastIndex=0,jh.test(e)}var sE=-(2**31),aE=2**31-1;function cE(e){return Number.isInteger(e)&&e<=aE&&e>=sE}function uE(e){return Number.isInteger(e)}function Mh(){return!0}var lE=/[^\\]\\Z/;function dE(e){if(lE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Fh=w(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatLimitDefinition=void 0;var fE=Oc(),Ve=N(),xt=Ve.operators,Jo={formatMaximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},formatMinimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},formatExclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},formatExclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},pE={message:({keyword:e,schemaCode:t})=>(0,Ve.str)`should be ${Jo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ve._)`{comparison: ${Jo[e].okStr}, limit: ${t}}`};hr.formatLimitDefinition={keyword:Object.keys(Jo),type:"string",schemaType:"string",$data:!0,error:pE,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new fE.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,Ve._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ve.or)((0,Ve._)`typeof ${p} != "object"`,(0,Ve._)`${p} instanceof RegExp`,(0,Ve._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Ve._)`${s.code.formats}${(0,Ve.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ve._)`${f}.compare(${r}, ${n}) ${Jo[o].fail} 0`}},dependencies:["format"]};var mE=e=>(e.addKeyword(hr.formatLimitDefinition),e);hr.default=mE});var Gh=w((Sn,Hh)=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});var gr=Uh(),hE=Fh(),qc=N(),Vh=new qc.Name("fullFormats"),gE=new qc.Name("fastFormats"),Bc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Kh(e,t,gr.fullFormats,Vh),e;let[r,n]=t.mode==="fast"?[gr.fastFormats,gE]:[gr.fullFormats,Vh],o=t.formats||gr.formatNames;return Kh(e,o,r,n),t.keywords&&(0,hE.default)(e),e};Bc.get=(e,t="full")=>{let n=(t==="fast"?gr.fastFormats:gr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Kh(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,qc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Hh.exports=Sn=Bc;Object.defineProperty(Sn,"__esModule",{value:!0});Sn.default=Bc});var ng=w((ej,rg)=>{rg.exports=tg;tg.sync=bE;var Xh=dt("fs");function wE(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function eg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:wE(t,r)}function tg(e,t,r){Xh.stat(e,function(n,o){r(n,n?!1:eg(o,e,t))})}function bE(e,t){return eg(Xh.statSync(e),e,t)}});var cg=w((tj,ag)=>{ag.exports=ig;ig.sync=vE;var og=dt("fs");function ig(e,t,r){og.stat(e,function(n,o){r(n,n?!1:sg(o,t))})}function vE(e,t){return sg(og.statSync(e),t)}function sg(e,t){return e.isFile()&&$E(e,t)}function $E(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var lg=w((nj,ug)=>{var rj=dt("fs"),ti;process.platform==="win32"||global.TESTING_WINDOWS?ti=ng():ti=cg();ug.exports=Lc;Lc.sync=xE;function Lc(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Lc(e,t||{},function(i,s){i?o(i):n(s)})})}ti(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function xE(e,t){try{return ti.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var yg=w((oj,gg)=>{var yr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",dg=dt("path"),kE=yr?";":":",fg=lg(),pg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),mg=(e,t)=>{let r=t.colon||kE,n=e.match(/\//)||yr&&e.match(/\\/)?[""]:[...yr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=yr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=yr?o.split(r):[""];return yr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},hg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=mg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(pg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=dg.join(p,e),h=!p&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;u(c(h,l,0))}),c=(l,u,d)=>new Promise((f,p)=>{if(d===o.length)return f(a(u+1));let m=o[d];fg(l+m,{pathExt:i},(h,_)=>{if(!h&&_)if(t.all)s.push(l+m);else return f(l+m);return f(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},SE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=mg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=dg.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let f=u+n[d];try{if(fg.sync(f,{pathExt:o}))if(t.all)i.push(f);else return f}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw pg(e)};gg.exports=hg;hg.sync=SE});var wg=w((ij,Zc)=>{"use strict";var _g=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Zc.exports=_g;Zc.exports.default=_g});var xg=w((sj,$g)=>{"use strict";var bg=dt("path"),EE=yg(),TE=wg();function vg(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=EE.sync(e.command,{path:r[TE({env:r})],pathExt:t?bg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=bg.resolve(o?e.options.cwd:"",s)),s}function PE(e){return vg(e)||vg(e,!0)}$g.exports=PE});var kg=w((aj,Fc)=>{"use strict";var Uc=/([()\][%!^"`<>&|;, *?])/g;function zE(e){return e=e.replace(Uc,"^$1"),e}function RE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Uc,"^$1"),t&&(e=e.replace(Uc,"^$1")),e}Fc.exports.command=zE;Fc.exports.argument=RE});var Eg=w((cj,Sg)=>{"use strict";Sg.exports=/^#!(.*)/});var Pg=w((uj,Tg)=>{"use strict";var IE=Eg();Tg.exports=(e="")=>{let t=e.match(IE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Rg=w((lj,zg)=>{"use strict";var Vc=dt("fs"),AE=Pg();function OE(e){let r=Buffer.alloc(150),n;try{n=Vc.openSync(e,"r"),Vc.readSync(n,r,0,150,0),Vc.closeSync(n)}catch{}return AE(r.toString())}zg.exports=OE});var Ng=w((dj,Og)=>{"use strict";var NE=dt("path"),Ig=xg(),Ag=kg(),CE=Rg(),DE=process.platform==="win32",jE=/\.(?:com|exe)$/i,ME=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function qE(e){e.file=Ig(e);let t=e.file&&CE(e.file);return t?(e.args.unshift(e.file),e.command=t,Ig(e)):e.file}function BE(e){if(!DE)return e;let t=qE(e),r=!jE.test(t);if(e.options.forceShell||r){let n=ME.test(t);e.command=NE.normalize(e.command),e.command=Ag.command(e.command),e.args=e.args.map(i=>Ag.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function LE(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:BE(n)}Og.exports=LE});var jg=w((fj,Dg)=>{"use strict";var Kc=process.platform==="win32";function Hc(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function ZE(e,t){if(!Kc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Cg(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Cg(e,t){return Kc&&e===1&&!t.file?Hc(t.original,"spawn"):null}function UE(e,t){return Kc&&e===1&&!t.file?Hc(t.original,"spawnSync"):null}Dg.exports={hookChildProcess:ZE,verifyENOENT:Cg,verifyENOENTSync:UE,notFoundError:Hc}});var Bg=w((pj,_r)=>{"use strict";var Mg=dt("child_process"),Gc=Ng(),Wc=jg();function qg(e,t,r){let n=Gc(e,t,r),o=Mg.spawn(n.command,n.args,n.options);return Wc.hookChildProcess(o,n),o}function FE(e,t,r){let n=Gc(e,t,r),o=Mg.spawnSync(n.command,n.args,n.options);return o.error=o.error||Wc.verifyENOENTSync(o.status,n),o}_r.exports=qg;_r.exports.spawn=qg;_r.exports.sync=FE;_r.exports._parse=Gc;_r.exports._enoent=Wc});import{readFile as IR,mkdir as AR,writeFile as OR}from"node:fs/promises";import{dirname as NR,join as s_}from"node:path";var XR=Object.freeze({status:"aborted"});function y(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var eI=Symbol("zod_brand"),ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bn={};function Ie(e){return e&&Object.assign(Bn,e),Bn}var F={};Ou(F,{BIGINT_FORMAT_RANGES:()=>Cu,Class:()=>Ii,NUMBER_FORMAT_RANGES:()=>qi,aborted:()=>Tt,allowsEval:()=>Di,assert:()=>__,assertEqual:()=>m_,assertIs:()=>g_,assertNever:()=>y_,assertNotEqual:()=>h_,assignProp:()=>Ci,cached:()=>zr,captureStackTrace:()=>Zn,cleanEnum:()=>I_,cleanRegex:()=>Ir,clone:()=>Je,createTransparentProxy:()=>k_,defineLazy:()=>G,esc:()=>Et,escapeRegex:()=>ft,extend:()=>T_,finalizeIssue:()=>qe,floatSafeRemainder:()=>Ni,getElementAtPath:()=>w_,getEnumValues:()=>Ai,getLengthableOrigin:()=>Ar,getParsedType:()=>x_,getSizableOrigin:()=>Du,isObject:()=>Ht,isPlainObject:()=>Gt,issue:()=>Bi,joinValues:()=>Ln,jsonStringifyReplacer:()=>Oi,merge:()=>P_,normalizeParams:()=>P,nullish:()=>Rr,numKeys:()=>$_,omit:()=>E_,optionalKeys:()=>Mi,partial:()=>z_,pick:()=>S_,prefixIssues:()=>Qe,primitiveTypes:()=>Nu,promiseAllObject:()=>b_,propertyKeyTypes:()=>ji,randomString:()=>v_,required:()=>R_,stringifyPrimitive:()=>Un,unwrapMessage:()=>Pr});function m_(e){return e}function h_(e){return e}function g_(e){}function y_(e){throw new Error}function __(e){}function Ai(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 Ln(e,t="|"){return e.map(r=>Un(r)).join(t)}function Oi(e,t){return typeof t=="bigint"?t.toString():t}function zr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Rr(e){return e==null}function Ir(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ni(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function G(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 Ci(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function w_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function b_(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function v_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Et(e){return JSON.stringify(e)}var Zn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Di=zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Gt(e){if(Ht(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Ht(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function $_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var x_=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}`)}},ji=new Set(["string","number","symbol"]),Nu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function P(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 k_(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},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 Un(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Mi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var qi={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]},Cu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function S_(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 Je(e,{...e._zod.def,shape:r,checks:[]})}function E_(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 Je(e,{...e._zod.def,shape:r,checks:[]})}function T_(e,t){if(!Gt(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 Ci(this,"shape",n),n},checks:[]};return Je(e,r)}function P_(e,t){return Je(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function z_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Je(t,{...t._zod.def,shape:o,checks:[]})}function R_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Je(t,{...t._zod.def,shape:o,checks:[]})}function Tt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Qe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Pr(e){return typeof e=="string"?e:e?.message}function qe(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Pr(e.inst?._zod.def?.error?.(e))??Pr(t?.error?.(e))??Pr(r.customError?.(e))??Pr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Du(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ar(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Bi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function I_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ii=class{constructor(...t){}};var ju=(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,Oi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fn=y("$ZodError",ju),Li=y("$ZodError",ju,{Parent:Error});function Mu(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 qu(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var Bu=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ot;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>qe(c,i,Ie())));throw Zn(a,o?.callee),a}return s.value};var Lu=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>qe(c,i,Ie())));throw Zn(a,o?.callee),a}return s.value};var Zi=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ot;return i.issues.length?{success:!1,error:new(e??Fn)(i.issues.map(s=>qe(s,o,Ie())))}:{success:!0,data:i.value}},Or=Zi(Li),Ui=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>qe(s,o,Ie())))}:{success:!0,data:i.value}},Vn=Ui(Li);var Zu=/^[cC][^\s-]{8,}$/,Uu=/^[0-9a-z]+$/,Fu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vu=/^[0-9a-vA-V]{20}$/,Ku=/^[A-Za-z0-9]{27}$/,Hu=/^[a-zA-Z0-9_-]{21}$/,Gu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Wu=/^([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 Ju=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var O_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qu(){return new RegExp(O_,"u")}var Yu=/^(?:(?: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])$/,Xu=/^(([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})$/,el=/^((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])$/,tl=/^(([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])$/,rl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vi=/^[A-Za-z0-9_-]*$/,nl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var ol=/^\+(?:[0-9]){6,14}[0-9]$/,il="(?:(?:\\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])))",sl=new RegExp(`^${il}$`);function al(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 cl(e){return new RegExp(`^${al(e)}$`)}function ul(e){let t=al({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(`^${il}T(?:${n})$`)}var ll=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var dl=/^\d+$/,fl=/^-?\d+(?:\.\d+)?/i,pl=/true|false/i,ml=/null/i;var hl=/^[^A-Z]*$/,gl=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),yl={number:"number",bigint:"bigint",object:"date"},Hi=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=yl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(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=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=yl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(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})}}),_l=y("$ZodCheckMultipleOf",(e,t)=>{me.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):Ni(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})}}),wl=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=qi[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=dl)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.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}):s.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&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var bl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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 s=Ar(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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 s=Ar(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$l=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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,i=o.length;if(i===t.length)return;let s=Ar(o),a=i>t.length;n.issues.push({origin:s,...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})}}),Nr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.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=()=>{})}),xl=y("$ZodCheckRegex",(e,t)=>{Nr.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})}}),kl=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=hl),Nr.init(e,t)}),Sl=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=gl),Nr.init(e,t)}),El=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=ft(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Tl=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${ft(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})}}),Pl=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${ft(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 zl=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Kn=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(`
10
+ deps: ${r}}`};var Kk={keyword:"dependencies",type:"object",schemaType:"object",error:et.error,code(e){let[t,r]=Vk(e);oh(e,t),ih(e,r)}};function Vk({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 oh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,kn.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,kn.checkReportMissingProp)(e,l)}):(r.if((0,pc._)`${c} && (${(0,kn.checkMissingProp)(e,a,i)})`),(0,kn.reportMissingProp)(e,i),r.else())}}et.validatePropertyDeps=oh;function ih(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,Fk.alwaysValidSchema)(i,t[a])||(r.if((0,kn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}et.validateSchemaDeps=ih;et.default=Kk});var ch=w(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ah=N(),Hk=B(),Gk={message:"property name must be valid",params:({params:e})=>(0,ah._)`{propertyName: ${e.propertyName}}`},Wk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Gk,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Hk.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,ah.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};mc.default=Wk});var gc=w(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Uo=Ce(),Fe=N(),Jk=ct(),Fo=B(),Qk={message:"must NOT have additional properties",params:({params:e})=>(0,Fe._)`{additionalProperty: ${e.additionalProperty}}`},Yk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Qk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Fo.alwaysValidSchema)(s,r))return;let l=(0,Uo.allSchemaProperties)(n.properties),u=(0,Uo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Fe._)`${i} === ${Jk.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let v;if(l.length>8){let b=(0,Fo.schemaRefOrVal)(s,n.properties,"properties");v=(0,Uo.isOwnProperty)(t,b,_)}else l.length?v=(0,Fe.or)(...l.map(b=>(0,Fe._)`${_} === ${b}`)):v=Fe.nil;return u.length&&(v=(0,Fe.or)(v,...u.map(b=>(0,Fe._)`${(0,Uo.usePattern)(e,b)}.test(${_})`))),(0,Fe.not)(v)}function p(_){t.code((0,Fe._)`delete ${o}[${_}]`)}function m(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Fo.alwaysValidSchema)(s,r)){let v=t.name("valid");c.removeAdditional==="failing"?(h(_,v,!1),t.if((0,Fe.not)(v),()=>{e.reset(),p(_)})):(h(_,v),a||t.if((0,Fe.not)(v),()=>t.break()))}}function h(_,v,b){let $={keyword:"additionalProperties",dataProp:_,dataPropType:Fo.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,v)}}};hc.default=Yk});var dh=w(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Xk=ln(),uh=Ce(),yc=B(),lh=gc(),eS={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&lh.default.code(new Xk.KeywordCxt(i,lh.default,"additionalProperties"));let s=(0,uh.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=yc.mergeEvaluated.props(t,(0,yc.toHash)(s),i.props));let a=s.filter(d=>!(0,yc.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,uh.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};_c.default=eS});var hh=w(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var fh=Ce(),Ko=N(),ph=B(),mh=B(),tS={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,fh.allSchemaProperties)(r),c=a.filter(h=>(0,ph.alwaysValidSchema)(i,r[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof Ko.Name)&&(i.props=(0,mh.evaluatedPropsToName)(t,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(t.var(u,!0),m(h),t.if(u))}function p(h){for(let _ in l)new RegExp(h).test(_)&&(0,ph.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,Ko._)`${(0,fh.usePattern)(e,h)}.test(${_})`,()=>{let v=c.includes(h);v||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:mh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,Ko._)`${d}[${_}]`,!0):!v&&!i.allErrors&&t.if((0,Ko.not)(u),()=>t.break())})})}}};wc.default=tS});var gh=w(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var rS=B(),nS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,rS.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"}};vc.default=nS});var yh=w(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var oS=Ce(),iS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:oS.validateUnion,error:{message:"must match a schema in anyOf"}};bc.default=iS});var _h=w($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Vo=N(),sS=B(),aS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Vo._)`{passingSchemas: ${e.passing}}`},cS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:aS,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 i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let f;(0,sS.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Vo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Vo._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,Vo.Name)})})}}};$c.default=cS});var wh=w(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var uS=B(),lS={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((i,s)=>{if((0,uS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};xc.default=lS});var $h=w(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Ho=N(),bh=B(),dS={message:({params:e})=>(0,Ho.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ho._)`{failingKeyword: ${e.ifClause}}`},fS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:dS,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,bh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=vh(n,"then"),i=vh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,Ho.not)(a),l("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let f=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(f,s),d?t.assign(d,(0,Ho._)`${u}`):e.setParams({ifClause:u})}}}};function vh(e,t){let r=e.schema[t];return r!==void 0&&!(0,bh.alwaysValidSchema)(e,r)}kc.default=fS});var xh=w(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var pS=B(),mS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,pS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Sc.default=mS});var kh=w(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var hS=cc(),gS=eh(),yS=uc(),_S=rh(),wS=nh(),vS=sh(),bS=ch(),$S=gc(),xS=dh(),kS=hh(),SS=gh(),ES=yh(),TS=_h(),PS=wh(),zS=$h(),RS=xh();function IS(e=!1){let t=[SS.default,ES.default,TS.default,PS.default,zS.default,RS.default,bS.default,$S.default,vS.default,xS.default,kS.default];return e?t.push(gS.default,_S.default):t.push(hS.default,yS.default),t.push(wS.default),t}Ec.default=IS});var Sh=w(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var ie=N(),OS={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},AS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:OS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),v=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(v,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(v,h)),e.fail$data((0,ie.or)(b(),$()));function b(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${v}`}function $(){let T=u.$async?(0,ie._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ie._)`${v}(${n})`,R=(0,ie._)`(typeof ${v} == "function" ? ${T} : ${v}.test(${n}))`;return(0,ie._)`${v} && ${v} !== true && ${_} === ${t} && !${R}`}}function p(){let m=d.formats[i];if(!m){b();return}if(m===!0)return;let[h,_,v]=$(m);h===t&&e.pass(T());function b(){if(c.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function $(R){let we=R instanceof RegExp?(0,ie.regexpCode)(R):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Re=r.scopeValue("formats",{key:i,ref:R,code:we});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,ie._)`${Re}.validate`]:["string",R,Re]}function T(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${v}(${n})`}return typeof _=="function"?(0,ie._)`${v}(${n})`:(0,ie._)`${v}.test(${n})`}}}};Tc.default=AS});var Eh=w(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var NS=Sh(),CS=[NS.default];Pc.default=CS});var Th=w(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.contentVocabulary=dr.metadataVocabulary=void 0;dr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];dr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var zh=w(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var DS=Dm(),jS=Jm(),MS=kh(),qS=Eh(),Ph=Th(),LS=[DS.default,jS.default,(0,MS.default)(),qS.default,Ph.metadataVocabulary,Ph.contentVocabulary];zc.default=LS});var Ih=w(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.DiscrError=void 0;var Rh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Rh||(Go.DiscrError=Rh={}))});var Ah=w(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var fr=N(),Rc=Ih(),Oh=Io(),BS=dn(),ZS=B(),US={message:({params:{discrError:e,tagName:t}})=>e===Rc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,fr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},FS={keyword:"discriminator",type:"object",schemaType:"object",error:US,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.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(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,fr._)`${r}${(0,fr.getProperty)(a)}`);t.if((0,fr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Rc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let p=f();t.if(!1);for(let m in p)t.elseIf((0,fr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Rc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,fr.Name),m}function f(){var p;let m={},h=v(o),_=!0;for(let T=0;T<s.length;T++){let R=s[T];if(R?.$ref&&!(0,ZS.schemaHasRulesButRef)(R,i.self.RULES)){let Re=R.$ref;if(R=Oh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Re),R instanceof Oh.SchemaEnv&&(R=R.schema),R===void 0)throw new BS.default(i.opts.uriResolver,i.baseId,Re)}let we=(p=R?.properties)===null||p===void 0?void 0:p[a];if(typeof we!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||v(R)),b(we,T)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:T}){return Array.isArray(T)&&T.includes(a)}function b(T,R){if(T.const)$(T.const,R);else if(T.enum)for(let we of T.enum)$(we,R);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(T,R){if(typeof T!="string"||T in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[T]=R}}}};Ic.default=FS});var Nh=w((BD,KS)=>{KS.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 Ac=w((ee,Oc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var VS=Rm(),HS=zh(),GS=Ah(),Ch=Nh(),WS=["/properties"],Wo="http://json-schema.org/draft-07/schema",pr=class extends VS.default{_addVocabularies(){super._addVocabularies(),HS.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(GS.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Ch,WS):Ch;this.addMetaSchema(t,Wo,!1),this.refs["http://json-schema.org/schema"]=Wo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wo)?Wo:void 0)}};ee.Ajv=pr;Oc.exports=ee=pr;Oc.exports.Ajv=pr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=pr;var JS=ln();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return JS.KeywordCxt}});var mr=N();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return mr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return mr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return mr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return mr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return mr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return mr.CodeGen}});var QS=zo();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return QS.default}});var YS=dn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return YS.default}})});var Uh=w(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.formatNames=rt.fastFormats=rt.fullFormats=void 0;function tt(e,t){return{validate:e,compare:t}}rt.fullFormats={date:tt(qh,jc),time:tt(Cc(!0),Mc),"date-time":tt(Dh(!0),Bh),"iso-time":tt(Cc(),Lh),"iso-date-time":tt(Dh(),Zh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:oE,"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:dE,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:iE,int32:{type:"number",validate:cE},int64:{type:"number",validate:uE},float:{type:"number",validate:Mh},double:{type:"number",validate:Mh},password:!0,binary:!0};rt.fastFormats={...rt.fullFormats,date:tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jc),time:tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Mc),"date-time":tt(/^\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,Bh),"iso-time":tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Lh),"iso-date-time":tt(/^\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,Zh),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};rt.formatNames=Object.keys(rt.fullFormats);function XS(e){return e%4===0&&(e%100!==0||e%400===0)}var eE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qh(e){let t=eE.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&&XS(r)?29:tE[n])}function jc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Nc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cc(e){return function(r){let n=Nc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&s<61}}function Mc(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 Lh(e,t){if(!(e&&t))return;let r=Nc.exec(e),n=Nc.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 Dc=/t|\s/i;function Dh(e){let t=Cc(e);return function(n){let o=n.split(Dc);return o.length===2&&qh(o[0])&&t(o[1])}}function Bh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Zh(e,t){if(!(e&&t))return;let[r,n]=e.split(Dc),[o,i]=t.split(Dc),s=jc(r,o);if(s!==void 0)return s||Mc(n,i)}var rE=/\/|:/,nE=/^(?:[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 oE(e){return rE.test(e)&&nE.test(e)}var jh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iE(e){return jh.lastIndex=0,jh.test(e)}var sE=-(2**31),aE=2**31-1;function cE(e){return Number.isInteger(e)&&e<=aE&&e>=sE}function uE(e){return Number.isInteger(e)}function Mh(){return!0}var lE=/[^\\]\\Z/;function dE(e){if(lE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Fh=w(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatLimitDefinition=void 0;var fE=Ac(),Ke=N(),xt=Ke.operators,Jo={formatMaximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},formatMinimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},formatExclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},formatExclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},pE={message:({keyword:e,schemaCode:t})=>(0,Ke.str)`should be ${Jo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ke._)`{comparison: ${Jo[e].okStr}, limit: ${t}}`};hr.formatLimitDefinition={keyword:Object.keys(Jo),type:"string",schemaType:"string",$data:!0,error:pE,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new fE.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,Ke._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ke.or)((0,Ke._)`typeof ${p} != "object"`,(0,Ke._)`${p} instanceof RegExp`,(0,Ke._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Ke._)`${s.code.formats}${(0,Ke.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ke._)`${f}.compare(${r}, ${n}) ${Jo[o].fail} 0`}},dependencies:["format"]};var mE=e=>(e.addKeyword(hr.formatLimitDefinition),e);hr.default=mE});var Gh=w((Sn,Hh)=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});var gr=Uh(),hE=Fh(),qc=N(),Kh=new qc.Name("fullFormats"),gE=new qc.Name("fastFormats"),Lc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Vh(e,t,gr.fullFormats,Kh),e;let[r,n]=t.mode==="fast"?[gr.fastFormats,gE]:[gr.fullFormats,Kh],o=t.formats||gr.formatNames;return Vh(e,o,r,n),t.keywords&&(0,hE.default)(e),e};Lc.get=(e,t="full")=>{let n=(t==="fast"?gr.fastFormats:gr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Vh(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,qc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Hh.exports=Sn=Lc;Object.defineProperty(Sn,"__esModule",{value:!0});Sn.default=Lc});var ng=w((tj,rg)=>{rg.exports=tg;tg.sync=vE;var Xh=dt("fs");function wE(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function eg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:wE(t,r)}function tg(e,t,r){Xh.stat(e,function(n,o){r(n,n?!1:eg(o,e,t))})}function vE(e,t){return eg(Xh.statSync(e),e,t)}});var cg=w((rj,ag)=>{ag.exports=ig;ig.sync=bE;var og=dt("fs");function ig(e,t,r){og.stat(e,function(n,o){r(n,n?!1:sg(o,t))})}function bE(e,t){return sg(og.statSync(e),t)}function sg(e,t){return e.isFile()&&$E(e,t)}function $E(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var lg=w((oj,ug)=>{var nj=dt("fs"),ti;process.platform==="win32"||global.TESTING_WINDOWS?ti=ng():ti=cg();ug.exports=Bc;Bc.sync=xE;function Bc(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Bc(e,t||{},function(i,s){i?o(i):n(s)})})}ti(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function xE(e,t){try{return ti.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var yg=w((ij,gg)=>{var yr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",dg=dt("path"),kE=yr?";":":",fg=lg(),pg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),mg=(e,t)=>{let r=t.colon||kE,n=e.match(/\//)||yr&&e.match(/\\/)?[""]:[...yr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=yr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=yr?o.split(r):[""];return yr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},hg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=mg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(pg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=dg.join(p,e),h=!p&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;u(c(h,l,0))}),c=(l,u,d)=>new Promise((f,p)=>{if(d===o.length)return f(a(u+1));let m=o[d];fg(l+m,{pathExt:i},(h,_)=>{if(!h&&_)if(t.all)s.push(l+m);else return f(l+m);return f(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},SE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=mg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=dg.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let f=u+n[d];try{if(fg.sync(f,{pathExt:o}))if(t.all)i.push(f);else return f}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw pg(e)};gg.exports=hg;hg.sync=SE});var wg=w((sj,Zc)=>{"use strict";var _g=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Zc.exports=_g;Zc.exports.default=_g});var xg=w((aj,$g)=>{"use strict";var vg=dt("path"),EE=yg(),TE=wg();function bg(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=EE.sync(e.command,{path:r[TE({env:r})],pathExt:t?vg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=vg.resolve(o?e.options.cwd:"",s)),s}function PE(e){return bg(e)||bg(e,!0)}$g.exports=PE});var kg=w((cj,Fc)=>{"use strict";var Uc=/([()\][%!^"`<>&|;, *?])/g;function zE(e){return e=e.replace(Uc,"^$1"),e}function RE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Uc,"^$1"),t&&(e=e.replace(Uc,"^$1")),e}Fc.exports.command=zE;Fc.exports.argument=RE});var Eg=w((uj,Sg)=>{"use strict";Sg.exports=/^#!(.*)/});var Pg=w((lj,Tg)=>{"use strict";var IE=Eg();Tg.exports=(e="")=>{let t=e.match(IE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Rg=w((dj,zg)=>{"use strict";var Kc=dt("fs"),OE=Pg();function AE(e){let r=Buffer.alloc(150),n;try{n=Kc.openSync(e,"r"),Kc.readSync(n,r,0,150,0),Kc.closeSync(n)}catch{}return OE(r.toString())}zg.exports=AE});var Ng=w((fj,Ag)=>{"use strict";var NE=dt("path"),Ig=xg(),Og=kg(),CE=Rg(),DE=process.platform==="win32",jE=/\.(?:com|exe)$/i,ME=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function qE(e){e.file=Ig(e);let t=e.file&&CE(e.file);return t?(e.args.unshift(e.file),e.command=t,Ig(e)):e.file}function LE(e){if(!DE)return e;let t=qE(e),r=!jE.test(t);if(e.options.forceShell||r){let n=ME.test(t);e.command=NE.normalize(e.command),e.command=Og.command(e.command),e.args=e.args.map(i=>Og.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function BE(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:LE(n)}Ag.exports=BE});var jg=w((pj,Dg)=>{"use strict";var Vc=process.platform==="win32";function Hc(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function ZE(e,t){if(!Vc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Cg(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Cg(e,t){return Vc&&e===1&&!t.file?Hc(t.original,"spawn"):null}function UE(e,t){return Vc&&e===1&&!t.file?Hc(t.original,"spawnSync"):null}Dg.exports={hookChildProcess:ZE,verifyENOENT:Cg,verifyENOENTSync:UE,notFoundError:Hc}});var Lg=w((mj,_r)=>{"use strict";var Mg=dt("child_process"),Gc=Ng(),Wc=jg();function qg(e,t,r){let n=Gc(e,t,r),o=Mg.spawn(n.command,n.args,n.options);return Wc.hookChildProcess(o,n),o}function FE(e,t,r){let n=Gc(e,t,r),o=Mg.spawnSync(n.command,n.args,n.options);return o.error=o.error||Wc.verifyENOENTSync(o.status,n),o}_r.exports=qg;_r.exports.spawn=qg;_r.exports.sync=FE;_r.exports._parse=Gc;_r.exports._enoent=Wc});import{readFile as OR,mkdir as AR,writeFile as NR}from"node:fs/promises";import{dirname as CR,join as s_}from"node:path";var eI=Object.freeze({status:"aborted"});function y(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var tI=Symbol("zod_brand"),ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ln={};function Ie(e){return e&&Object.assign(Ln,e),Ln}var F={};Au(F,{BIGINT_FORMAT_RANGES:()=>Cu,Class:()=>Ii,NUMBER_FORMAT_RANGES:()=>qi,aborted:()=>Tt,allowsEval:()=>Di,assert:()=>__,assertEqual:()=>m_,assertIs:()=>g_,assertNever:()=>y_,assertNotEqual:()=>h_,assignProp:()=>Ci,cached:()=>zr,captureStackTrace:()=>Zn,cleanEnum:()=>I_,cleanRegex:()=>Ir,clone:()=>Je,createTransparentProxy:()=>k_,defineLazy:()=>G,esc:()=>Et,escapeRegex:()=>ft,extend:()=>T_,finalizeIssue:()=>qe,floatSafeRemainder:()=>Ni,getElementAtPath:()=>w_,getEnumValues:()=>Oi,getLengthableOrigin:()=>Or,getParsedType:()=>x_,getSizableOrigin:()=>Du,isObject:()=>Ht,isPlainObject:()=>Gt,issue:()=>Li,joinValues:()=>Bn,jsonStringifyReplacer:()=>Ai,merge:()=>P_,normalizeParams:()=>P,nullish:()=>Rr,numKeys:()=>$_,omit:()=>E_,optionalKeys:()=>Mi,partial:()=>z_,pick:()=>S_,prefixIssues:()=>Qe,primitiveTypes:()=>Nu,promiseAllObject:()=>v_,propertyKeyTypes:()=>ji,randomString:()=>b_,required:()=>R_,stringifyPrimitive:()=>Un,unwrapMessage:()=>Pr});function m_(e){return e}function h_(e){return e}function g_(e){}function y_(e){throw new Error}function __(e){}function Oi(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 Bn(e,t="|"){return e.map(r=>Un(r)).join(t)}function Ai(e,t){return typeof t=="bigint"?t.toString():t}function zr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Rr(e){return e==null}function Ir(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ni(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function G(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 Ci(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function w_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function v_(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function b_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Et(e){return JSON.stringify(e)}var Zn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Di=zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Gt(e){if(Ht(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Ht(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function $_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var x_=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}`)}},ji=new Set(["string","number","symbol"]),Nu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function P(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 k_(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},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 Un(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Mi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var qi={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]},Cu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function S_(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 Je(e,{...e._zod.def,shape:r,checks:[]})}function E_(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 Je(e,{...e._zod.def,shape:r,checks:[]})}function T_(e,t){if(!Gt(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 Ci(this,"shape",n),n},checks:[]};return Je(e,r)}function P_(e,t){return Je(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function z_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Je(t,{...t._zod.def,shape:o,checks:[]})}function R_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Je(t,{...t._zod.def,shape:o,checks:[]})}function Tt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Qe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Pr(e){return typeof e=="string"?e:e?.message}function qe(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Pr(e.inst?._zod.def?.error?.(e))??Pr(t?.error?.(e))??Pr(r.customError?.(e))??Pr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Du(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Or(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Li(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function I_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ii=class{constructor(...t){}};var ju=(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,Ai,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fn=y("$ZodError",ju),Bi=y("$ZodError",ju,{Parent:Error});function Mu(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 qu(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var Lu=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ot;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>qe(c,i,Ie())));throw Zn(a,o?.callee),a}return s.value};var Bu=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>qe(c,i,Ie())));throw Zn(a,o?.callee),a}return s.value};var Zi=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ot;return i.issues.length?{success:!1,error:new(e??Fn)(i.issues.map(s=>qe(s,o,Ie())))}:{success:!0,data:i.value}},Ar=Zi(Bi),Ui=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>qe(s,o,Ie())))}:{success:!0,data:i.value}},Kn=Ui(Bi);var Zu=/^[cC][^\s-]{8,}$/,Uu=/^[0-9a-z]+$/,Fu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ku=/^[0-9a-vA-V]{20}$/,Vu=/^[A-Za-z0-9]{27}$/,Hu=/^[a-zA-Z0-9_-]{21}$/,Gu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Wu=/^([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 Ju=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var A_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qu(){return new RegExp(A_,"u")}var Yu=/^(?:(?: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])$/,Xu=/^(([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})$/,el=/^((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])$/,tl=/^(([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])$/,rl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ki=/^[A-Za-z0-9_-]*$/,nl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var ol=/^\+(?:[0-9]){6,14}[0-9]$/,il="(?:(?:\\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])))",sl=new RegExp(`^${il}$`);function al(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 cl(e){return new RegExp(`^${al(e)}$`)}function ul(e){let t=al({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(`^${il}T(?:${n})$`)}var ll=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var dl=/^\d+$/,fl=/^-?\d+(?:\.\d+)?/i,pl=/true|false/i,ml=/null/i;var hl=/^[^A-Z]*$/,gl=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),yl={number:"number",bigint:"bigint",object:"date"},Hi=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=yl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(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=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=yl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(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})}}),_l=y("$ZodCheckMultipleOf",(e,t)=>{me.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):Ni(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})}}),wl=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=qi[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=dl)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.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}):s.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&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var vl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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 s=Or(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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 s=Or(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$l=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Rr(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,i=o.length;if(i===t.length)return;let s=Or(o),a=i>t.length;n.issues.push({origin:s,...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})}}),Nr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.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=()=>{})}),xl=y("$ZodCheckRegex",(e,t)=>{Nr.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})}}),kl=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=hl),Nr.init(e,t)}),Sl=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=gl),Nr.init(e,t)}),El=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=ft(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Tl=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${ft(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})}}),Pl=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${ft(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 zl=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Vn=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
11
  `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
12
- `))}};var Il={major:4,minor:0,patch:0};var W=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Il;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=Tt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new ot;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Tt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Tt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new ot;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Or(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Vn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Gn=y("$ZodString",(e,t)=>{W.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ll(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}}),Q=y("$ZodStringFormat",(e,t)=>{Nr.init(e,t),Gn.init(e,t)}),Ll=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wu),Q.init(e,t)}),Zl=y("$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());Q.init(e,t)}),Ul=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ju),Q.init(e,t)}),Fl=y("$ZodURL",(e,t)=>{Q.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=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:nl.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("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Vl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qu()),Q.init(e,t)}),Kl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hu),Q.init(e,t)}),Hl=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zu),Q.init(e,t)}),Gl=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Uu),Q.init(e,t)}),Wl=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Fu),Q.init(e,t)}),Jl=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vu),Q.init(e,t)}),Ql=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ku),Q.init(e,t)}),Yl=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ul(t)),Q.init(e,t)}),Xl=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=sl),Q.init(e,t)}),ed=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cl(t)),Q.init(e,t)}),td=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Gu),Q.init(e,t)}),rd=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Yu),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),nd=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Xu),Q.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})}}}),od=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=el),Q.init(e,t)}),id=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tl),Q.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>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 sd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ad=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rl),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{sd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function N_(e){if(!Vi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sd(r)}var cd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Vi),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{N_(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ud=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ol),Q.init(e,t)});function C_(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 ld=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{C_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ji=y("$ZodNumber",(e,t)=>{W.init(e,t),e._zod.pattern=e._zod.bag.pattern??fl,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 i=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,...i?{received:i}:{}}),r}}),dd=y("$ZodNumber",(e,t)=>{wl.init(e,t),Ji.init(e,t)}),fd=y("$ZodBoolean",(e,t)=>{W.init(e,t),e._zod.pattern=pl,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}});var pd=y("$ZodNull",(e,t)=>{W.init(e,t),e._zod.pattern=ml,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}});var md=y("$ZodUnknown",(e,t)=>{W.init(e,t),e._zod.parse=r=>r}),hd=y("$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)});function Al(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}var gd=y("$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 i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>Al(l,r,s))):Al(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Hn(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}function Ol(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(...Qe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var yd=y("$ZodObject",(e,t)=>{W.init(e,t);let r=zr(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof W))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=Mi(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});G(e._zod,"propValues",()=>{let d=t.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let h of m.values)f[p].add(h)}}return f});let n=d=>{let f=new Kn(["shape","payload","ctx"]),p=r.value,m=v=>{let $=Et(v);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let v of p.keys)h[v]=`key_${_++}`;f.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let $=h[v];f.write(`const ${$} = ${m(v)};`);let T=Et(v);f.write(`
12
+ `))}};var Il={major:4,minor:0,patch:0};var W=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Il;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=Tt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new ot;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Tt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Tt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new ot;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Ar(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Kn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Gn=y("$ZodString",(e,t)=>{W.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ll(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}}),Q=y("$ZodStringFormat",(e,t)=>{Nr.init(e,t),Gn.init(e,t)}),Bl=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wu),Q.init(e,t)}),Zl=y("$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());Q.init(e,t)}),Ul=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ju),Q.init(e,t)}),Fl=y("$ZodURL",(e,t)=>{Q.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=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:nl.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("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Kl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qu()),Q.init(e,t)}),Vl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hu),Q.init(e,t)}),Hl=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zu),Q.init(e,t)}),Gl=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Uu),Q.init(e,t)}),Wl=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Fu),Q.init(e,t)}),Jl=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ku),Q.init(e,t)}),Ql=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Vu),Q.init(e,t)}),Yl=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ul(t)),Q.init(e,t)}),Xl=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=sl),Q.init(e,t)}),ed=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cl(t)),Q.init(e,t)}),td=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Gu),Q.init(e,t)}),rd=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Yu),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),nd=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Xu),Q.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})}}}),od=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=el),Q.init(e,t)}),id=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tl),Q.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>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 sd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ad=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rl),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{sd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function N_(e){if(!Ki.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sd(r)}var cd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ki),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{N_(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ud=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ol),Q.init(e,t)});function C_(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 ld=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{C_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ji=y("$ZodNumber",(e,t)=>{W.init(e,t),e._zod.pattern=e._zod.bag.pattern??fl,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 i=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,...i?{received:i}:{}}),r}}),dd=y("$ZodNumber",(e,t)=>{wl.init(e,t),Ji.init(e,t)}),fd=y("$ZodBoolean",(e,t)=>{W.init(e,t),e._zod.pattern=pl,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}});var pd=y("$ZodNull",(e,t)=>{W.init(e,t),e._zod.pattern=ml,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}});var md=y("$ZodUnknown",(e,t)=>{W.init(e,t),e._zod.parse=r=>r}),hd=y("$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)});function Ol(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}var gd=y("$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 i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>Ol(l,r,s))):Ol(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Hn(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}function Al(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(...Qe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var yd=y("$ZodObject",(e,t)=>{W.init(e,t);let r=zr(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof W))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=Mi(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});G(e._zod,"propValues",()=>{let d=t.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let h of m.values)f[p].add(h)}}return f});let n=d=>{let f=new Vn(["shape","payload","ctx"]),p=r.value,m=b=>{let $=Et(b);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let b of p.keys)h[b]=`key_${_++}`;f.write("const newResult = {}");for(let b of p.keys)if(p.optionalKeys.has(b)){let $=h[b];f.write(`const ${$} = ${m(b)};`);let T=Et(b);f.write(`
13
13
  if (${$}.issues.length) {
14
14
  if (input[${T}] === undefined) {
15
15
  if (${T} in input) {
@@ -28,35 +28,35 @@ var c_=Object.create;var Pi=Object.defineProperty;var u_=Object.getOwnPropertyDe
28
28
  } else {
29
29
  newResult[${T}] = ${$}.value;
30
30
  }
31
- `)}else{let $=h[v];f.write(`const ${$} = ${m(v)};`),f.write(`
31
+ `)}else{let $=h[b];f.write(`const ${$} = ${m(b)};`),f.write(`
32
32
  if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
33
33
  ...iss,
34
- path: iss.path ? [${Et(v)}, ...iss.path] : [${Et(v)}]
35
- })));`),f.write(`newResult[${Et(v)}] = ${$}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(v,$)=>b(d,v,$)},o,i=Ht,s=!Bn.jitless,c=s&&Di.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let $=u.shape;for(let T of u.keys){let R=$[T],we=R._zod.run({value:p[T],issues:[]},f),Re=R._zod.optin==="optional"&&R._zod.optout==="optional";we instanceof Promise?m.push(we.then(Kt=>Re?Ol(Kt,d,T,p):Hn(Kt,d,T))):Re?Ol(we,d,T,p):Hn(we,d,T)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,b=l._zod,v=b.def.type;for(let $ of Object.keys(p)){if(_.has($))continue;if(v==="never"){h.push($);continue}let T=b.run({value:p[$],issues:[]},f);T instanceof Promise?m.push(T.then(R=>Hn(R,d,$))):Hn(T,d,$)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function Nl(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(i=>qe(i,n,Ie())))}),t}var Qi=y("$ZodUnion",(e,t)=>{W.init(e,t),G(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),G(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),G(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),G(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=>Ir(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>Nl(s,r,e,n)):Nl(i,r,e,n)}}),_d=y("$ZodDiscriminatedUnion",(e,t)=>{Qi.init(e,t);let r=e._zod.parse;G(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=zr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Ht(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),wd=y("$ZodIntersection",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>Cl(r,c,l)):Cl(r,i,s)}});function Wi(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(Gt(e)&&Gt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=Wi(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],i=t[n],s=Wi(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Cl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Tt(e))return e;let n=Wi(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 bd=y("$ZodRecord",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Gt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Qe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Qe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.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 s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,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(l=>qe(l,n,Ie())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Qe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Qe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var vd=y("$ZodEnum",(e,t)=>{W.init(e,t);let r=Ai(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>ji.has(typeof n)).map(n=>typeof n=="string"?ft(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),$d=y("$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"?ft(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 xd=y("$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(s=>(r.value=s,r));if(o instanceof Promise)throw new ot;return r.value=o,r}}),kd=y("$ZodOptional",(e,t)=>{W.init(e,t),e._zod.optin="optional",e._zod.optout="optional",G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),G(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ir(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)}),Sd=y("$ZodNullable",(e,t)=>{W.init(e,t),G(e._zod,"optin",()=>t.innerType._zod.optin),G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ir(r.source)}|null)$`):void 0}),G(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)}),Ed=y("$ZodDefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(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(i=>Dl(i,t)):Dl(o,t)}});function Dl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Td=y("$ZodPrefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(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))}),Pd=y("$ZodNonOptional",(e,t)=>{W.init(e,t),G(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(i=>jl(i,e)):jl(o,e)}});function jl(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 zd=y("$ZodCatch",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(e._zod,"optout",()=>t.innerType._zod.optout),G(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(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>qe(s,n,Ie()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>qe(i,n,Ie()))},input:r.value}),r.issues=[]),r)}});var Rd=y("$ZodPipe",(e,t)=>{W.init(e,t),G(e._zod,"values",()=>t.in._zod.values),G(e._zod,"optin",()=>t.in._zod.optin),G(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(i=>Ml(i,t,n)):Ml(o,t,n)}});function Ml(e,t,r){return Tt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Id=y("$ZodReadonly",(e,t)=>{W.init(e,t),G(e._zod,"propValues",()=>t.innerType._zod.propValues),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"optin",()=>t.innerType._zod.optin),G(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(ql):ql(o)}});function ql(e){return e.value=Object.freeze(e.value),e}var Ad=y("$ZodCustom",(e,t)=>{me.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(i=>Bl(i,r,n,e));Bl(o,r,n,e)}});function Bl(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(Bi(o))}}var D_=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},j_=()=>{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 ${D_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Un(n.values[0])}`:`Invalid option: expected one of ${Ln(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.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":""}: ${Ln(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 Od(){return{localeError:j_()}}var mI=Symbol("ZodOutput"),hI=Symbol("ZodInput"),Yi=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 M_(){return new Yi}var Cr=M_();function Nd(e,t){return new e({type:"string",...P(t)})}function Cd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Xi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function Dd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function Md(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function qd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Bd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Ld(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Zd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Ud(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Fd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function Vd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function Kd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Hd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function Gd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function Wd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Jd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Qd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function Xd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function ef(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function tf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function rf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function nf(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function of(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function sf(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function af(e,t){return new e({type:"number",checks:[],...P(t)})}function cf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function uf(e,t){return new e({type:"boolean",...P(t)})}function lf(e,t){return new e({type:"null",...P(t)})}function df(e){return new e({type:"unknown"})}function ff(e,t){return new e({type:"never",...P(t)})}function Wn(e,t){return new Hi({check:"less_than",...P(t),value:e,inclusive:!1})}function Dr(e,t){return new Hi({check:"less_than",...P(t),value:e,inclusive:!0})}function Jn(e,t){return new Gi({check:"greater_than",...P(t),value:e,inclusive:!1})}function jr(e,t){return new Gi({check:"greater_than",...P(t),value:e,inclusive:!0})}function Qn(e,t){return new _l({check:"multiple_of",...P(t),value:e})}function Yn(e,t){return new bl({check:"max_length",...P(t),maximum:e})}function Wt(e,t){return new vl({check:"min_length",...P(t),minimum:e})}function Xn(e,t){return new $l({check:"length_equals",...P(t),length:e})}function es(e,t){return new xl({check:"string_format",format:"regex",...P(t),pattern:e})}function ts(e){return new kl({check:"string_format",format:"lowercase",...P(e)})}function rs(e){return new Sl({check:"string_format",format:"uppercase",...P(e)})}function ns(e,t){return new El({check:"string_format",format:"includes",...P(t),includes:e})}function os(e,t){return new Tl({check:"string_format",format:"starts_with",...P(t),prefix:e})}function is(e,t){return new Pl({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Pt(e){return new zl({check:"overwrite",tx:e})}function ss(e){return Pt(t=>t.normalize(e))}function as(){return Pt(e=>e.trim())}function cs(){return Pt(e=>e.toLowerCase())}function us(){return Pt(e=>e.toUpperCase())}function pf(e,t,r){return new e({type:"array",element:t,...P(r)})}function mf(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function hf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function Jt(e){return!!e._zod}function Be(e,t){return Jt(e)?Or(e,t):e.safeParse(t)}function eo(e){if(!e)return;let t;if(Jt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function gf(e){if(Jt(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.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 qr={};Ou(qr,{ZodISODate:()=>_f,ZodISODateTime:()=>yf,ZodISODuration:()=>bf,ZodISOTime:()=>wf,date:()=>ds,datetime:()=>ls,duration:()=>ps,time:()=>fs});var yf=y("ZodISODateTime",(e,t)=>{Yl.init(e,t),te.init(e,t)});function ls(e){return rf(yf,e)}var _f=y("ZodISODate",(e,t)=>{Xl.init(e,t),te.init(e,t)});function ds(e){return nf(_f,e)}var wf=y("ZodISOTime",(e,t)=>{ed.init(e,t),te.init(e,t)});function fs(e){return of(wf,e)}var bf=y("ZodISODuration",(e,t)=>{td.init(e,t),te.init(e,t)});function ps(e){return sf(bf,e)}var vf=(e,t)=>{Fn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>qu(e,r)},flatten:{value:r=>Mu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},WI=y("ZodError",vf),Br=y("ZodError",vf,{Parent:Error});var $f=Bu(Br),xf=Lu(Br),kf=Zi(Br),Sf=Ui(Br);var oe=y("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)=>Je(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>$f(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>kf(e,r,n),e.parseAsync=async(r,n)=>xf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Sf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Cw(r,n)),e.superRefine=r=>e.check(Dw(r)),e.overwrite=r=>e.check(Pt(r)),e.optional=()=>ne(e),e.nullable=()=>Pf(e),e.nullish=()=>ne(Pf(e)),e.nonoptional=r=>Pw(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>ro(e,r),e.transform=r=>hs(e,Nf(r)),e.default=r=>Sw(e,r),e.prefault=r=>Tw(e,r),e.catch=r=>Rw(e,r),e.pipe=r=>hs(e,r),e.readonly=()=>Ow(e),e.describe=r=>{let n=e.clone();return Cr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Cr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Cr.get(e);let n=e.clone();return Cr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),zf=y("_ZodString",(e,t)=>{Gn.init(e,t),oe.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(es(...n)),e.includes=(...n)=>e.check(ns(...n)),e.startsWith=(...n)=>e.check(os(...n)),e.endsWith=(...n)=>e.check(is(...n)),e.min=(...n)=>e.check(Wt(...n)),e.max=(...n)=>e.check(Yn(...n)),e.length=(...n)=>e.check(Xn(...n)),e.nonempty=(...n)=>e.check(Wt(1,...n)),e.lowercase=n=>e.check(ts(n)),e.uppercase=n=>e.check(rs(n)),e.trim=()=>e.check(as()),e.normalize=(...n)=>e.check(ss(...n)),e.toLowerCase=()=>e.check(cs()),e.toUpperCase=()=>e.check(us())}),H_=y("ZodString",(e,t)=>{Gn.init(e,t),zf.init(e,t),e.email=r=>e.check(Cd(G_,r)),e.url=r=>e.check(Bd(W_,r)),e.jwt=r=>e.check(tf(lw,r)),e.emoji=r=>e.check(Ld(J_,r)),e.guid=r=>e.check(Xi(Ef,r)),e.uuid=r=>e.check(Dd(to,r)),e.uuidv4=r=>e.check(jd(to,r)),e.uuidv6=r=>e.check(Md(to,r)),e.uuidv7=r=>e.check(qd(to,r)),e.nanoid=r=>e.check(Zd(Q_,r)),e.guid=r=>e.check(Xi(Ef,r)),e.cuid=r=>e.check(Ud(Y_,r)),e.cuid2=r=>e.check(Fd(X_,r)),e.ulid=r=>e.check(Vd(ew,r)),e.base64=r=>e.check(Yd(aw,r)),e.base64url=r=>e.check(Xd(cw,r)),e.xid=r=>e.check(Kd(tw,r)),e.ksuid=r=>e.check(Hd(rw,r)),e.ipv4=r=>e.check(Gd(nw,r)),e.ipv6=r=>e.check(Wd(ow,r)),e.cidrv4=r=>e.check(Jd(iw,r)),e.cidrv6=r=>e.check(Qd(sw,r)),e.e164=r=>e.check(ef(uw,r)),e.datetime=r=>e.check(ls(r)),e.date=r=>e.check(ds(r)),e.time=r=>e.check(fs(r)),e.duration=r=>e.check(ps(r))});function g(e){return Nd(H_,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),zf.init(e,t)}),G_=y("ZodEmail",(e,t)=>{Ul.init(e,t),te.init(e,t)});var Ef=y("ZodGUID",(e,t)=>{Ll.init(e,t),te.init(e,t)});var to=y("ZodUUID",(e,t)=>{Zl.init(e,t),te.init(e,t)});var W_=y("ZodURL",(e,t)=>{Fl.init(e,t),te.init(e,t)});var J_=y("ZodEmoji",(e,t)=>{Vl.init(e,t),te.init(e,t)});var Q_=y("ZodNanoID",(e,t)=>{Kl.init(e,t),te.init(e,t)});var Y_=y("ZodCUID",(e,t)=>{Hl.init(e,t),te.init(e,t)});var X_=y("ZodCUID2",(e,t)=>{Gl.init(e,t),te.init(e,t)});var ew=y("ZodULID",(e,t)=>{Wl.init(e,t),te.init(e,t)});var tw=y("ZodXID",(e,t)=>{Jl.init(e,t),te.init(e,t)});var rw=y("ZodKSUID",(e,t)=>{Ql.init(e,t),te.init(e,t)});var nw=y("ZodIPv4",(e,t)=>{rd.init(e,t),te.init(e,t)});var ow=y("ZodIPv6",(e,t)=>{nd.init(e,t),te.init(e,t)});var iw=y("ZodCIDRv4",(e,t)=>{od.init(e,t),te.init(e,t)});var sw=y("ZodCIDRv6",(e,t)=>{id.init(e,t),te.init(e,t)});var aw=y("ZodBase64",(e,t)=>{ad.init(e,t),te.init(e,t)});var cw=y("ZodBase64URL",(e,t)=>{cd.init(e,t),te.init(e,t)});var uw=y("ZodE164",(e,t)=>{ud.init(e,t),te.init(e,t)});var lw=y("ZodJWT",(e,t)=>{ld.init(e,t),te.init(e,t)});var Rf=y("ZodNumber",(e,t)=>{Ji.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(Jn(n,o)),e.gte=(n,o)=>e.check(jr(n,o)),e.min=(n,o)=>e.check(jr(n,o)),e.lt=(n,o)=>e.check(Wn(n,o)),e.lte=(n,o)=>e.check(Dr(n,o)),e.max=(n,o)=>e.check(Dr(n,o)),e.int=n=>e.check(Tf(n)),e.safe=n=>e.check(Tf(n)),e.positive=n=>e.check(Jn(0,n)),e.nonnegative=n=>e.check(jr(0,n)),e.negative=n=>e.check(Wn(0,n)),e.nonpositive=n=>e.check(Dr(0,n)),e.multipleOf=(n,o)=>e.check(Qn(n,o)),e.step=(n,o)=>e.check(Qn(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 V(e){return af(Rf,e)}var dw=y("ZodNumberFormat",(e,t)=>{dd.init(e,t),Rf.init(e,t)});function Tf(e){return cf(dw,e)}var fw=y("ZodBoolean",(e,t)=>{fd.init(e,t),oe.init(e,t)});function ce(e){return uf(fw,e)}var pw=y("ZodNull",(e,t)=>{pd.init(e,t),oe.init(e,t)});function If(e){return lf(pw,e)}var mw=y("ZodUnknown",(e,t)=>{md.init(e,t),oe.init(e,t)});function re(){return df(mw)}var hw=y("ZodNever",(e,t)=>{hd.init(e,t),oe.init(e,t)});function gw(e){return ff(hw,e)}var yw=y("ZodArray",(e,t)=>{gd.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Wt(r,n)),e.nonempty=r=>e.check(Wt(1,r)),e.max=(r,n)=>e.check(Yn(r,n)),e.length=(r,n)=>e.check(Xn(r,n)),e.unwrap=()=>e.element});function q(e,t){return pf(yw,e,t)}var Af=y("ZodObject",(e,t)=>{yd.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ke(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:gw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(Cf,e,r[0]),e.required=(...r)=>F.required(Df,e,r[0])});function x(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new Af(r)}function be(e,t){return new Af({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var Of=y("ZodUnion",(e,t)=>{Qi.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new Of({type:"union",options:e,...F.normalizeParams(t)})}var _w=y("ZodDiscriminatedUnion",(e,t)=>{Of.init(e,t),_d.init(e,t)});function gs(e,t,r){return new _w({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var ww=y("ZodIntersection",(e,t)=>{wd.init(e,t),oe.init(e,t)});function ro(e,t){return new ww({type:"intersection",left:e,right:t})}var bw=y("ZodRecord",(e,t)=>{bd.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new bw({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var ms=y("ZodEnum",(e,t)=>{vd.init(e,t),oe.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 i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ms({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ms({...t,checks:[],...F.normalizeParams(o),entries:i})}});function ke(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ms({type:"enum",entries:r,...F.normalizeParams(t)})}var vw=y("ZodLiteral",(e,t)=>{$d.init(e,t),oe.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 k(e,t){return new vw({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var $w=y("ZodTransform",(e,t)=>{xd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Nf(e){return new $w({type:"transform",transform:e})}var Cf=y("ZodOptional",(e,t)=>{kd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new Cf({type:"optional",innerType:e})}var xw=y("ZodNullable",(e,t)=>{Sd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pf(e){return new xw({type:"nullable",innerType:e})}var kw=y("ZodDefault",(e,t)=>{Ed.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Sw(e,t){return new kw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Ew=y("ZodPrefault",(e,t)=>{Td.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tw(e,t){return new Ew({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Df=y("ZodNonOptional",(e,t)=>{Pd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pw(e,t){return new Df({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var zw=y("ZodCatch",(e,t)=>{zd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rw(e,t){return new zw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Iw=y("ZodPipe",(e,t)=>{Rd.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function hs(e,t){return new Iw({type:"pipe",in:e,out:t})}var Aw=y("ZodReadonly",(e,t)=>{Id.init(e,t),oe.init(e,t)});function Ow(e){return new Aw({type:"readonly",innerType:e})}var jf=y("ZodCustom",(e,t)=>{Ad.init(e,t),oe.init(e,t)});function Nw(e){let t=new me({check:"custom"});return t._zod.check=e,t}function Mf(e,t){return mf(jf,e??(()=>!0),t)}function Cw(e,t={}){return hf(jf,e,t)}function Dw(e){let t=Nw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.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(F.issue(o))}},e(r.value,r)));return t}function ys(e,t){return hs(Nf(e),t)}Ie(Od());var ws="2025-11-25";var qf=[ws,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],pt="io.modelcontextprotocol/related-task",oo="2.0",ae=Mf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Bf=Y([g(),V().int()]),Lf=g(),ZA=be({ttl:V().optional(),pollInterval:V().optional()}),jw=x({ttl:V().optional()}),Mw=x({taskId:g()}),bs=be({progressToken:Bf.optional(),[pt]:Mw.optional()}),ze=x({_meta:bs.optional()}),Lr=ze.extend({task:jw.optional()}),Zf=e=>Lr.safeParse(e).success,ue=x({method:g(),params:ze.loose().optional()}),Ae=x({_meta:bs.optional()}),Oe=x({method:g(),params:Ae.loose().optional()}),le=be({_meta:bs.optional()}),io=Y([g(),V().int()]),Uf=x({jsonrpc:k(oo),id:io,...ue.shape}).strict(),vs=e=>Uf.safeParse(e).success,Ff=x({jsonrpc:k(oo),...Oe.shape}).strict(),Vf=e=>Ff.safeParse(e).success,$s=x({jsonrpc:k(oo),id:io,result:le}).strict(),Zr=e=>$s.safeParse(e).success;var I;(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"})(I||(I={}));var xs=x({jsonrpc:k(oo),id:io.optional(),error:x({code:V().int(),message:g(),data:re().optional()})}).strict();var Kf=e=>xs.safeParse(e).success;var Hf=Y([Uf,Ff,$s,xs]),UA=Y([$s,xs]),zt=le.strict(),qw=Ae.extend({requestId:io.optional(),reason:g().optional()}),so=Oe.extend({method:k("notifications/cancelled"),params:qw}),Bw=x({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:ke(["light","dark"]).optional()}),Ur=x({icons:q(Bw).optional()}),Qt=x({name:g(),title:g().optional()}),Gf=Qt.extend({...Qt.shape,...Ur.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Lw=ro(x({applyDefaults:ce().optional()}),J(g(),re())),Zw=ys(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ro(x({form:Lw.optional(),url:ae.optional()}),J(g(),re()).optional())),Uw=be({list:ae.optional(),cancel:ae.optional(),requests:be({sampling:be({createMessage:ae.optional()}).optional(),elicitation:be({create:ae.optional()}).optional()}).optional()}),Fw=be({list:ae.optional(),cancel:ae.optional(),requests:be({tools:be({call:ae.optional()}).optional()}).optional()}),Vw=x({experimental:J(g(),ae).optional(),sampling:x({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:Zw.optional(),roots:x({listChanged:ce().optional()}).optional(),tasks:Uw.optional(),extensions:J(g(),ae).optional()}),Kw=ze.extend({protocolVersion:g(),capabilities:Vw,clientInfo:Gf}),Hw=ue.extend({method:k("initialize"),params:Kw});var Gw=x({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:x({listChanged:ce().optional()}).optional(),resources:x({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:x({listChanged:ce().optional()}).optional(),tasks:Fw.optional(),extensions:J(g(),ae).optional()}),ks=le.extend({protocolVersion:g(),capabilities:Gw,serverInfo:Gf,instructions:g().optional()}),Ww=Oe.extend({method:k("notifications/initialized"),params:Ae.optional()});var ao=ue.extend({method:k("ping"),params:ze.optional()}),Jw=x({progress:V(),total:ne(V()),message:ne(g())}),Qw=x({...Ae.shape,...Jw.shape,progressToken:Bf}),co=Oe.extend({method:k("notifications/progress"),params:Qw}),Yw=ze.extend({cursor:Lf.optional()}),Fr=ue.extend({params:Yw.optional()}),Vr=le.extend({nextCursor:Lf.optional()}),Xw=ke(["working","input_required","completed","failed","cancelled"]),Kr=x({taskId:g(),status:Xw,ttl:Y([V(),If()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(V()),statusMessage:ne(g())}),Rt=le.extend({task:Kr}),eb=Ae.merge(Kr),Hr=Oe.extend({method:k("notifications/tasks/status"),params:eb}),uo=ue.extend({method:k("tasks/get"),params:ze.extend({taskId:g()})}),lo=le.merge(Kr),fo=ue.extend({method:k("tasks/result"),params:ze.extend({taskId:g()})}),FA=le.loose(),po=Fr.extend({method:k("tasks/list")}),mo=Vr.extend({tasks:q(Kr)}),ho=ue.extend({method:k("tasks/cancel"),params:ze.extend({taskId:g()})}),Wf=le.merge(Kr),Jf=x({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),Qf=Jf.extend({text:g()}),Ss=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yf=Jf.extend({blob:Ss}),Gr=ke(["user","assistant"]),Yt=x({audience:q(Gr).optional(),priority:V().min(0).max(1).optional(),lastModified:qr.datetime({offset:!0}).optional()}),Xf=x({...Qt.shape,...Ur.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(V()),annotations:Yt.optional(),_meta:ne(be({}))}),tb=x({...Qt.shape,...Ur.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:Yt.optional(),_meta:ne(be({}))}),rb=Fr.extend({method:k("resources/list")}),Es=Vr.extend({resources:q(Xf)}),nb=Fr.extend({method:k("resources/templates/list")}),Ts=Vr.extend({resourceTemplates:q(tb)}),Ps=ze.extend({uri:g()}),ob=Ps,ib=ue.extend({method:k("resources/read"),params:ob}),zs=le.extend({contents:q(Y([Qf,Yf]))}),Rs=Oe.extend({method:k("notifications/resources/list_changed"),params:Ae.optional()}),sb=Ps,ab=ue.extend({method:k("resources/subscribe"),params:sb}),cb=Ps,ub=ue.extend({method:k("resources/unsubscribe"),params:cb}),lb=Ae.extend({uri:g()}),db=Oe.extend({method:k("notifications/resources/updated"),params:lb}),fb=x({name:g(),description:ne(g()),required:ne(ce())}),pb=x({...Qt.shape,...Ur.shape,description:ne(g()),arguments:ne(q(fb)),_meta:ne(be({}))}),mb=Fr.extend({method:k("prompts/list")}),Is=Vr.extend({prompts:q(pb)}),hb=ze.extend({name:g(),arguments:J(g(),g()).optional()}),gb=ue.extend({method:k("prompts/get"),params:hb}),As=x({type:k("text"),text:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),Os=x({type:k("image"),data:Ss,mimeType:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),Ns=x({type:k("audio"),data:Ss,mimeType:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),yb=x({type:k("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),_b=x({type:k("resource"),resource:Y([Qf,Yf]),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),wb=Xf.extend({type:k("resource_link")}),Cs=Y([As,Os,Ns,wb,_b]),bb=x({role:Gr,content:Cs}),Ds=le.extend({description:g().optional(),messages:q(bb)}),js=Oe.extend({method:k("notifications/prompts/list_changed"),params:Ae.optional()}),vb=x({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),$b=x({taskSupport:ke(["required","optional","forbidden"]).optional()}),ep=x({...Qt.shape,...Ur.shape,description:g().optional(),inputSchema:x({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:x({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:vb.optional(),execution:$b.optional(),_meta:J(g(),re()).optional()}),xb=Fr.extend({method:k("tools/list")}),Ms=Vr.extend({tools:q(ep)}),mt=le.extend({content:q(Cs).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),VA=mt.or(le.extend({toolResult:re()})),kb=Lr.extend({name:g(),arguments:J(g(),re()).optional()}),Sb=ue.extend({method:k("tools/call"),params:kb}),qs=Oe.extend({method:k("notifications/tools/list_changed"),params:Ae.optional()}),tp=x({autoRefresh:ce().default(!0),debounceMs:V().int().nonnegative().default(300)}),rp=ke(["debug","info","notice","warning","error","critical","alert","emergency"]),Eb=ze.extend({level:rp}),Tb=ue.extend({method:k("logging/setLevel"),params:Eb}),Pb=Ae.extend({level:rp,logger:g().optional(),data:re()}),zb=Oe.extend({method:k("notifications/message"),params:Pb}),Rb=x({name:g().optional()}),Ib=x({hints:q(Rb).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),Ab=x({mode:ke(["auto","required","none"]).optional()}),Ob=x({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Cs).default([]),structuredContent:x({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),Nb=gs("type",[As,Os,Ns]),no=gs("type",[As,Os,Ns,yb,Ob]),Cb=x({role:Gr,content:Y([no,q(no)]),_meta:J(g(),re()).optional()}),Db=Lr.extend({messages:q(Cb),modelPreferences:Ib.optional(),systemPrompt:g().optional(),includeContext:ke(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(ep).optional(),toolChoice:Ab.optional()}),Bs=ue.extend({method:k("sampling/createMessage"),params:Db}),Ls=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens"]).or(g())),role:Gr,content:Nb}),Zs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Gr,content:Y([no,q(no)])}),jb=x({type:k("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),Mb=x({type:k("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:ke(["email","uri","date","date-time"]).optional(),default:g().optional()}),qb=x({type:ke(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),Bb=x({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),Lb=x({type:k("string"),title:g().optional(),description:g().optional(),oneOf:q(x({const:g(),title:g()})),default:g().optional()}),Zb=x({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),Ub=Y([Bb,Lb]),Fb=x({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:x({type:k("string"),enum:q(g())}),default:q(g()).optional()}),Vb=x({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:x({anyOf:q(x({const:g(),title:g()}))}),default:q(g()).optional()}),Kb=Y([Fb,Vb]),Hb=Y([Zb,Ub,Kb]),Gb=Y([Hb,jb,Mb,qb]),Wb=Lr.extend({mode:k("form").optional(),message:g(),requestedSchema:x({type:k("object"),properties:J(g(),Gb),required:q(g()).optional()})}),Jb=Lr.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),Qb=Y([Wb,Jb]),Us=ue.extend({method:k("elicitation/create"),params:Qb}),Yb=Ae.extend({elicitationId:g()}),Xb=Oe.extend({method:k("notifications/elicitation/complete"),params:Yb}),Fs=le.extend({action:ke(["accept","decline","cancel"]),content:ys(e=>e===null?void 0:e,J(g(),Y([g(),V(),ce(),q(g())])).optional())}),ev=x({type:k("ref/resource"),uri:g()});var tv=x({type:k("ref/prompt"),name:g()}),rv=ze.extend({ref:Y([tv,ev]),argument:x({name:g(),value:g()}),context:x({arguments:J(g(),g()).optional()}).optional()}),nv=ue.extend({method:k("completion/complete"),params:rv});var Vs=le.extend({completion:be({values:q(g()).max(100),total:ne(V().int()),hasMore:ne(ce())})}),ov=x({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),iv=ue.extend({method:k("roots/list"),params:ze.optional()}),sv=le.extend({roots:q(ov)}),av=Oe.extend({method:k("notifications/roots/list_changed"),params:Ae.optional()}),KA=Y([ao,Hw,nv,Tb,gb,mb,rb,nb,ib,ab,ub,Sb,xb,uo,fo,po,ho]),HA=Y([so,co,Ww,av,Hr]),GA=Y([zt,Ls,Zs,Fs,sv,lo,mo,Rt]),WA=Y([ao,Bs,Us,iv,uo,fo,po,ho]),JA=Y([so,co,zb,db,Rs,qs,js,Hr,Xb]),QA=Y([zt,ks,Vs,Ds,Is,Es,Ts,zs,mt,Ms,lo,mo,Rt]),E=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new _s(o.elicitations,r)}return new e(t,r,n)}},_s=class extends E{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function ht(e){return e==="completed"||e==="failed"||e==="cancelled"}var cv=Symbol("Let zodToJsonSchema decide on which parser to use");var RO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ks(e){let r=eo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=gf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Hs(e,t){let r=Be(e,t);if(!r.success)throw r.error;return r.data}var mv=6e4,go=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(so,r=>{this._oncancel(r)}),this.setNotificationHandler(co,r=>{this._onprogress(r)}),this.setRequestHandler(ao,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(uo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(fo,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,f=new E(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new E(I.InvalidParams,`Task not found: ${i}`);if(!ht(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ht(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[pt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(po,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new E(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ho,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(ht(o.status))throw new E(I.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 i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new E(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof E?o:new E(I.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,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),E.fromError(I.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=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Zr(i)||Kf(i)?this._onresponse(i):vs(i)?this._onrequest(i,s):Vf(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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=E.fromError(I.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,i=t.params?._meta?.[pt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Zf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(s.signal.aborted)throw new E(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Zr(t))n(t);else{let s=new E(t.error.code,t.error.message,t.error.data);n(s)}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 i=!1;if(Zr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Zr(t))o(t);else{let s=E.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Rt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new E(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ht(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new E(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=v=>{u(v)};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(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[pt]:c}});let m=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let $=v instanceof E?v:new E(I.RequestTimeout,String(v));u($)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let $=Be(r,v.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??mv,_=()=>m(E.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let v=$=>{let T=this._responseHandlers.get(f);T?T($):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(b,{type:"request",message:p,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(f),u($)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(f),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},lo,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},mo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Wf,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||{},[pt]: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||{},[pt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Ks(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Hs(t,o);return Promise.resolve(r(s,i))})}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=Ks(t);this._notificationHandlers.set(n,o=>{let i=Hs(t,o);return Promise.resolve(r(i))})}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"&&vs(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new E(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} 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,i)=>{if(r.aborted){i(new E(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new E(I.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 i=await n.getTask(o,r);if(!i)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Hr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ht(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new E(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ht(a.status))throw new E(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=Hr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ht(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function np(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function op(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];np(s)&&np(i)?r[o]={...s,...i}:r[o]=i}return r}var Wh=zi(Oc(),1),Jh=zi(Gh(),1);function yE(){let e=new Wh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jh.default)(e),e}var Qo=class{constructor(t){this._ajv=t??yE()}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 Yo=class{constructor(t){this._client=t}async*callToolStream(t,r=mt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof E){yield{type:"error",error:u};return}yield{type:"error",error:new E(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};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 Qh(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 Yh(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 Xo(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 i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Xo(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Xo(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Xo(r,t)}}function _E(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 ei=class extends go{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 Qo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",qs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",js,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Yo(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=op(this._capabilities,t)}setRequestHandler(t,r){let o=eo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Jt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Be(Us,c);if(!u.success){let v=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid elicitation request: ${v}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=_E(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new E(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new E(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let v=Be(Rt,m);if(!v.success){let $=v.error instanceof Error?v.error.message:String(v.error);throw new E(I.InvalidParams,`Invalid task creation result: ${$}`)}return v.data}let h=Be(Fs,m);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new E(I.InvalidParams,`Invalid elicitation result: ${v}`)}let _=h.data,b=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&b&&this._capabilities.elicitation?.form?.applyDefaults)try{Xo(b,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Be(Bs,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Be(Rt,f);if(!_.success){let b=_.error instanceof Error?_.error.message:String(_.error);throw new E(I.InvalidParams,`Invalid task creation result: ${b}`)}return _.data}let m=d.tools||d.toolChoice?Zs:Ls,h=Be(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new E(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.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:ws,capabilities:this._capabilities,clientInfo:this._clientInfo}},ks,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!qf.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){Qh(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Yh(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},zt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Vs,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},zt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Ds,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Is,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Es,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Ts,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},zs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},zt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},zt,r)}async callTool(t,r=mt,n){if(this.isToolTaskRequired(t.name))throw new E(I.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),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof E?s:new E(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(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},Ms,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=tp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(l,a);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Zg=zi(Bg(),1);import Jc from"node:process";import{PassThrough as KE}from"node:stream";var ri=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),VE(r)}clear(){this._buffer=void 0}};function VE(e){return Hf.parse(JSON.parse(e))}function Lg(e){return JSON.stringify(e)+`
37
- `}var HE=Jc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function GE(){let e={};for(let t of HE){let r=Jc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var ni=class{constructor(t){this._readBuffer=new ri,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new KE)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,Zg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...GE(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Jc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=Lg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var WE=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Zt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new ni({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??JE(),stderr:t.stderr??"pipe"}),n=new ei({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:YE(r).map(XE),nextCursor:Ug(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!oi(n,["error"])&&rT(n,["ok","success"],!0),target:t,messageId:Ke(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:eT(r).map(tT).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=WE.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:QE(r)},mt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
- `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function JE(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function QE(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function YE(e){if(Array.isArray(e))return e;if(!wr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&wr(r)?[r]:[]}function XE(e){return wr(e)?{id:Ke(e,["id","message_id","messageId"]),cursor:Ug(e,["cursor"]),type:Ke(e,["type","event_type","eventType"]),platform:Ke(e,["platform"]),target:Ke(e,["target"]),sessionKey:Ke(e,["session_key","sessionKey"]),timestamp:Ke(e,["timestamp","created_at","createdAt"]),message:Ke(e,["message","text","content"]),raw:e}:{raw:e}}function eT(e){if(Array.isArray(e))return e;if(!wr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function tT(e){if(!wr(e))return null;let t=Ke(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Ke(e,["platform"]),name:Ke(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Ke(e,t){let r=oi(e,t);return typeof r=="string"?r:void 0}function rT(e,t,r){let n=oi(e,t);return typeof n=="boolean"?n:r}function Ug(e,t){let r=oi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function oi(e,t){if(wr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as lR,writeFile as dR}from"node:fs/promises";import{join as Hy}from"node:path";import{basename as Ky}from"node:path";import{createHash as wT,randomUUID as su}from"node:crypto";import{spawn as bT}from"node:child_process";import{constants as nu}from"node:fs";import{readFileSync as vT}from"node:fs";import{mkdir as Xg,open as $T,readFile as xT,rename as hM,rm as zn,stat as gM,writeFile as yM}from"node:fs/promises";import{tmpdir as kT}from"node:os";import{dirname as vr,join as Me,resolve as ui}from"node:path";import{fileURLToPath as ST}from"node:url";var ii=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function j(e,t){return new ii(e,t)}function Qc(e){let t=e.split(`
34
+ path: iss.path ? [${Et(b)}, ...iss.path] : [${Et(b)}]
35
+ })));`),f.write(`newResult[${Et(b)}] = ${$}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let v=f.compile();return(b,$)=>v(d,b,$)},o,i=Ht,s=!Ln.jitless,c=s&&Di.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let $=u.shape;for(let T of u.keys){let R=$[T],we=R._zod.run({value:p[T],issues:[]},f),Re=R._zod.optin==="optional"&&R._zod.optout==="optional";we instanceof Promise?m.push(we.then(Vt=>Re?Al(Vt,d,T,p):Hn(Vt,d,T))):Re?Al(we,d,T,p):Hn(we,d,T)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,v=l._zod,b=v.def.type;for(let $ of Object.keys(p)){if(_.has($))continue;if(b==="never"){h.push($);continue}let T=v.run({value:p[$],issues:[]},f);T instanceof Promise?m.push(T.then(R=>Hn(R,d,$))):Hn(T,d,$)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function Nl(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(i=>qe(i,n,Ie())))}),t}var Qi=y("$ZodUnion",(e,t)=>{W.init(e,t),G(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),G(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),G(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),G(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=>Ir(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>Nl(s,r,e,n)):Nl(i,r,e,n)}}),_d=y("$ZodDiscriminatedUnion",(e,t)=>{Qi.init(e,t);let r=e._zod.parse;G(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=zr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Ht(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),wd=y("$ZodIntersection",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>Cl(r,c,l)):Cl(r,i,s)}});function Wi(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(Gt(e)&&Gt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=Wi(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],i=t[n],s=Wi(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Cl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Tt(e))return e;let n=Wi(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 vd=y("$ZodRecord",(e,t)=>{W.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Gt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Qe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Qe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.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 s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,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(l=>qe(l,n,Ie())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Qe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Qe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var bd=y("$ZodEnum",(e,t)=>{W.init(e,t);let r=Oi(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>ji.has(typeof n)).map(n=>typeof n=="string"?ft(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),$d=y("$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"?ft(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 xd=y("$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(s=>(r.value=s,r));if(o instanceof Promise)throw new ot;return r.value=o,r}}),kd=y("$ZodOptional",(e,t)=>{W.init(e,t),e._zod.optin="optional",e._zod.optout="optional",G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),G(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ir(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)}),Sd=y("$ZodNullable",(e,t)=>{W.init(e,t),G(e._zod,"optin",()=>t.innerType._zod.optin),G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ir(r.source)}|null)$`):void 0}),G(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)}),Ed=y("$ZodDefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(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(i=>Dl(i,t)):Dl(o,t)}});function Dl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Td=y("$ZodPrefault",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(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))}),Pd=y("$ZodNonOptional",(e,t)=>{W.init(e,t),G(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(i=>jl(i,e)):jl(o,e)}});function jl(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 zd=y("$ZodCatch",(e,t)=>{W.init(e,t),e._zod.optin="optional",G(e._zod,"optout",()=>t.innerType._zod.optout),G(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(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>qe(s,n,Ie()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>qe(i,n,Ie()))},input:r.value}),r.issues=[]),r)}});var Rd=y("$ZodPipe",(e,t)=>{W.init(e,t),G(e._zod,"values",()=>t.in._zod.values),G(e._zod,"optin",()=>t.in._zod.optin),G(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(i=>Ml(i,t,n)):Ml(o,t,n)}});function Ml(e,t,r){return Tt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Id=y("$ZodReadonly",(e,t)=>{W.init(e,t),G(e._zod,"propValues",()=>t.innerType._zod.propValues),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"optin",()=>t.innerType._zod.optin),G(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(ql):ql(o)}});function ql(e){return e.value=Object.freeze(e.value),e}var Od=y("$ZodCustom",(e,t)=>{me.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(i=>Ll(i,r,n,e));Ll(o,r,n,e)}});function Ll(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(Li(o))}}var D_=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},j_=()=>{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 ${D_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Un(n.values[0])}`:`Invalid option: expected one of ${Bn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.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":""}: ${Bn(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 Ad(){return{localeError:j_()}}var hI=Symbol("ZodOutput"),gI=Symbol("ZodInput"),Yi=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 M_(){return new Yi}var Cr=M_();function Nd(e,t){return new e({type:"string",...P(t)})}function Cd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Xi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function Dd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function Md(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function qd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Ld(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Bd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Zd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Ud(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Fd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function Kd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function Vd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Hd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function Gd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function Wd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Jd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Qd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function Xd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function ef(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function tf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function rf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function nf(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function of(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function sf(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function af(e,t){return new e({type:"number",checks:[],...P(t)})}function cf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function uf(e,t){return new e({type:"boolean",...P(t)})}function lf(e,t){return new e({type:"null",...P(t)})}function df(e){return new e({type:"unknown"})}function ff(e,t){return new e({type:"never",...P(t)})}function Wn(e,t){return new Hi({check:"less_than",...P(t),value:e,inclusive:!1})}function Dr(e,t){return new Hi({check:"less_than",...P(t),value:e,inclusive:!0})}function Jn(e,t){return new Gi({check:"greater_than",...P(t),value:e,inclusive:!1})}function jr(e,t){return new Gi({check:"greater_than",...P(t),value:e,inclusive:!0})}function Qn(e,t){return new _l({check:"multiple_of",...P(t),value:e})}function Yn(e,t){return new vl({check:"max_length",...P(t),maximum:e})}function Wt(e,t){return new bl({check:"min_length",...P(t),minimum:e})}function Xn(e,t){return new $l({check:"length_equals",...P(t),length:e})}function es(e,t){return new xl({check:"string_format",format:"regex",...P(t),pattern:e})}function ts(e){return new kl({check:"string_format",format:"lowercase",...P(e)})}function rs(e){return new Sl({check:"string_format",format:"uppercase",...P(e)})}function ns(e,t){return new El({check:"string_format",format:"includes",...P(t),includes:e})}function os(e,t){return new Tl({check:"string_format",format:"starts_with",...P(t),prefix:e})}function is(e,t){return new Pl({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Pt(e){return new zl({check:"overwrite",tx:e})}function ss(e){return Pt(t=>t.normalize(e))}function as(){return Pt(e=>e.trim())}function cs(){return Pt(e=>e.toLowerCase())}function us(){return Pt(e=>e.toUpperCase())}function pf(e,t,r){return new e({type:"array",element:t,...P(r)})}function mf(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function hf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function Jt(e){return!!e._zod}function Le(e,t){return Jt(e)?Ar(e,t):e.safeParse(t)}function eo(e){if(!e)return;let t;if(Jt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function gf(e){if(Jt(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.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 qr={};Au(qr,{ZodISODate:()=>_f,ZodISODateTime:()=>yf,ZodISODuration:()=>vf,ZodISOTime:()=>wf,date:()=>ds,datetime:()=>ls,duration:()=>ps,time:()=>fs});var yf=y("ZodISODateTime",(e,t)=>{Yl.init(e,t),te.init(e,t)});function ls(e){return rf(yf,e)}var _f=y("ZodISODate",(e,t)=>{Xl.init(e,t),te.init(e,t)});function ds(e){return nf(_f,e)}var wf=y("ZodISOTime",(e,t)=>{ed.init(e,t),te.init(e,t)});function fs(e){return of(wf,e)}var vf=y("ZodISODuration",(e,t)=>{td.init(e,t),te.init(e,t)});function ps(e){return sf(vf,e)}var bf=(e,t)=>{Fn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>qu(e,r)},flatten:{value:r=>Mu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},JI=y("ZodError",bf),Lr=y("ZodError",bf,{Parent:Error});var $f=Lu(Lr),xf=Bu(Lr),kf=Zi(Lr),Sf=Ui(Lr);var oe=y("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)=>Je(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>$f(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>kf(e,r,n),e.parseAsync=async(r,n)=>xf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Sf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Cw(r,n)),e.superRefine=r=>e.check(Dw(r)),e.overwrite=r=>e.check(Pt(r)),e.optional=()=>ne(e),e.nullable=()=>Pf(e),e.nullish=()=>ne(Pf(e)),e.nonoptional=r=>Pw(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>ro(e,r),e.transform=r=>hs(e,Nf(r)),e.default=r=>Sw(e,r),e.prefault=r=>Tw(e,r),e.catch=r=>Rw(e,r),e.pipe=r=>hs(e,r),e.readonly=()=>Aw(e),e.describe=r=>{let n=e.clone();return Cr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Cr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Cr.get(e);let n=e.clone();return Cr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),zf=y("_ZodString",(e,t)=>{Gn.init(e,t),oe.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(es(...n)),e.includes=(...n)=>e.check(ns(...n)),e.startsWith=(...n)=>e.check(os(...n)),e.endsWith=(...n)=>e.check(is(...n)),e.min=(...n)=>e.check(Wt(...n)),e.max=(...n)=>e.check(Yn(...n)),e.length=(...n)=>e.check(Xn(...n)),e.nonempty=(...n)=>e.check(Wt(1,...n)),e.lowercase=n=>e.check(ts(n)),e.uppercase=n=>e.check(rs(n)),e.trim=()=>e.check(as()),e.normalize=(...n)=>e.check(ss(...n)),e.toLowerCase=()=>e.check(cs()),e.toUpperCase=()=>e.check(us())}),H_=y("ZodString",(e,t)=>{Gn.init(e,t),zf.init(e,t),e.email=r=>e.check(Cd(G_,r)),e.url=r=>e.check(Ld(W_,r)),e.jwt=r=>e.check(tf(lw,r)),e.emoji=r=>e.check(Bd(J_,r)),e.guid=r=>e.check(Xi(Ef,r)),e.uuid=r=>e.check(Dd(to,r)),e.uuidv4=r=>e.check(jd(to,r)),e.uuidv6=r=>e.check(Md(to,r)),e.uuidv7=r=>e.check(qd(to,r)),e.nanoid=r=>e.check(Zd(Q_,r)),e.guid=r=>e.check(Xi(Ef,r)),e.cuid=r=>e.check(Ud(Y_,r)),e.cuid2=r=>e.check(Fd(X_,r)),e.ulid=r=>e.check(Kd(ew,r)),e.base64=r=>e.check(Yd(aw,r)),e.base64url=r=>e.check(Xd(cw,r)),e.xid=r=>e.check(Vd(tw,r)),e.ksuid=r=>e.check(Hd(rw,r)),e.ipv4=r=>e.check(Gd(nw,r)),e.ipv6=r=>e.check(Wd(ow,r)),e.cidrv4=r=>e.check(Jd(iw,r)),e.cidrv6=r=>e.check(Qd(sw,r)),e.e164=r=>e.check(ef(uw,r)),e.datetime=r=>e.check(ls(r)),e.date=r=>e.check(ds(r)),e.time=r=>e.check(fs(r)),e.duration=r=>e.check(ps(r))});function g(e){return Nd(H_,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),zf.init(e,t)}),G_=y("ZodEmail",(e,t)=>{Ul.init(e,t),te.init(e,t)});var Ef=y("ZodGUID",(e,t)=>{Bl.init(e,t),te.init(e,t)});var to=y("ZodUUID",(e,t)=>{Zl.init(e,t),te.init(e,t)});var W_=y("ZodURL",(e,t)=>{Fl.init(e,t),te.init(e,t)});var J_=y("ZodEmoji",(e,t)=>{Kl.init(e,t),te.init(e,t)});var Q_=y("ZodNanoID",(e,t)=>{Vl.init(e,t),te.init(e,t)});var Y_=y("ZodCUID",(e,t)=>{Hl.init(e,t),te.init(e,t)});var X_=y("ZodCUID2",(e,t)=>{Gl.init(e,t),te.init(e,t)});var ew=y("ZodULID",(e,t)=>{Wl.init(e,t),te.init(e,t)});var tw=y("ZodXID",(e,t)=>{Jl.init(e,t),te.init(e,t)});var rw=y("ZodKSUID",(e,t)=>{Ql.init(e,t),te.init(e,t)});var nw=y("ZodIPv4",(e,t)=>{rd.init(e,t),te.init(e,t)});var ow=y("ZodIPv6",(e,t)=>{nd.init(e,t),te.init(e,t)});var iw=y("ZodCIDRv4",(e,t)=>{od.init(e,t),te.init(e,t)});var sw=y("ZodCIDRv6",(e,t)=>{id.init(e,t),te.init(e,t)});var aw=y("ZodBase64",(e,t)=>{ad.init(e,t),te.init(e,t)});var cw=y("ZodBase64URL",(e,t)=>{cd.init(e,t),te.init(e,t)});var uw=y("ZodE164",(e,t)=>{ud.init(e,t),te.init(e,t)});var lw=y("ZodJWT",(e,t)=>{ld.init(e,t),te.init(e,t)});var Rf=y("ZodNumber",(e,t)=>{Ji.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(Jn(n,o)),e.gte=(n,o)=>e.check(jr(n,o)),e.min=(n,o)=>e.check(jr(n,o)),e.lt=(n,o)=>e.check(Wn(n,o)),e.lte=(n,o)=>e.check(Dr(n,o)),e.max=(n,o)=>e.check(Dr(n,o)),e.int=n=>e.check(Tf(n)),e.safe=n=>e.check(Tf(n)),e.positive=n=>e.check(Jn(0,n)),e.nonnegative=n=>e.check(jr(0,n)),e.negative=n=>e.check(Wn(0,n)),e.nonpositive=n=>e.check(Dr(0,n)),e.multipleOf=(n,o)=>e.check(Qn(n,o)),e.step=(n,o)=>e.check(Qn(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 K(e){return af(Rf,e)}var dw=y("ZodNumberFormat",(e,t)=>{dd.init(e,t),Rf.init(e,t)});function Tf(e){return cf(dw,e)}var fw=y("ZodBoolean",(e,t)=>{fd.init(e,t),oe.init(e,t)});function ce(e){return uf(fw,e)}var pw=y("ZodNull",(e,t)=>{pd.init(e,t),oe.init(e,t)});function If(e){return lf(pw,e)}var mw=y("ZodUnknown",(e,t)=>{md.init(e,t),oe.init(e,t)});function re(){return df(mw)}var hw=y("ZodNever",(e,t)=>{hd.init(e,t),oe.init(e,t)});function gw(e){return ff(hw,e)}var yw=y("ZodArray",(e,t)=>{gd.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Wt(r,n)),e.nonempty=r=>e.check(Wt(1,r)),e.max=(r,n)=>e.check(Yn(r,n)),e.length=(r,n)=>e.check(Xn(r,n)),e.unwrap=()=>e.element});function q(e,t){return pf(yw,e,t)}var Of=y("ZodObject",(e,t)=>{yd.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ke(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:gw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(Cf,e,r[0]),e.required=(...r)=>F.required(Df,e,r[0])});function x(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new Of(r)}function ve(e,t){return new Of({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var Af=y("ZodUnion",(e,t)=>{Qi.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new Af({type:"union",options:e,...F.normalizeParams(t)})}var _w=y("ZodDiscriminatedUnion",(e,t)=>{Af.init(e,t),_d.init(e,t)});function gs(e,t,r){return new _w({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var ww=y("ZodIntersection",(e,t)=>{wd.init(e,t),oe.init(e,t)});function ro(e,t){return new ww({type:"intersection",left:e,right:t})}var vw=y("ZodRecord",(e,t)=>{vd.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new vw({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var ms=y("ZodEnum",(e,t)=>{bd.init(e,t),oe.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 i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ms({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ms({...t,checks:[],...F.normalizeParams(o),entries:i})}});function ke(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ms({type:"enum",entries:r,...F.normalizeParams(t)})}var bw=y("ZodLiteral",(e,t)=>{$d.init(e,t),oe.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 k(e,t){return new bw({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var $w=y("ZodTransform",(e,t)=>{xd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Nf(e){return new $w({type:"transform",transform:e})}var Cf=y("ZodOptional",(e,t)=>{kd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new Cf({type:"optional",innerType:e})}var xw=y("ZodNullable",(e,t)=>{Sd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pf(e){return new xw({type:"nullable",innerType:e})}var kw=y("ZodDefault",(e,t)=>{Ed.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Sw(e,t){return new kw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Ew=y("ZodPrefault",(e,t)=>{Td.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tw(e,t){return new Ew({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Df=y("ZodNonOptional",(e,t)=>{Pd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pw(e,t){return new Df({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var zw=y("ZodCatch",(e,t)=>{zd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rw(e,t){return new zw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Iw=y("ZodPipe",(e,t)=>{Rd.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function hs(e,t){return new Iw({type:"pipe",in:e,out:t})}var Ow=y("ZodReadonly",(e,t)=>{Id.init(e,t),oe.init(e,t)});function Aw(e){return new Ow({type:"readonly",innerType:e})}var jf=y("ZodCustom",(e,t)=>{Od.init(e,t),oe.init(e,t)});function Nw(e){let t=new me({check:"custom"});return t._zod.check=e,t}function Mf(e,t){return mf(jf,e??(()=>!0),t)}function Cw(e,t={}){return hf(jf,e,t)}function Dw(e){let t=Nw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.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(F.issue(o))}},e(r.value,r)));return t}function ys(e,t){return hs(Nf(e),t)}Ie(Ad());var ws="2025-11-25";var qf=[ws,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],pt="io.modelcontextprotocol/related-task",oo="2.0",ae=Mf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Lf=Y([g(),K().int()]),Bf=g(),UO=ve({ttl:K().optional(),pollInterval:K().optional()}),jw=x({ttl:K().optional()}),Mw=x({taskId:g()}),vs=ve({progressToken:Lf.optional(),[pt]:Mw.optional()}),ze=x({_meta:vs.optional()}),Br=ze.extend({task:jw.optional()}),Zf=e=>Br.safeParse(e).success,ue=x({method:g(),params:ze.loose().optional()}),Oe=x({_meta:vs.optional()}),Ae=x({method:g(),params:Oe.loose().optional()}),le=ve({_meta:vs.optional()}),io=Y([g(),K().int()]),Uf=x({jsonrpc:k(oo),id:io,...ue.shape}).strict(),bs=e=>Uf.safeParse(e).success,Ff=x({jsonrpc:k(oo),...Ae.shape}).strict(),Kf=e=>Ff.safeParse(e).success,$s=x({jsonrpc:k(oo),id:io,result:le}).strict(),Zr=e=>$s.safeParse(e).success;var I;(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"})(I||(I={}));var xs=x({jsonrpc:k(oo),id:io.optional(),error:x({code:K().int(),message:g(),data:re().optional()})}).strict();var Vf=e=>xs.safeParse(e).success;var Hf=Y([Uf,Ff,$s,xs]),FO=Y([$s,xs]),zt=le.strict(),qw=Oe.extend({requestId:io.optional(),reason:g().optional()}),so=Ae.extend({method:k("notifications/cancelled"),params:qw}),Lw=x({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:ke(["light","dark"]).optional()}),Ur=x({icons:q(Lw).optional()}),Qt=x({name:g(),title:g().optional()}),Gf=Qt.extend({...Qt.shape,...Ur.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Bw=ro(x({applyDefaults:ce().optional()}),J(g(),re())),Zw=ys(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ro(x({form:Bw.optional(),url:ae.optional()}),J(g(),re()).optional())),Uw=ve({list:ae.optional(),cancel:ae.optional(),requests:ve({sampling:ve({createMessage:ae.optional()}).optional(),elicitation:ve({create:ae.optional()}).optional()}).optional()}),Fw=ve({list:ae.optional(),cancel:ae.optional(),requests:ve({tools:ve({call:ae.optional()}).optional()}).optional()}),Kw=x({experimental:J(g(),ae).optional(),sampling:x({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:Zw.optional(),roots:x({listChanged:ce().optional()}).optional(),tasks:Uw.optional(),extensions:J(g(),ae).optional()}),Vw=ze.extend({protocolVersion:g(),capabilities:Kw,clientInfo:Gf}),Hw=ue.extend({method:k("initialize"),params:Vw});var Gw=x({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:x({listChanged:ce().optional()}).optional(),resources:x({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:x({listChanged:ce().optional()}).optional(),tasks:Fw.optional(),extensions:J(g(),ae).optional()}),ks=le.extend({protocolVersion:g(),capabilities:Gw,serverInfo:Gf,instructions:g().optional()}),Ww=Ae.extend({method:k("notifications/initialized"),params:Oe.optional()});var ao=ue.extend({method:k("ping"),params:ze.optional()}),Jw=x({progress:K(),total:ne(K()),message:ne(g())}),Qw=x({...Oe.shape,...Jw.shape,progressToken:Lf}),co=Ae.extend({method:k("notifications/progress"),params:Qw}),Yw=ze.extend({cursor:Bf.optional()}),Fr=ue.extend({params:Yw.optional()}),Kr=le.extend({nextCursor:Bf.optional()}),Xw=ke(["working","input_required","completed","failed","cancelled"]),Vr=x({taskId:g(),status:Xw,ttl:Y([K(),If()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(K()),statusMessage:ne(g())}),Rt=le.extend({task:Vr}),ev=Oe.merge(Vr),Hr=Ae.extend({method:k("notifications/tasks/status"),params:ev}),uo=ue.extend({method:k("tasks/get"),params:ze.extend({taskId:g()})}),lo=le.merge(Vr),fo=ue.extend({method:k("tasks/result"),params:ze.extend({taskId:g()})}),KO=le.loose(),po=Fr.extend({method:k("tasks/list")}),mo=Kr.extend({tasks:q(Vr)}),ho=ue.extend({method:k("tasks/cancel"),params:ze.extend({taskId:g()})}),Wf=le.merge(Vr),Jf=x({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),Qf=Jf.extend({text:g()}),Ss=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yf=Jf.extend({blob:Ss}),Gr=ke(["user","assistant"]),Yt=x({audience:q(Gr).optional(),priority:K().min(0).max(1).optional(),lastModified:qr.datetime({offset:!0}).optional()}),Xf=x({...Qt.shape,...Ur.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(K()),annotations:Yt.optional(),_meta:ne(ve({}))}),tv=x({...Qt.shape,...Ur.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:Yt.optional(),_meta:ne(ve({}))}),rv=Fr.extend({method:k("resources/list")}),Es=Kr.extend({resources:q(Xf)}),nv=Fr.extend({method:k("resources/templates/list")}),Ts=Kr.extend({resourceTemplates:q(tv)}),Ps=ze.extend({uri:g()}),ov=Ps,iv=ue.extend({method:k("resources/read"),params:ov}),zs=le.extend({contents:q(Y([Qf,Yf]))}),Rs=Ae.extend({method:k("notifications/resources/list_changed"),params:Oe.optional()}),sv=Ps,av=ue.extend({method:k("resources/subscribe"),params:sv}),cv=Ps,uv=ue.extend({method:k("resources/unsubscribe"),params:cv}),lv=Oe.extend({uri:g()}),dv=Ae.extend({method:k("notifications/resources/updated"),params:lv}),fv=x({name:g(),description:ne(g()),required:ne(ce())}),pv=x({...Qt.shape,...Ur.shape,description:ne(g()),arguments:ne(q(fv)),_meta:ne(ve({}))}),mv=Fr.extend({method:k("prompts/list")}),Is=Kr.extend({prompts:q(pv)}),hv=ze.extend({name:g(),arguments:J(g(),g()).optional()}),gv=ue.extend({method:k("prompts/get"),params:hv}),Os=x({type:k("text"),text:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),As=x({type:k("image"),data:Ss,mimeType:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),Ns=x({type:k("audio"),data:Ss,mimeType:g(),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),yv=x({type:k("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),_v=x({type:k("resource"),resource:Y([Qf,Yf]),annotations:Yt.optional(),_meta:J(g(),re()).optional()}),wv=Xf.extend({type:k("resource_link")}),Cs=Y([Os,As,Ns,wv,_v]),vv=x({role:Gr,content:Cs}),Ds=le.extend({description:g().optional(),messages:q(vv)}),js=Ae.extend({method:k("notifications/prompts/list_changed"),params:Oe.optional()}),bv=x({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),$v=x({taskSupport:ke(["required","optional","forbidden"]).optional()}),ep=x({...Qt.shape,...Ur.shape,description:g().optional(),inputSchema:x({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:x({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:bv.optional(),execution:$v.optional(),_meta:J(g(),re()).optional()}),xv=Fr.extend({method:k("tools/list")}),Ms=Kr.extend({tools:q(ep)}),mt=le.extend({content:q(Cs).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),VO=mt.or(le.extend({toolResult:re()})),kv=Br.extend({name:g(),arguments:J(g(),re()).optional()}),Sv=ue.extend({method:k("tools/call"),params:kv}),qs=Ae.extend({method:k("notifications/tools/list_changed"),params:Oe.optional()}),tp=x({autoRefresh:ce().default(!0),debounceMs:K().int().nonnegative().default(300)}),rp=ke(["debug","info","notice","warning","error","critical","alert","emergency"]),Ev=ze.extend({level:rp}),Tv=ue.extend({method:k("logging/setLevel"),params:Ev}),Pv=Oe.extend({level:rp,logger:g().optional(),data:re()}),zv=Ae.extend({method:k("notifications/message"),params:Pv}),Rv=x({name:g().optional()}),Iv=x({hints:q(Rv).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),Ov=x({mode:ke(["auto","required","none"]).optional()}),Av=x({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Cs).default([]),structuredContent:x({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),Nv=gs("type",[Os,As,Ns]),no=gs("type",[Os,As,Ns,yv,Av]),Cv=x({role:Gr,content:Y([no,q(no)]),_meta:J(g(),re()).optional()}),Dv=Br.extend({messages:q(Cv),modelPreferences:Iv.optional(),systemPrompt:g().optional(),includeContext:ke(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(ep).optional(),toolChoice:Ov.optional()}),Ls=ue.extend({method:k("sampling/createMessage"),params:Dv}),Bs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens"]).or(g())),role:Gr,content:Nv}),Zs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Gr,content:Y([no,q(no)])}),jv=x({type:k("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),Mv=x({type:k("string"),title:g().optional(),description:g().optional(),minLength:K().optional(),maxLength:K().optional(),format:ke(["email","uri","date","date-time"]).optional(),default:g().optional()}),qv=x({type:ke(["number","integer"]),title:g().optional(),description:g().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),Lv=x({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),Bv=x({type:k("string"),title:g().optional(),description:g().optional(),oneOf:q(x({const:g(),title:g()})),default:g().optional()}),Zv=x({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),Uv=Y([Lv,Bv]),Fv=x({type:k("array"),title:g().optional(),description:g().optional(),minItems:K().optional(),maxItems:K().optional(),items:x({type:k("string"),enum:q(g())}),default:q(g()).optional()}),Kv=x({type:k("array"),title:g().optional(),description:g().optional(),minItems:K().optional(),maxItems:K().optional(),items:x({anyOf:q(x({const:g(),title:g()}))}),default:q(g()).optional()}),Vv=Y([Fv,Kv]),Hv=Y([Zv,Uv,Vv]),Gv=Y([Hv,jv,Mv,qv]),Wv=Br.extend({mode:k("form").optional(),message:g(),requestedSchema:x({type:k("object"),properties:J(g(),Gv),required:q(g()).optional()})}),Jv=Br.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),Qv=Y([Wv,Jv]),Us=ue.extend({method:k("elicitation/create"),params:Qv}),Yv=Oe.extend({elicitationId:g()}),Xv=Ae.extend({method:k("notifications/elicitation/complete"),params:Yv}),Fs=le.extend({action:ke(["accept","decline","cancel"]),content:ys(e=>e===null?void 0:e,J(g(),Y([g(),K(),ce(),q(g())])).optional())}),eb=x({type:k("ref/resource"),uri:g()});var tb=x({type:k("ref/prompt"),name:g()}),rb=ze.extend({ref:Y([tb,eb]),argument:x({name:g(),value:g()}),context:x({arguments:J(g(),g()).optional()}).optional()}),nb=ue.extend({method:k("completion/complete"),params:rb});var Ks=le.extend({completion:ve({values:q(g()).max(100),total:ne(K().int()),hasMore:ne(ce())})}),ob=x({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),ib=ue.extend({method:k("roots/list"),params:ze.optional()}),sb=le.extend({roots:q(ob)}),ab=Ae.extend({method:k("notifications/roots/list_changed"),params:Oe.optional()}),HO=Y([ao,Hw,nb,Tv,gv,mv,rv,nv,iv,av,uv,Sv,xv,uo,fo,po,ho]),GO=Y([so,co,Ww,ab,Hr]),WO=Y([zt,Bs,Zs,Fs,sb,lo,mo,Rt]),JO=Y([ao,Ls,Us,ib,uo,fo,po,ho]),QO=Y([so,co,zv,dv,Rs,qs,js,Hr,Xv]),YO=Y([zt,ks,Ks,Ds,Is,Es,Ts,zs,mt,Ms,lo,mo,Rt]),E=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new _s(o.elicitations,r)}return new e(t,r,n)}},_s=class extends E{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function ht(e){return e==="completed"||e==="failed"||e==="cancelled"}var cb=Symbol("Let zodToJsonSchema decide on which parser to use");var IA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Vs(e){let r=eo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=gf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Hs(e,t){let r=Le(e,t);if(!r.success)throw r.error;return r.data}var mb=6e4,go=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(so,r=>{this._oncancel(r)}),this.setNotificationHandler(co,r=>{this._onprogress(r)}),this.setRequestHandler(ao,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(uo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(fo,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,f=new E(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new E(I.InvalidParams,`Task not found: ${i}`);if(!ht(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ht(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[pt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(po,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new E(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ho,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(ht(o.status))throw new E(I.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 i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new E(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof E?o:new E(I.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,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),E.fromError(I.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=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Zr(i)||Vf(i)?this._onresponse(i):bs(i)?this._onrequest(i,s):Kf(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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=E.fromError(I.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,i=t.params?._meta?.[pt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Zf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(s.signal.aborted)throw new E(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Zr(t))n(t);else{let s=new E(t.error.code,t.error.message,t.error.data);n(s)}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 i=!1;if(Zr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Zr(t))o(t);else{let s=E.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Rt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new E(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ht(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new E(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};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(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[pt]:c}});let m=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let $=b instanceof E?b:new E(I.RequestTimeout,String(b));u($)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let $=Le(r,b.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??mb,_=()=>m(E.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=$=>{let T=this._responseHandlers.get(f);T?T($):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(f),u($)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},lo,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},mo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Wf,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||{},[pt]: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||{},[pt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Vs(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Hs(t,o);return Promise.resolve(r(s,i))})}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=Vs(t);this._notificationHandlers.set(n,o=>{let i=Hs(t,o);return Promise.resolve(r(i))})}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"&&bs(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new E(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} 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,i)=>{if(r.aborted){i(new E(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new E(I.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 i=await n.getTask(o,r);if(!i)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Hr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ht(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new E(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ht(a.status))throw new E(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=Hr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ht(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function np(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function op(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];np(s)&&np(i)?r[o]={...s,...i}:r[o]=i}return r}var Wh=zi(Ac(),1),Jh=zi(Gh(),1);function yE(){let e=new Wh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jh.default)(e),e}var Qo=class{constructor(t){this._ajv=t??yE()}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 Yo=class{constructor(t){this._client=t}async*callToolStream(t,r=mt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof E){yield{type:"error",error:u};return}yield{type:"error",error:new E(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};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 Qh(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 Yh(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 Xo(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 i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Xo(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Xo(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Xo(r,t)}}function _E(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 ei=class extends go{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 Qo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",qs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",js,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Yo(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=op(this._capabilities,t)}setRequestHandler(t,r){let o=eo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Jt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Le(Us,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=_E(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new E(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new E(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let b=Le(Rt,m);if(!b.success){let $=b.error instanceof Error?b.error.message:String(b.error);throw new E(I.InvalidParams,`Invalid task creation result: ${$}`)}return b.data}let h=Le(Fs,m);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new E(I.InvalidParams,`Invalid elicitation result: ${b}`)}let _=h.data,v=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Xo(v,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Le(Ls,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Le(Rt,f);if(!_.success){let v=_.error instanceof Error?_.error.message:String(_.error);throw new E(I.InvalidParams,`Invalid task creation result: ${v}`)}return _.data}let m=d.tools||d.toolChoice?Zs:Bs,h=Le(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new E(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.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:ws,capabilities:this._capabilities,clientInfo:this._clientInfo}},ks,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!qf.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){Qh(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Yh(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},zt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Ks,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},zt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Ds,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Is,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Es,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Ts,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},zs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},zt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},zt,r)}async callTool(t,r=mt,n){if(this.isToolTaskRequired(t.name))throw new E(I.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),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof E?s:new E(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(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},Ms,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=tp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(l,a);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Zg=zi(Lg(),1);import Jc from"node:process";import{PassThrough as VE}from"node:stream";var ri=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),KE(r)}clear(){this._buffer=void 0}};function KE(e){return Hf.parse(JSON.parse(e))}function Bg(e){return JSON.stringify(e)+`
37
+ `}var HE=Jc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function GE(){let e={};for(let t of HE){let r=Jc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var ni=class{constructor(t){this._readBuffer=new ri,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new VE)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,Zg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...GE(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Jc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=Bg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var WE=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Zt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new ni({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??JE(),stderr:t.stderr??"pipe"}),n=new ei({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:YE(r).map(XE),nextCursor:Ug(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!oi(n,["error"])&&rT(n,["ok","success"],!0),target:t,messageId:Ve(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:eT(r).map(tT).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=WE.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:QE(r)},mt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
+ `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function JE(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function QE(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function YE(e){if(Array.isArray(e))return e;if(!wr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&wr(r)?[r]:[]}function XE(e){return wr(e)?{id:Ve(e,["id","message_id","messageId"]),cursor:Ug(e,["cursor"]),type:Ve(e,["type","event_type","eventType"]),platform:Ve(e,["platform"]),target:Ve(e,["target"]),sessionKey:Ve(e,["session_key","sessionKey"]),timestamp:Ve(e,["timestamp","created_at","createdAt"]),message:Ve(e,["message","text","content"]),raw:e}:{raw:e}}function eT(e){if(Array.isArray(e))return e;if(!wr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function tT(e){if(!wr(e))return null;let t=Ve(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Ve(e,["platform"]),name:Ve(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Ve(e,t){let r=oi(e,t);return typeof r=="string"?r:void 0}function rT(e,t,r){let n=oi(e,t);return typeof n=="boolean"?n:r}function Ug(e,t){let r=oi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function oi(e,t){if(wr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as dR,writeFile as fR}from"node:fs/promises";import{join as Hy}from"node:path";import{basename as Vy}from"node:path";import{createHash as vT,randomUUID as su}from"node:crypto";import{spawn as bT}from"node:child_process";import{constants as nu}from"node:fs";import{readFileSync as $T}from"node:fs";import{mkdir as Xg,open as xT,readFile as kT,rename as vM,rm as zn,stat as bM,writeFile as $M}from"node:fs/promises";import{tmpdir as ST}from"node:os";import{dirname as br,join as Me,resolve as ui}from"node:path";import{fileURLToPath as ET}from"node:url";var ii=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function j(e,t){return new ii(e,t)}function Qc(e){let t=e.split(`
39
39
  `);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(r=>r.endsWith("\r")?r.slice(0,-1):r)}function nt(e){return j(e,"invalid quoted string")}function Ut(e,t){if(e==="")return"";if(e.startsWith('"'))return Fg(e,t);if(e.includes('"'))throw nt(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:nT(e)?Number(e):e}function En(e,t){let r=e.trim();if(r.startsWith('"'))return[Fg(r,t),!0];if(r.includes('"')||/\s/.test(r))throw j(t,"expected non-empty field name");return[r,!1]}function Fg(e,t){if(e[0]!=='"')throw nt(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw nt(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw nt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw nt(t);r+=String.fromCharCode(a),n+=4;break}default:throw nt(t)}continue}if(o<" "&&o!==" ")throw nt(t);r+=o}throw nt(t)}function Tn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw nt(r);return n.push(e.slice(o).trim()),n}function He(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw nt(r);return-1}function nT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function br(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Hg=2;function cT(e={}){return{indent:Math.max(1,e.indent??Hg),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function uT(e,t){let r=[],n=!1;return Qc(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){n=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw j(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw j(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function Pn(e,t){let r=cT(t),n=uT(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw j(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=ru(o.content,He(o.content,":",o.number))}catch(u){if(r.strict)throw Gg(u,o.number);l=void 0}if(l!==void 0)return dT(l,n,r)}if(i&&He(o.content,":",o.number)===-1)return Ut(o.content.trim(),o.number);let s={index:0},a=eu(n,s,0,r),c=n[s.index];if(c!==void 0)throw j(c.number,"expected end of document");return a}function eu(e,t,r,n){let o={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<r)break;if(i.depth>r)throw j(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=lT(e,t,r,n);hT(o,s,a,c,n,i.number)}return o}function lT(e,t,r,n){let o=e[t.index],i=o.content,s=He(i,":",o.number);if(s===-1)throw j(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1);if(He(a,"[",o.number)!==-1){let f;try{f=ru(a,s)}catch(m){if(n.strict)throw Gg(m,o.number);t.index+=1;let h=Vg(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:h}}if(f.key===""&&!f.keyQuoted)throw j(o.number,"expected non-empty field name");let p=tu(f,c,e,t,r,n);return{key:f.key,quoted:f.keyQuoted,value:p}}let[l,u]=En(a,o.number);if(l===""&&!u)throw j(o.number,"expected non-empty field name");t.index+=1;let d=Vg(e,t,r,c,o.number,n);return{key:l,quoted:u,value:d}}function Vg(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return Ut(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?eu(e,t,r+1,i):{}}function dT(e,t,r){let n=t[0],o=He(n.content,":",n.number);if(o===-1)throw j(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=tu(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw j(c.number,"expected end of document");return a}function tu(e,t,r,n,o,i){let s=r[n.index].number,a=t.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw j(s,"expected tabular rows");return fT(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Tn(a,e.delimiter,s).map(l=>Ut(l,s));if(c.length!==e.len)throw j(s,"array length mismatch");return c}return pT(e,r,n,o+1,i)}function fT(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw Yc(r,n.index);if(c.depth<o)break;if(c.depth>o)throw j(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw j(c.number,"blank line inside array");if(!Kg(c.content,e.delimiter,c.number))break;let l=Tn(c.content,e.delimiter,c.number);if(l.length!==t.length)throw j(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{br(u,d,Ut(l[f],c.number))}),s.push(u),n.index+=1}if(s.length!==e.len)throw Yc(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Kg(a.content,e.delimiter,a.number))throw j(a.number,"array length mismatch");return s}function Kg(e,t,r){let n=He(e,":",r);if(n===-1)return!0;let o=He(e,t,r);return o===-1?!1:o<n}function pT(e,t,r,n,o){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0||a.depth<n)throw Yc(t,r.index);if(a.depth>n)throw j(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw j(a.number,"blank line inside array");i.push(mT(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw j(s.number,"array length mismatch");return i}function mT(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw j(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=He(i,":",o.number),a;try{a=ru(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return tu(a,c,e,t,r,n)}}if(He(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return eu(s,{index:0},r+1,n)}return t.index+=1,Ut(i,o.number)}function Yc(e,t){let r=e[t]??e[e.length-1];return j(r===void 0?1:r.number,"array length mismatch")}function ru(e,t){if(t===-1)throw j(0,"array header missing colon");let r=e.slice(0,t),n=He(r,"[",0);if(n===-1)throw j(0,"invalid array header");let o,i;try{[o,i]=En(r.slice(0,n),0)}catch{throw j(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw j(0,"invalid array header");let c=s.slice(0,a),l=/^[0-9]*/.exec(c)[0];if(l===""||l.length>1&&l.startsWith("0"))throw j(0,"invalid array header");let u=Number.parseInt(l,10),d;switch(c.slice(l.length)){case"":d=",";break;case" ":d=" ";break;case"|":d="|";break;default:throw j(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2){let m;try{m=Tn(f.slice(1,-1),d,0),p=m.map(h=>En(h,0)[0])}catch{throw j(0,"invalid array header")}}else throw j(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function Gg(e,t){return j(t,e.reason??String(e.message))}function hT(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(gT)){Xc(e,s,n,o,i);return}}Xc(e,[t],n,o,i)}function Xc(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw j(o,"duplicate key");br(e,i,r);return}if(s&&!yT(e[i])){if(n.strict)throw j(o,"path expansion conflict");br(e,i,{})}else s||br(e,i,{});Xc(e[i],t.slice(1),r,n,o)}function gT(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function yT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createConnection as _T}from"node:net";async function ai(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=_T(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
40
+ `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw nt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw nt(t);r+=String.fromCharCode(a),n+=4;break}default:throw nt(t)}continue}if(o<" "&&o!==" ")throw nt(t);r+=o}throw nt(t)}function Tn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw nt(r);return n.push(e.slice(o).trim()),n}function He(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw nt(r);return-1}function nT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function vr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Hg=2;function cT(e={}){return{indent:Math.max(1,e.indent??Hg),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function uT(e,t){let r=[],n=!1;return Qc(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){n=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw j(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw j(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function Pn(e,t){let r=cT(t),n=uT(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw j(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=ru(o.content,He(o.content,":",o.number))}catch(u){if(r.strict)throw Gg(u,o.number);l=void 0}if(l!==void 0)return dT(l,n,r)}if(i&&He(o.content,":",o.number)===-1)return Ut(o.content.trim(),o.number);let s={index:0},a=eu(n,s,0,r),c=n[s.index];if(c!==void 0)throw j(c.number,"expected end of document");return a}function eu(e,t,r,n){let o={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<r)break;if(i.depth>r)throw j(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=lT(e,t,r,n);hT(o,s,a,c,n,i.number)}return o}function lT(e,t,r,n){let o=e[t.index],i=o.content,s=He(i,":",o.number);if(s===-1)throw j(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1);if(He(a,"[",o.number)!==-1){let f;try{f=ru(a,s)}catch(m){if(n.strict)throw Gg(m,o.number);t.index+=1;let h=Kg(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:h}}if(f.key===""&&!f.keyQuoted)throw j(o.number,"expected non-empty field name");let p=tu(f,c,e,t,r,n);return{key:f.key,quoted:f.keyQuoted,value:p}}let[l,u]=En(a,o.number);if(l===""&&!u)throw j(o.number,"expected non-empty field name");t.index+=1;let d=Kg(e,t,r,c,o.number,n);return{key:l,quoted:u,value:d}}function Kg(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return Ut(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?eu(e,t,r+1,i):{}}function dT(e,t,r){let n=t[0],o=He(n.content,":",n.number);if(o===-1)throw j(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=tu(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw j(c.number,"expected end of document");return a}function tu(e,t,r,n,o,i){let s=r[n.index].number,a=t.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw j(s,"expected tabular rows");return fT(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Tn(a,e.delimiter,s).map(l=>Ut(l,s));if(c.length!==e.len)throw j(s,"array length mismatch");return c}return pT(e,r,n,o+1,i)}function fT(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw Yc(r,n.index);if(c.depth<o)break;if(c.depth>o)throw j(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw j(c.number,"blank line inside array");if(!Vg(c.content,e.delimiter,c.number))break;let l=Tn(c.content,e.delimiter,c.number);if(l.length!==t.length)throw j(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{vr(u,d,Ut(l[f],c.number))}),s.push(u),n.index+=1}if(s.length!==e.len)throw Yc(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Vg(a.content,e.delimiter,a.number))throw j(a.number,"array length mismatch");return s}function Vg(e,t,r){let n=He(e,":",r);if(n===-1)return!0;let o=He(e,t,r);return o===-1?!1:o<n}function pT(e,t,r,n,o){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0||a.depth<n)throw Yc(t,r.index);if(a.depth>n)throw j(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw j(a.number,"blank line inside array");i.push(mT(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw j(s.number,"array length mismatch");return i}function mT(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw j(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=He(i,":",o.number),a;try{a=ru(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return tu(a,c,e,t,r,n)}}if(He(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return eu(s,{index:0},r+1,n)}return t.index+=1,Ut(i,o.number)}function Yc(e,t){let r=e[t]??e[e.length-1];return j(r===void 0?1:r.number,"array length mismatch")}function ru(e,t){if(t===-1)throw j(0,"array header missing colon");let r=e.slice(0,t),n=He(r,"[",0);if(n===-1)throw j(0,"invalid array header");let o,i;try{[o,i]=En(r.slice(0,n),0)}catch{throw j(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw j(0,"invalid array header");let c=s.slice(0,a),l=/^[0-9]*/.exec(c)[0];if(l===""||l.length>1&&l.startsWith("0"))throw j(0,"invalid array header");let u=Number.parseInt(l,10),d;switch(c.slice(l.length)){case"":d=",";break;case" ":d=" ";break;case"|":d="|";break;default:throw j(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2){let m;try{m=Tn(f.slice(1,-1),d,0),p=m.map(h=>En(h,0)[0])}catch{throw j(0,"invalid array header")}}else throw j(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function Gg(e,t){return j(t,e.reason??String(e.message))}function hT(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(gT)){Xc(e,s,n,o,i);return}}Xc(e,[t],n,o,i)}function Xc(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw j(o,"duplicate key");vr(e,i,r);return}if(s&&!yT(e[i])){if(n.strict)throw j(o,"path expansion conflict");vr(e,i,{})}else s||vr(e,i,{});Xc(e[i],t.slice(1),r,n,o)}function gT(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function yT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Mj=new TextEncoder,qj=new TextDecoder;import{createConnection as wT}from"node:net";async function ai(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=wT(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
41
41
  `)}),i.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
42
- `);if(d<0)return;let f=a.slice(0,d);l(()=>{try{n(JSON.parse(f))}catch(p){o(p)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var ET=108,TT=1,PT=5e3;function li(e){let t=ZT(e)??ui(e),r=LT(t);return{rootDir:t,socketPath:Me(r,"rsp.sock"),pidPath:Me(r,"rsp.pid"),lockPath:Me(r,"rsp.lock"),wakeLockPath:Me(t,".red","tmp","rsp.wake.lock"),summaryPath:Me(t,".red","tmp","rsp-status-summary.json"),registryPath:Me(t,".red","tmp","rsp-resident.pid.json")}}var ci=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await zT(this.paths,this.config);let r=await ai(this.paths,{...t,id:su()});if(!r.ok)throw new Error(r.error);return r.value}};async function zT(e,t){if(await Xg(vr(e.socketPath),{recursive:!0,mode:448}),await Qg(e.socketPath,t))return;await Jg(e,t);let r=await OT(e.lockPath);if(r)try{if(await Qg(e.socketPath,t))return;await Jg(e,t),await AT(e.socketPath);let n=NT(e,t);await Wg(e.socketPath,n);return}finally{await r.close(),await zn(e.lockPath,{force:!0})}await Wg(e.socketPath)}async function In(e,t=200){try{return await ey(e,t)!=null}catch{return!1}}async function ey(e,t=200){let r=await ai({socketPath:e,timeoutMs:t},{id:su(),op:"ping"});return r.ok?ry(r.value)?{version:KT(r.value.version)}:{}:null}async function RT(e){try{let t=jT(await xT(e,"utf8"));return HT(t)?t:null}catch{return null}}async function Wg(e,t){let r=Date.now()+IT(),n;for(;Date.now()<r;){if(await In(e))return;if(t){let o=t.spawnError();if(o)throw new Error(ou("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(ou("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?ou("resident rsp server did not start",t):"resident rsp server did not start")}function IT(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:PT}async function AT(e){await zn(e,{force:!0})}async function OT(e){await Xg(vr(e),{recursive:!0,mode:448});try{return await $T(e,nu.O_CREAT|nu.O_EXCL|nu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function NT(e,t){let[r,n]=BT(t),o=process.env.RSP_DEBUG==="1",i,s="",a=bT(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:o?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),o&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{s=DT(`${s}${c}`,CT)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var CT=8*1024;function ou(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
42
+ `);if(d<0)return;let f=a.slice(0,d);l(()=>{try{n(JSON.parse(f))}catch(p){o(p)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var TT=108,PT=1,zT=5e3;function li(e){let t=UT(e)??ui(e),r=ZT(t);return{rootDir:t,socketPath:Me(r,"rsp.sock"),pidPath:Me(r,"rsp.pid"),lockPath:Me(r,"rsp.lock"),wakeLockPath:Me(t,".red","tmp","rsp.wake.lock"),summaryPath:Me(t,".red","tmp","rsp-status-summary.json"),registryPath:Me(t,".red","tmp","rsp-resident.pid.json")}}var ci=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await RT(this.paths,this.config);let r=await ai(this.paths,{...t,id:su()});if(!r.ok)throw new Error(r.error);return r.value}};async function RT(e,t){if(await Xg(br(e.socketPath),{recursive:!0,mode:448}),await Qg(e.socketPath,t))return;await Jg(e,t);let r=await NT(e.lockPath);if(r)try{if(await Qg(e.socketPath,t))return;await Jg(e,t),await AT(e.socketPath);let n=CT(e,t);await Wg(e.socketPath,n);return}finally{await r.close(),await zn(e.lockPath,{force:!0})}await Wg(e.socketPath)}async function In(e,t=200){try{return await ey(e,t)!=null}catch{return!1}}async function ey(e,t=200){let r=await ai({socketPath:e,timeoutMs:t},{id:su(),op:"ping"});return r.ok?ry(r.value)?{version:HT(r.value.version)}:{}:null}async function IT(e){try{let t=MT(await kT(e,"utf8"));return GT(t)?t:null}catch{return null}}async function Wg(e,t){let r=Date.now()+OT(),n;for(;Date.now()<r;){if(await In(e))return;if(t){let o=t.spawnError();if(o)throw new Error(ou("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(ou("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?ou("resident rsp server did not start",t):"resident rsp server did not start")}function OT(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:zT}async function AT(e){await zn(e,{force:!0})}async function NT(e){await Xg(br(e),{recursive:!0,mode:448});try{return await xT(e,nu.O_CREAT|nu.O_EXCL|nu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function CT(e,t){let[r,n]=BT(t),o=process.env.RSP_DEBUG==="1",i,s="",a=bT(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:o?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),o&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{s=jT(`${s}${c}`,DT)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var DT=8*1024;function ou(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
43
43
  ${o}`),n.join(`
44
- `)}function DT(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function jT(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return Pn(t)}}async function Jg(e,t){try{let r=await RT(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!Rn(r.pid)){await zn(e.registryPath,{force:!0});return}if(await In(r.socket_path,100))return;if(ty(t.clientVersion,r.resident_version)&&(await qT(r.pid,1500),!Rn(r.pid))){await zn(e.registryPath,{force:!0});return}await MT(r.pid),await zn(e.registryPath,{force:!0})}catch{}}function Rn(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function MT(e){if(!Rn(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!Rn(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function qT(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!Rn(e))return;await new Promise(n=>setTimeout(n,50))}}function BT(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?ui(process.argv[1]):ST(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function LT(e){let t=wT("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=Me(r,"red-skills",t);if(Me(o,"rsp.sock").length<ET)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return Me(kT(),`red-skills-${n}`,t)}function ZT(e){let t=ui(e);for(let r=0;r<32;r++){try{let o=iu(Me(t,".git"));if(o!=null)return UT(t,o)??t;if(iu(Me(t,".git","HEAD"))!=null||iu(Me(t,".red","config.yaml"))!=null)return t}catch{}let n=vr(t);if(n===t)return null;t=n}return null}function UT(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=ui(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?vr(vr(vr(n))):null}function iu(e){try{return vT(e,"utf8")}catch{return null}}async function Qg(e,t){let r=await ey(e).catch(()=>null);return r?ty(t.clientVersion,r.version)?(await FT(e,t.clientVersion),await GT(e),!1):!0:!1}async function FT(e,t){try{await ai({socketPath:e,timeoutMs:200},{id:su(),op:"handover",clientVersion:t})}catch{}}function ty(e,t){return!e||!t?!1:VT(e,t)>0}function VT(e,t){let r=Yg(e),n=Yg(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function Yg(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function ry(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function KT(e){return typeof e=="string"&&e.length>0?e:void 0}function HT(e){return ry(e)&&e.version===TT&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function GT(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await In(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as WT}from"node:child_process";var cu=["supports","contradicts","related_to"];function uu(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function lu(e){return typeof e=="string"&&cu.includes(e)}function $r(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function ny(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
45
- `)}function JT(e){return{deriveConnections(t){return YT(e,t)}}}function oy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return JT({command:t,args:XT(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:eP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function QT(e){let t=JSON.parse(tP(e));return(Array.isArray(t)?t:au(t)&&Array.isArray(t.connections)?t.connections:[]).filter(rP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:au(n.metadata)?n.metadata:void 0}))}async function YT(e,t){let r=WT(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return QT(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function XT(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function eP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function tP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function rP(e){return au(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&lu(e.kind)}function au(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as di}from"node:fs";import{mkdir as nP,readFile as du,writeFile as oP}from"node:fs/promises";import{dirname as fu,isAbsolute as iP,join as xr,resolve as kt}from"node:path";var fi="file://./.red/brain/brain.rdb",sP="RED_BRAIN_ROOT",aP="brain.root";async function cP(e=process.cwd(),t={}){let n=(t.env??process.env)[sP];if(n)return kt(e,n);let o=await uP(e);if(o)return o;let i=kt(e),s=null;for(;;){let a=xr(i,".red");if(di(a)&&(s??=i,di(xr(a,"brain"))||di(xr(a,aP))))return i;let c=fu(i);if(c===i)return s??kt(e);i=c}}async function uP(e){let t=kt(e);for(;;){let r=xr(t,".red","config.yaml");try{let o=await du(r,"utf8"),i=lP(o);if(i)return kt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=fu(t);if(n===t)return null;t=n}}function lP(e){let t=dP(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function dP(e){let t={},r=[],n=[];for(let o of e.split(`
46
- `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function iy(e){return xr(kt(e),".red","brain","config.yaml")}function fP(e){return xr(kt(e),".env")}async function pP(e){let t=iy(e);return di(t)||(await nP(fu(t),{recursive:!0}),await oP(t,`connection_string: ${fi}
47
- `,"utf8")),t}async function mP(e){let t=iy(e);try{let r=await du(t,"utf8");return hP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function hP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:fi};let r=t.slice(18).trim();return{connection_string:sy(r)||fi}}function sy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function ay(e=process.cwd()){let t=await cP(e),r=await pP(t),n=await mP(t)??{connection_string:fi},o=await gP(t),i=n.connection_string,s=yP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:_P(t,s)}}async function gP(e){let t={...process.env};try{let r=await du(fP(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=sy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function yP(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function _P(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return iP(r)?t:`file://${kt(e,r)}`}import{resolve as wP}from"node:path";var bP=".red/tmp/red-skills.rdb",vP=7,$P=64*1024*1024;function uy(e){return e.connectionString.startsWith("file://")?e.connectionString.slice(7)===dy(e.rootDir):!1}async function ly(e){let t=li(e.rootDir),r=new ci(t,kP(e.rootDir));return await r.request({op:"ping"}),new pu(r)}function xP(e){return`file://${dy(e)}`}function dy(e){return wP(e,bP)}function kP(e){return{storeUri:xP(e),ttlDays:vP,byteBudget:$P,serverCommand:process.env.RSP_BIN??"rsp"}}var pu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return SP(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:cy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:cy(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function cy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function SP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var EP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",TP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function fy(e,t){return EP?zP(e,t):TP?IP(e,t):PP(e,t)}async function PP(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function zP(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:RP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*RP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function IP(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:AP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*AP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as CP}from"node:url";import{dirname as DP,resolve as jP,join as qM}from"node:path";import{existsSync as OP}from"node:fs";import{join as NP}from"node:path";function py(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=NP(r,"bin",t);if(OP(i))return i;throw new Error(`reddb: binary "${t}" not found.
44
+ `)}function jT(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function MT(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return Pn(t)}}async function Jg(e,t){try{let r=await IT(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!Rn(r.pid)){await zn(e.registryPath,{force:!0});return}if(await In(r.socket_path,100))return;if(ty(t.clientVersion,r.resident_version)&&(await LT(r.pid,1500),!Rn(r.pid))){await zn(e.registryPath,{force:!0});return}await qT(r.pid),await zn(e.registryPath,{force:!0})}catch{}}function Rn(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function qT(e){if(!Rn(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!Rn(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function LT(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!Rn(e))return;await new Promise(n=>setTimeout(n,50))}}function BT(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?ui(process.argv[1]):ET(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function ZT(e){let t=vT("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=Me(r,"red-skills",t);if(Me(o,"rsp.sock").length<TT)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return Me(ST(),`red-skills-${n}`,t)}function UT(e){let t=ui(e);for(let r=0;r<32;r++){try{let o=iu(Me(t,".git"));if(o!=null)return FT(t,o)??t;if(iu(Me(t,".git","HEAD"))!=null||iu(Me(t,".red","config.yaml"))!=null)return t}catch{}let n=br(t);if(n===t)return null;t=n}return null}function FT(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=ui(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?br(br(br(n))):null}function iu(e){try{return $T(e,"utf8")}catch{return null}}async function Qg(e,t){let r=await ey(e).catch(()=>null);return r?ty(t.clientVersion,r.version)?(await KT(e,t.clientVersion),await WT(e),!1):!0:!1}async function KT(e,t){try{await ai({socketPath:e,timeoutMs:200},{id:su(),op:"handover",clientVersion:t})}catch{}}function ty(e,t){return!e||!t?!1:VT(e,t)>0}function VT(e,t){let r=Yg(e),n=Yg(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function Yg(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function ry(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HT(e){return typeof e=="string"&&e.length>0?e:void 0}function GT(e){return ry(e)&&e.version===PT&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function WT(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await In(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as JT}from"node:child_process";var cu=["supports","contradicts","related_to"];function uu(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function lu(e){return typeof e=="string"&&cu.includes(e)}function $r(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function ny(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
45
+ `)}function QT(e){return{deriveConnections(t){return XT(e,t)}}}function oy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return QT({command:t,args:eP(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:tP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function YT(e){let t=JSON.parse(rP(e));return(Array.isArray(t)?t:au(t)&&Array.isArray(t.connections)?t.connections:[]).filter(nP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:au(n.metadata)?n.metadata:void 0}))}async function XT(e,t){let r=JT(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return YT(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function eP(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function tP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function rP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function nP(e){return au(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&lu(e.kind)}function au(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as di}from"node:fs";import{mkdir as oP,readFile as du,writeFile as iP}from"node:fs/promises";import{dirname as fu,isAbsolute as sP,join as xr,resolve as kt}from"node:path";var fi="file://./.red/brain/brain.rdb",aP="RED_BRAIN_ROOT",cP="brain.root";async function uP(e=process.cwd(),t={}){let n=(t.env??process.env)[aP];if(n)return kt(e,n);let o=await lP(e);if(o)return o;let i=kt(e),s=null;for(;;){let a=xr(i,".red");if(di(a)&&(s??=i,di(xr(a,"brain"))||di(xr(a,cP))))return i;let c=fu(i);if(c===i)return s??kt(e);i=c}}async function lP(e){let t=kt(e);for(;;){let r=xr(t,".red","config.yaml");try{let o=await du(r,"utf8"),i=dP(o);if(i)return kt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=fu(t);if(n===t)return null;t=n}}function dP(e){let t=fP(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function fP(e){let t={},r=[],n=[];for(let o of e.split(`
46
+ `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function iy(e){return xr(kt(e),".red","brain","config.yaml")}function pP(e){return xr(kt(e),".env")}async function mP(e){let t=iy(e);return di(t)||(await oP(fu(t),{recursive:!0}),await iP(t,`connection_string: ${fi}
47
+ `,"utf8")),t}async function hP(e){let t=iy(e);try{let r=await du(t,"utf8");return gP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function gP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:fi};let r=t.slice(18).trim();return{connection_string:sy(r)||fi}}function sy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function ay(e=process.cwd()){let t=await uP(e),r=await mP(t),n=await hP(t)??{connection_string:fi},o=await yP(t),i=n.connection_string,s=_P(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:wP(t,s)}}async function yP(e){let t={...process.env};try{let r=await du(pP(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=sy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function _P(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function wP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return sP(r)?t:`file://${kt(e,r)}`}import{resolve as vP}from"node:path";var bP=".red/tmp/red-skills.rdb",$P=7,xP=64*1024*1024;function uy(e){return e.connectionString.startsWith("file://")?e.connectionString.slice(7)===dy(e.rootDir):!1}async function ly(e){let t=li(e.rootDir),r=new ci(t,SP(e.rootDir));return await r.request({op:"ping"}),new pu(r)}function kP(e){return`file://${dy(e)}`}function dy(e){return vP(e,bP)}function SP(e){return{storeUri:kP(e),ttlDays:$P,byteBudget:xP,serverCommand:process.env.RSP_BIN??"rsp"}}var pu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return EP(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:cy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:cy(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function cy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function EP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var TP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",PP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function fy(e,t){return TP?RP(e,t):PP?OP(e,t):zP(e,t)}async function zP(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function RP(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:IP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*IP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function OP(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:AP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*AP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as DP}from"node:url";import{dirname as jP,resolve as MP,join as FM}from"node:path";import{existsSync as NP}from"node:fs";import{join as CP}from"node:path";function py(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=CP(r,"bin",t);if(NP(i))return i;throw new Error(`reddb: binary "${t}" not found.
48
48
  expected at: ${i}
49
49
  override: set ${n}=/path/to/${t}
50
50
  fix: re-run \`pnpm install\` (the postinstall script downloads it),
51
- or check the postinstall log for a download error.`)}var MP=DP(CP(import.meta.url)),qP=jP(MP,"..");function BP(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function my(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:py({name:BP(),packageRoot:qP,envVar:"REDDB_BIN"})}var LP=new TextEncoder,ZP=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},pi=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(LP.encode(o+`
52
- `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(ZP.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new z(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new z("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function hu(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?UP(e):FP(e)}function UP(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=VP(o),a=r.port?Number(r.port):mu(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function FP(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):mu(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):mu(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new z("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function VP(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new z("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function mu(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var KP=new Set(["embedded"]),An=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&KP.has(this._transport))throw new z("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:GP(n.value)}async put(t,r,n,o={}){this._guard("put");let i=HP(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function HP(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return hy(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return hy(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function hy(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function GP(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var kr=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(gy).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${gu(o,t)} = ${JP(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${gu(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${gu(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new z("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${yu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(gy).join(", ")}] FROM ${yu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
51
+ or check the postinstall log for a download error.`)}var qP=jP(DP(import.meta.url)),LP=MP(qP,"..");function BP(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function my(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:py({name:BP(),packageRoot:LP,envVar:"REDDB_BIN"})}var ZP=new TextEncoder,UP=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},pi=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(ZP.encode(o+`
52
+ `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(UP.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new z(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new z("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function hu(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?FP(e):KP(e)}function FP(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=VP(o),a=r.port?Number(r.port):mu(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function KP(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):mu(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):mu(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new z("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function VP(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new z("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function mu(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var HP=new Set(["embedded"]),On=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&HP.has(this._transport))throw new z("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:WP(n.value)}async put(t,r,n,o={}){this._guard("put");let i=GP(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function GP(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return hy(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return hy(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function hy(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function WP(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var kr=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(gy).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${gu(o,t)} = ${QP(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${gu(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${gu(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new z("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${yu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(gy).join(", ")}] FROM ${yu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
53
53
 
54
54
  `)){let u=l.split(`
55
- `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function gu(e,t){return`${yu(e)}.${WP(t)}`}function yu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new z("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function WP(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function JP(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function gy(e){return`'${String(e).replace(/'/g,"''")}'`}var On=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${lt(t)}`})}push(t,r,n={}){let o=XP(n);return this.client.call("query",{sql:`QUEUE PUSH ${lt(t)} ${ez(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${lt(t)}${wu(r)}`});return _u(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${lt(t)}${wu(r)}`});return _u(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${lt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${lt(t)}`})}async readWait(t,r,n={}){let o=QP(t,r,n),i=await this.client.call("query",{sql:o});return _u(i)}};function QP(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=lt(e),a=lt(t),c=o!=null?` GROUP ${lt(o)}`:"",l=i!=null?wu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function lt(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function wu(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new z("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function YP(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function XP(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new z("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${YP(e.priority)}`),e.key!=null&&(t+=` KEY ${bu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${bu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function ez(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?bu(e):JSON.stringify(e)}function bu(e){return`'${String(e).replace(/'/g,"''")}'`}function _u(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Nn=class{constructor(t){this.db=t}async insert(t,r){yy(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${mi(t)} DOCUMENT VALUES (${nz(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new z("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=tz(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${mi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){yy(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new z("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new z("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${_y(c)} = ${oz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${mi(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${mi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function yy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function tz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new z("INVALID_ARGUMENT","limit must be a positive integer");return e}function mi(e){return String(e).split(".").map(_y).join(".")}function _y(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function rz(e){return wy(JSON.stringify(e))}function nz(e){return JSON.stringify(e)}function oz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?rz(e):wy(e)}function wy(e){return`'${String(e).replace(/'/g,"''")}'`}var Cn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){sz(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(by).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${St(o)} ${St(t)} = ${iz(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${St(n)} ${St(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${St(n)} ${St(t)}`})}};function iz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${St(r)}.${St(n)})`}return az(e)}function sz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function St(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function az(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):by(e)}function by(e){return`'${String(e).replace(/'/g,"''")}'`}var Dn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){cz(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(vy).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Sr(o)}.${Sr(t)} = ${uz(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Sr(n)}.${Sr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Sr(n)}.${Sr(t)}`})}};function cz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Sr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function uz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):vy(e)}function vy(e){return`'${String(e).replace(/'/g,"''")}'`}async function xy(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(lz)}async function ky(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${fz(t)}`)).rows??[]).some(n=>n.name===String(t))}var jn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new z("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map($y).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${$y(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function lz(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function $y(e){return String(e).split(".").map(dz).join(".")}function dz(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function fz(e){return`'${String(e).replace(/'/g,"''")}'`}var pz="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",mz="1.0",Ty="1.0.9",Sy="NESTED_TX_NOT_SUPPORTED";async function Py(e,t={}){let r=hu(e);if($z(r),r.kind==="embedded"){let n=vz(r,t.auth);if(n.token||n.username)throw new z("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=bz(r),i=t.binary??my(),s=await fy(i,o),a=new pi(s);return await a.call("version",{}),new $u(a,{transport:"embedded"})}}function Ey(e){return hz(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:yz(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&wz(e)?{$uuid:e}:e}function hz(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new z("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new z("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new z("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function gz(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Ey):e.map(Ey)}function yz(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function _z(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function wz(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function hi(e){if(Array.isArray(e))return e.map(hi);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return _z(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=hi(o);return r}return e}function bz(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function vz(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function $z(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",pz)}var gi=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw xu()}},vu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw xu();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new z("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new gi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){zy(r,n)}throw r}}},$u=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=mz,this.cache=new An(t,this.transport),this.queue=new On(t),this.queues=this.queue,this.documents=new Nn(this);let n=new kr(t);this.kv=Object.assign((o="kv_default")=>new kr(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Cn(t,o),this.vault=(o="red.vault")=>new Dn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new z("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=gz(r);return n==null?this.client.call("query",{sql:t}).then(hi):this.client.call("query",{sql:t,params:n}).then(hi)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return xz(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return kz(n,r.length)}tx(){return new vu(this)}async transaction(t){if(this.inTransaction)throw xu();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new gi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){zy(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return ky(this,t)}list(){return xy(this)}from(t){return new jn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function xu(){return new z(Sy,`${Sy}: nested transactions are not supported on one connection`)}function zy(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function xz(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Ty} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function kz(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new z("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Ty} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new z("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Mn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&Sz(t.chosenOption)&&Ez(t.outcome)&&Tz(t.cost)}function Sz(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function Ez(e){return e==="success"||e==="failure"||e==="escalated"}function Tz(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as Pz}from"node:crypto";function ku(e){return Pz("sha256").update(e).digest("hex")}function Ry(e){return ku(JSON.stringify(e))}function Iy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Su="unknown",yi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Pu(t.from),i=Pu(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>zz(p,n)).filter(p=>p!=null).filter(p=>Iz(p,t)).filter(p=>Az(p.ts,o,i)).sort((p,m)=>p.ts-m.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=Cz(c,l,r),f=[Ay(null,s,u,r)];if(t.groupBy){let m=[...Oz(s,t.groupBy).entries()].map(([h,_])=>Ay(h,_,u,r)).sort((h,_)=>_.total-h.total||jz(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function zz(e,t){let r=e.properties.metadata??{},n=Rz(e,r,t);return n==null?null:{ts:n,platform:Eu(r,"platform")??Su,eventType:Eu(r,"event_type")??Su,target:Eu(r,"target")??Su}}function Rz(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Pu(t.timestamp)??n}function Eu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Iz(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function Az(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function Oz(e,t){let r=new Map;for(let n of e){let o=Nz(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function Nz(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Ay(e,t,r,n){let o=new Map;for(let s of t){let a=Tu(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function Cz(e,t,r){if(e==null||t==null)return[];let n=[],o=Tu(e,r),i=Tu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=Dz(o,r),s++;return n}function Tu(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function Dz(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function Pu(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function jz(e,t){return String(e??"").localeCompare(String(t??""))}var Mz=["validate","simple","complex","think"];var qz={validate:1,simple:.85,complex:.65,think:.45};function Bz(){return{schemaVersion:1,buckets:{}}}function Ny(e,t={}){let r=Kz(t.initial??Bz());for(let n of e)Lz(r,n,t);return r}function Lz(e,t,r={}){let n=(r.tierForEvent??Zz)(t);if(!n)return e;let i=Fz(e,t.taskClass).arms[n],s=Uz(t,n);return i.posterior.alpha=Oy(i.posterior.alpha+s),i.posterior.beta=Oy(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function Zz(e){let t=e.chosenOption.kind;if(Hz(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function Uz(e,t){return e.outcome!=="success"?0:qz[t]}function Fz(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=Vz(),e.buckets[r]}function Vz(){return{arms:{validate:_i(),simple:_i(),complex:_i(),think:_i()}}}function _i(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function Kz(e){return JSON.parse(JSON.stringify(e))}function Hz(e){return Mz.includes(e)}function Oy(e){return Math.round(e*1e3)/1e3}var wi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Cy={contact:"person"},bi=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ge={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var $i=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await Py(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.outcomeEvents}`)}kv(){return this.db.kv(Ge.kv)}async capture(t){let r=Zy(t.kind??"note"),n=Date.now(),o=Qz(t.tags??[]),i=Ry([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let h=await this.getArtifact(s);if(h)return h}let a=await this.listArtifacts(),c=`${Iy(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},f=(await this.db.query(`INSERT INTO ${Ge.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let p=Number(f.red_entity_id??f.rid);await this.kv().put(jy(i),p),this.artifactCache=null;let m={...u,rid:p};return await this.autoLinkArtifact(m,a),await this.materializeTagConnections(m),m}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.artifacts}`);this.artifactCache=t.rows.map(Gz).filter(vi)}return this.artifactCache}async search(t,r=10,n={}){let o=Yz(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=Fy(u,o),f=Vy({...d,connections:Xz(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:tR(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=Uy(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Ge.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(My(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.connections}`);this.connectionCache=t.rows.map(Wz).filter(vi)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:cR(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new yi(r).events(t)}async appendOutcomeEvent(t){if(!Mn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ge.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.outcomeEvents}`);this.outcomeEventCache=t.rows.map(Jz).filter(vi).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(qy());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return By(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!By(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(qy(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=Ny(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!$r(i.artifact)).slice(0,r);return rR(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(jy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(My(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||$r(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=ny(t),i=new Set([t.rid]);for(let d of r)$r(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!$r(d.artifact)).map(d=>({artifact:uu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:uu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:cu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!lu(d.kind))continue;let f=await this.getArtifact(d.from),p=await this.getArtifact(d.to);if(!f||!p)continue;let m=f.rid===t.rid||p.rid===t.rid,h=n.has(f.rid)||n.has(p.rid);if(!m||!h||f.rid===p.rid)continue;let _=await this.link({from:f.rid,to:p.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function Zy(e){let r=Cy[e]??e;if(wi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Uy(e){if(bi.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function Gz(e){let t=Number(e.red_entity_id??e.rid),r=zu(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:Zy(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function Wz(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:Uy(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:zu(e.properties??e.PROPERTIES)}}function Jz(e){let t=Number(e.red_entity_id??e.rid),r=zu(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Mn(r)?null:{rid:t,event:r}}function zu(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function vi(e){return e!=null}function Qz(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function Yz(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Dy(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function Fy(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+Dy(r,a)*3+Dy(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function Xz(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||$r(a))continue;let c=Vy({...Fy(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*eR(i.kind))}return Ft(o*.35)}function eR(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function Vy(e){return{...e,lexical:Ft(e.lexical),tags:Ft(e.tags),kind:Ft(e.kind),connections:Ft(e.connections),vector:Ft(e.vector),total:Ft(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Ft(e){return Math.round(e*1e3)/1e3}function tR(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function rR(e,t){let r=t.map(nR),n=oR(t),o=iR(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:sR(e,r,n,o)}}function nR(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function oR(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function iR(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function sR(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
56
- `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${aR(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
57
- `)}function aR(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(vi);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function jy(e){return`artifact.hash.${e}`}function My(e,t,r){return`connection.${e}.${r}.${t}`}function qy(){return`model-tier-bandit.v${1}`}function By(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function cR(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function uR(e=process.cwd()){let t=await ay(e);if(uy(t))try{return{config:t,store:await ly(t),project:Ky(t.rootDir)}}catch(n){let o=li(t.rootDir);if(await In(o.socketPath,50))throw n}let r=await $i.open({uri:t.connectionString,autoLinker:oy()});return{config:t,store:r,project:Ky(t.rootDir)}}async function _e(e,t=process.cwd()){let r=await uR(t);try{return await e(r)}finally{await r.store.close()}}async function Gy(e,t){if(e!=="SessionStart")return{};let r=await _e(async({config:o,store:i})=>(await i.status(),o)),n=Hy(r.rootDir,".red","brain","sessions");return await lR(n,{recursive:!0}),await dR(Hy(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var xi=class{map({event:t,sourceAgent:r}){return{title:fR(t),content:pR(t),kind:"event",tags:mR(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Wy(t),metadata:hR(t)}}};function Wy(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${ku(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function fR(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function pR(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
58
- `)||JSON.stringify(e.raw)}function mR(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function hR(e){let t={event_key:Wy(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function ki(e){let t=new xi,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Vt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Qy(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Vt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Vt("brain_act requires a non-empty message");let o=t.connect??(a=>Zt.connect(a)),i=t.process??gR(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Vt(`brain_act could not reach the channel bridge: ${Jy(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Vt(`brain_act could not send to "${r}": ${Jy(c)}`,{cause:c})}if(!a.ok)throw new Vt(`brain_act could not send to "${r}": ${yR(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function gR(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function yR(e){return _R(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function _R(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function Jy(e){return e instanceof Error?e.message:String(e)}import{createServer as wR}from"node:http";async function e_(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:Ru(n,"supports"),contradicts:Ru(n,"contradicts"),depends_on:Ru(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>bR(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>vR(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function t_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:$R(e)}}async function r_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=wR((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
59
- `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function bR(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:SR(e.properties.content)}}function vR(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function $R(e){return`<!doctype html>
55
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function gu(e,t){return`${yu(e)}.${JP(t)}`}function yu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new z("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function JP(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function QP(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function gy(e){return`'${String(e).replace(/'/g,"''")}'`}var An=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${lt(t)}`})}push(t,r,n={}){let o=ez(n);return this.client.call("query",{sql:`QUEUE PUSH ${lt(t)} ${tz(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${lt(t)}${wu(r)}`});return _u(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${lt(t)}${wu(r)}`});return _u(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${lt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${lt(t)}`})}async readWait(t,r,n={}){let o=YP(t,r,n),i=await this.client.call("query",{sql:o});return _u(i)}};function YP(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=lt(e),a=lt(t),c=o!=null?` GROUP ${lt(o)}`:"",l=i!=null?wu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function lt(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function wu(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new z("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function XP(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function ez(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new z("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${XP(e.priority)}`),e.key!=null&&(t+=` KEY ${vu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${vu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function tz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?vu(e):JSON.stringify(e)}function vu(e){return`'${String(e).replace(/'/g,"''")}'`}function _u(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Nn=class{constructor(t){this.db=t}async insert(t,r){yy(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${mi(t)} DOCUMENT VALUES (${oz(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new z("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=rz(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${mi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){yy(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new z("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new z("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${_y(c)} = ${iz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${mi(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${mi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function yy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function rz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new z("INVALID_ARGUMENT","limit must be a positive integer");return e}function mi(e){return String(e).split(".").map(_y).join(".")}function _y(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function nz(e){return wy(JSON.stringify(e))}function oz(e){return JSON.stringify(e)}function iz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?nz(e):wy(e)}function wy(e){return`'${String(e).replace(/'/g,"''")}'`}var Cn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){az(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(vy).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${St(o)} ${St(t)} = ${sz(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${St(n)} ${St(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${St(n)} ${St(t)}`})}};function sz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${St(r)}.${St(n)})`}return cz(e)}function az(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function St(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function cz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):vy(e)}function vy(e){return`'${String(e).replace(/'/g,"''")}'`}var Dn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){uz(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(by).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Sr(o)}.${Sr(t)} = ${lz(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Sr(n)}.${Sr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Sr(n)}.${Sr(t)}`})}};function uz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Sr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function lz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):by(e)}function by(e){return`'${String(e).replace(/'/g,"''")}'`}async function xy(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(dz)}async function ky(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${pz(t)}`)).rows??[]).some(n=>n.name===String(t))}var jn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new z("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map($y).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${$y(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function dz(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function $y(e){return String(e).split(".").map(fz).join(".")}function fz(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function pz(e){return`'${String(e).replace(/'/g,"''")}'`}var mz="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",hz="1.0",Ty="1.0.9",Sy="NESTED_TX_NOT_SUPPORTED";async function Py(e,t={}){let r=hu(e);if(xz(r),r.kind==="embedded"){let n=$z(r,t.auth);if(n.token||n.username)throw new z("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=bz(r),i=t.binary??my(),s=await fy(i,o),a=new pi(s);return await a.call("version",{}),new $u(a,{transport:"embedded"})}}function Ey(e){return gz(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:_z(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&vz(e)?{$uuid:e}:e}function gz(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new z("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new z("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new z("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function yz(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Ey):e.map(Ey)}function _z(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function wz(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function vz(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function hi(e){if(Array.isArray(e))return e.map(hi);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return wz(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=hi(o);return r}return e}function bz(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function $z(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function xz(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",mz)}var gi=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw xu()}},bu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw xu();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new z("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new gi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){zy(r,n)}throw r}}},$u=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=hz,this.cache=new On(t,this.transport),this.queue=new An(t),this.queues=this.queue,this.documents=new Nn(this);let n=new kr(t);this.kv=Object.assign((o="kv_default")=>new kr(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Cn(t,o),this.vault=(o="red.vault")=>new Dn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new z("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=yz(r);return n==null?this.client.call("query",{sql:t}).then(hi):this.client.call("query",{sql:t,params:n}).then(hi)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return kz(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return Sz(n,r.length)}tx(){return new bu(this)}async transaction(t){if(this.inTransaction)throw xu();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new gi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){zy(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return ky(this,t)}list(){return xy(this)}from(t){return new jn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function xu(){return new z(Sy,`${Sy}: nested transactions are not supported on one connection`)}function zy(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function kz(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Ty} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function Sz(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new z("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Ty} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new z("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Mn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&Ez(t.chosenOption)&&Tz(t.outcome)&&Pz(t.cost)}function Ez(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function Tz(e){return e==="success"||e==="failure"||e==="escalated"}function Pz(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as zz}from"node:crypto";function ku(e){return zz("sha256").update(e).digest("hex")}function Ry(e){return ku(JSON.stringify(e))}function Iy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Su="unknown",yi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Pu(t.from),i=Pu(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>Rz(p,n)).filter(p=>p!=null).filter(p=>Oz(p,t)).filter(p=>Az(p.ts,o,i)).sort((p,m)=>p.ts-m.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=Dz(c,l,r),f=[Oy(null,s,u,r)];if(t.groupBy){let m=[...Nz(s,t.groupBy).entries()].map(([h,_])=>Oy(h,_,u,r)).sort((h,_)=>_.total-h.total||Mz(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function Rz(e,t){let r=e.properties.metadata??{},n=Iz(e,r,t);return n==null?null:{ts:n,platform:Eu(r,"platform")??Su,eventType:Eu(r,"event_type")??Su,target:Eu(r,"target")??Su}}function Iz(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Pu(t.timestamp)??n}function Eu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Oz(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function Az(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function Nz(e,t){let r=new Map;for(let n of e){let o=Cz(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function Cz(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Oy(e,t,r,n){let o=new Map;for(let s of t){let a=Tu(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function Dz(e,t,r){if(e==null||t==null)return[];let n=[],o=Tu(e,r),i=Tu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=jz(o,r),s++;return n}function Tu(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function jz(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function Pu(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function Mz(e,t){return String(e??"").localeCompare(String(t??""))}var qz=["validate","simple","complex","think"];var Lz={validate:1,simple:.85,complex:.65,think:.45};function Bz(){return{schemaVersion:1,buckets:{}}}function Ny(e,t={}){let r=Hz(t.initial??Bz());for(let n of e)Zz(r,n,t);return r}function Zz(e,t,r={}){let n=(r.tierForEvent??Uz)(t);if(!n)return e;let i=Kz(e,t.taskClass).arms[n],s=Fz(t,n);return i.posterior.alpha=Ay(i.posterior.alpha+s),i.posterior.beta=Ay(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function Uz(e){let t=e.chosenOption.kind;if(Gz(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function Fz(e,t){return e.outcome!=="success"?0:Lz[t]}function Kz(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=Vz(),e.buckets[r]}function Vz(){return{arms:{validate:_i(),simple:_i(),complex:_i(),think:_i()}}}function _i(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function Hz(e){return JSON.parse(JSON.stringify(e))}function Gz(e){return qz.includes(e)}function Ay(e){return Math.round(e*1e3)/1e3}var wi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Cy={contact:"person"},vi=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ge={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var $i=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await Py(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.outcomeEvents}`)}kv(){return this.db.kv(Ge.kv)}async capture(t){let r=Zy(t.kind??"note"),n=Date.now(),o=Yz(t.tags??[]),i=Ry([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let h=await this.getArtifact(s);if(h)return h}let a=await this.listArtifacts(),c=`${Iy(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},f=(await this.db.query(`INSERT INTO ${Ge.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let p=Number(f.red_entity_id??f.rid);await this.kv().put(jy(i),p),this.artifactCache=null;let m={...u,rid:p};return await this.autoLinkArtifact(m,a),await this.materializeTagConnections(m),m}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.artifacts}`);this.artifactCache=t.rows.map(Wz).filter(bi)}return this.artifactCache}async search(t,r=10,n={}){let o=Xz(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=Fy(u,o),f=Ky({...d,connections:eR(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:rR(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=Uy(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Ge.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(My(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.connections}`);this.connectionCache=t.rows.map(Jz).filter(bi)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:uR(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new yi(r).events(t)}async appendOutcomeEvent(t){if(!Mn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ge.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.outcomeEvents}`);this.outcomeEventCache=t.rows.map(Qz).filter(bi).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(qy());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return Ly(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!Ly(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(qy(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=Ny(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!$r(i.artifact)).slice(0,r);return nR(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(jy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(My(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||$r(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=ny(t),i=new Set([t.rid]);for(let d of r)$r(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!$r(d.artifact)).map(d=>({artifact:uu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:uu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:cu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!lu(d.kind))continue;let f=await this.getArtifact(d.from),p=await this.getArtifact(d.to);if(!f||!p)continue;let m=f.rid===t.rid||p.rid===t.rid,h=n.has(f.rid)||n.has(p.rid);if(!m||!h||f.rid===p.rid)continue;let _=await this.link({from:f.rid,to:p.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function Zy(e){let r=Cy[e]??e;if(wi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Uy(e){if(vi.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function Wz(e){let t=Number(e.red_entity_id??e.rid),r=zu(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:Zy(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function Jz(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:Uy(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:zu(e.properties??e.PROPERTIES)}}function Qz(e){let t=Number(e.red_entity_id??e.rid),r=zu(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Mn(r)?null:{rid:t,event:r}}function zu(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function bi(e){return e!=null}function Yz(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function Xz(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Dy(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function Fy(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+Dy(r,a)*3+Dy(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function eR(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||$r(a))continue;let c=Ky({...Fy(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*tR(i.kind))}return Ft(o*.35)}function tR(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function Ky(e){return{...e,lexical:Ft(e.lexical),tags:Ft(e.tags),kind:Ft(e.kind),connections:Ft(e.connections),vector:Ft(e.vector),total:Ft(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Ft(e){return Math.round(e*1e3)/1e3}function rR(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function nR(e,t){let r=t.map(oR),n=iR(t),o=sR(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:aR(e,r,n,o)}}function oR(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function iR(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function sR(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function aR(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
56
+ `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${cR(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
57
+ `)}function cR(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(bi);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function jy(e){return`artifact.hash.${e}`}function My(e,t,r){return`connection.${e}.${r}.${t}`}function qy(){return`model-tier-bandit.v${1}`}function Ly(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function uR(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function lR(e=process.cwd()){let t=await ay(e);if(uy(t))try{return{config:t,store:await ly(t),project:Vy(t.rootDir)}}catch(n){let o=li(t.rootDir);if(await In(o.socketPath,50))throw n}let r=await $i.open({uri:t.connectionString,autoLinker:oy()});return{config:t,store:r,project:Vy(t.rootDir)}}async function _e(e,t=process.cwd()){let r=await lR(t);try{return await e(r)}finally{await r.store.close()}}async function Gy(e,t){if(e!=="SessionStart")return{};let r=await _e(async({config:o,store:i})=>(await i.status(),o)),n=Hy(r.rootDir,".red","brain","sessions");return await dR(n,{recursive:!0}),await fR(Hy(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var xi=class{map({event:t,sourceAgent:r}){return{title:pR(t),content:mR(t),kind:"event",tags:hR(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Wy(t),metadata:gR(t)}}};function Wy(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${ku(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function pR(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function mR(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
58
+ `)||JSON.stringify(e.raw)}function hR(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function gR(e){let t={event_key:Wy(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function ki(e){let t=new xi,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Kt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Qy(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Kt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Kt("brain_act requires a non-empty message");let o=t.connect??(a=>Zt.connect(a)),i=t.process??yR(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Kt(`brain_act could not reach the channel bridge: ${Jy(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Kt(`brain_act could not send to "${r}": ${Jy(c)}`,{cause:c})}if(!a.ok)throw new Kt(`brain_act could not send to "${r}": ${_R(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function yR(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function _R(e){return wR(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function wR(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function Jy(e){return e instanceof Error?e.message:String(e)}import{createServer as vR}from"node:http";async function e_(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:Ru(n,"supports"),contradicts:Ru(n,"contradicts"),depends_on:Ru(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>bR(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>$R(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function t_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:xR(e)}}async function r_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=vR((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
59
+ `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function bR(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:ER(e.properties.content)}}function $R(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function xR(e){return`<!doctype html>
60
60
  <html lang="en">
61
61
  <head>
62
62
  <meta charset="utf-8">
@@ -254,37 +254,37 @@ ${o}`),n.join(`
254
254
  <section>
255
255
  <h2>Recent Decisions</h2>
256
256
  <div class="feed">
257
- ${e.recent_decisions.length===0?Xy("No decision artifacts captured yet."):e.recent_decisions.map(xR).join("")}
257
+ ${e.recent_decisions.length===0?Xy("No decision artifacts captured yet."):e.recent_decisions.map(kR).join("")}
258
258
  </div>
259
259
  </section>
260
260
  </div>
261
261
  <section>
262
262
  <h2>Recent Connections</h2>
263
263
  <div class="feed">
264
- ${e.recent_connections.length===0?Xy("No graph connections captured yet."):e.recent_connections.map(kR).join("")}
264
+ ${e.recent_connections.length===0?Xy("No graph connections captured yet."):e.recent_connections.map(SR).join("")}
265
265
  </div>
266
266
  </section>
267
267
  </main>
268
268
  <footer class="meta">${se(e.attribution.red_hermes)}</footer>
269
- <script id="brain-dashboard-data" type="application/json">${ER(e)}</script>
269
+ <script id="brain-dashboard-data" type="application/json">${TR(e)}</script>
270
270
  </body>
271
- </html>`}function Er(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function Yy(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function xR(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
271
+ </html>`}function Er(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function Yy(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function kR(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
272
272
  <h3>${se(e.title)}</h3>
273
273
  <div class="meta">#${e.rid} - ${se(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
274
274
  <p class="meta">${se(e.excerpt)}</p>
275
275
  ${r}
276
- </article>`}function kR(e){return`<article class="item">
276
+ </article>`}function SR(e){return`<article class="item">
277
277
  <h3><span class="edge ${se(e.kind)}">${se(e.kind)}</span> ${se(e.from.title)} -> ${se(e.to.title)}</h3>
278
278
  <div class="meta">#${e.rid} - ${se(e.created_at)}${e.reason?` - ${se(e.reason)}`:""}</div>
279
- </article>`}function Xy(e){return`<div class="empty">${se(e)}</div>`}function Ru(e,t){return e.filter(r=>r.kind===t).length}function SR(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function ER(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as TR,readFile as PR,writeFile as zR}from"node:fs/promises";import{dirname as RR}from"node:path";async function n_(e){let t=await ki({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function o_(e){try{let t=await PR(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function i_(e,t){await TR(RR(e),{recursive:!0}),await zR(e,JSON.stringify(t,null,2)+`
280
- `,"utf8")}async function CR(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":QR();return;case"init":await _e(async({config:r,store:n})=>{let o=await n.status();xe({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await _e(async({config:r,store:n})=>{xe({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await jR(t);return;case"search":await MR(t);return;case"think":case"query":await qR(t);return;case"get":await BR(t);return;case"link":await LR(t);return;case"backlinks":await ZR(t);return;case"act":await HR(t);return;case"hook":await GR(t);return;case"ingest-events":await FR(t);return;case"schedule-ingest":await UR(t);return;case"kpi":case"kpis":await VR(t);return;case"dashboard":await KR(t);return;case"outcome-event":await DR(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function DR(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=We(r),o=await JR(),i=JSON.parse(o);if(!Mn(i))throw new Error("invalid brain outcome event");await _e(async({store:s})=>{xe(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function jR(e){let t=We(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await IR(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await _e(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:WR(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});xe(i)})}async function MR(e){let t=We(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=qn(t,"limit")??10;await _e(async({store:o})=>xe(await o.search(r,n)))}async function qR(e){let t=We(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=qn(t,"limit")??8;await _e(async({store:o})=>{let i=await o.think(r,n);t.json===!0?xe(i):console.log(i.answer)})}async function BR(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await _e(async({store:r})=>{let n=await r.getArtifact(Si(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);xe(n)})}async function LR(e){let t=We(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await _e(async({store:o})=>{xe(await o.link({from:Si(r),to:Si(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function ZR(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await _e(async({store:r})=>xe(await r.backlinks(Si(t))))}async function UR(e){let t=We(e),r=M(t,"session-key")??M(t,"session"),n=qn(t,"limit"),o=await Zt.connect();try{await _e(async({config:i,store:s})=>{let a=M(t,"state")??s_(i.rootDir,".red","brain","ingestion-state.json"),c=await o_(a),l=await n_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await i_(a,l.state),xe(l)})}finally{await o.close().catch(()=>{})}}async function FR(e){let t=We(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=qn(t,"limit"),i=await Zt.connect();try{await _e(async({store:s})=>{let a=await ki({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});xe(a)})}finally{await i.close().catch(()=>{})}}async function VR(e){let t=We(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await _e(async({store:i})=>{xe(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function KR(e){let t=We(e),r=await _e(async({config:o,store:i,project:s})=>{let a=await e_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:t_(a),defaultOut:s_(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){xe(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=qn(t,"port")??4738,s=await r_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await AR(NR(n),{recursive:!0}),await OR(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function HR(e){let t=We(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");xe(await Qy({target:r,message:n}))}async function GR(e){let[t="SessionStart",...r]=e,n=We(r),o=M(n,"runner")??"unknown";xe(await Gy(t,o))}function Si(e){return/^\d+$/.test(e)?Number(e):e}function We(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function WR(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function qn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function xe(e){console.log(JSON.stringify(e,null,2))}async function JR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function QR(){console.log(`brain commands:
279
+ </article>`}function Xy(e){return`<div class="empty">${se(e)}</div>`}function Ru(e,t){return e.filter(r=>r.kind===t).length}function ER(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function TR(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as PR,readFile as zR,writeFile as RR}from"node:fs/promises";import{dirname as IR}from"node:path";async function n_(e){let t=await ki({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function o_(e){try{let t=await zR(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function i_(e,t){await PR(IR(e),{recursive:!0}),await RR(e,JSON.stringify(t,null,2)+`
280
+ `,"utf8")}async function DR(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":YR();return;case"init":await _e(async({config:r,store:n})=>{let o=await n.status();xe({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await _e(async({config:r,store:n})=>{xe({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await MR(t);return;case"search":await qR(t);return;case"think":case"query":await LR(t);return;case"get":await BR(t);return;case"link":await ZR(t);return;case"backlinks":await UR(t);return;case"act":await GR(t);return;case"hook":await WR(t);return;case"ingest-events":await KR(t);return;case"schedule-ingest":await FR(t);return;case"kpi":case"kpis":await VR(t);return;case"dashboard":await HR(t);return;case"outcome-event":await jR(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function jR(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=We(r),o=await QR(),i=JSON.parse(o);if(!Mn(i))throw new Error("invalid brain outcome event");await _e(async({store:s})=>{xe(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function MR(e){let t=We(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await OR(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await _e(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:JR(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});xe(i)})}async function qR(e){let t=We(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=qn(t,"limit")??10;await _e(async({store:o})=>xe(await o.search(r,n)))}async function LR(e){let t=We(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=qn(t,"limit")??8;await _e(async({store:o})=>{let i=await o.think(r,n);t.json===!0?xe(i):console.log(i.answer)})}async function BR(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await _e(async({store:r})=>{let n=await r.getArtifact(Si(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);xe(n)})}async function ZR(e){let t=We(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await _e(async({store:o})=>{xe(await o.link({from:Si(r),to:Si(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function UR(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await _e(async({store:r})=>xe(await r.backlinks(Si(t))))}async function FR(e){let t=We(e),r=M(t,"session-key")??M(t,"session"),n=qn(t,"limit"),o=await Zt.connect();try{await _e(async({config:i,store:s})=>{let a=M(t,"state")??s_(i.rootDir,".red","brain","ingestion-state.json"),c=await o_(a),l=await n_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await i_(a,l.state),xe(l)})}finally{await o.close().catch(()=>{})}}async function KR(e){let t=We(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=qn(t,"limit"),i=await Zt.connect();try{await _e(async({store:s})=>{let a=await ki({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});xe(a)})}finally{await i.close().catch(()=>{})}}async function VR(e){let t=We(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await _e(async({store:i})=>{xe(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function HR(e){let t=We(e),r=await _e(async({config:o,store:i,project:s})=>{let a=await e_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:t_(a),defaultOut:s_(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){xe(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=qn(t,"port")??4738,s=await r_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await AR(CR(n),{recursive:!0}),await NR(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function GR(e){let t=We(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");xe(await Qy({target:r,message:n}))}async function WR(e){let[t="SessionStart",...r]=e,n=We(r),o=M(n,"runner")??"unknown";xe(await Gy(t,o))}function Si(e){return/^\d+$/.test(e)?Number(e):e}function We(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function JR(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function qn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function xe(e){console.log(JSON.stringify(e,null,2))}async function QR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function YR(){console.log(`brain commands:
281
281
  init
282
282
  status
283
283
  capture [text] --title <title> --kind <${wi.join("|")}> --tag <tag>
284
284
  search <query> [--limit N]
285
285
  think <query> [--limit N] [--json]
286
286
  get <rid|id>
287
- link --from <rid|id> --to <rid|id> --kind <${bi.join("|")}>
287
+ link --from <rid|id> --to <rid|id> --kind <${vi.join("|")}>
288
288
  backlinks <rid|id>
289
289
  act --target <channel> --message <text>
290
290
  ingest-events [--after-cursor N] [--session-key KEY] [--limit N]
@@ -292,4 +292,4 @@ ${o}`),n.join(`
292
292
  kpi [--interval hour|day|week|month] [--group-by platform|event_type|target] [--time-field event|ingested] [--from T] [--to T] [--platform P] [--event-type T] [--target T]
293
293
  dashboard [--out PATH] [--json] [--serve] [--host 127.0.0.1] [--port 4738]
294
294
  outcome-event record [--root PATH] < event.json
295
- `)}CR().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
295
+ `)}DR().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});