@reddb-io/red-skills 3.3.13 → 3.3.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.bundle.min.mjs +48 -45
- package/dist/castle-mcp.bundle.min.mjs +357 -354
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +593 -587
- package/dist/memory.bundle.min.mjs +497 -494
- package/dist/redskilled.bundle.min.mjs +91 -72
- package/dist/rsp.bundle.min.mjs +118 -115
- package/package.json +1 -1
|
@@ -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 $b=Object.create;var fs=Object.defineProperty;var Sb=Object.getOwnPropertyDescriptor;var Eb=Object.getOwnPropertyNames;var Tb=Object.getPrototypeOf,Rb=Object.prototype.hasOwnProperty;var Et=(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 v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ml=(e,t)=>{for(var r in t)fs(e,r,{get:t[r],enumerable:!0})},Pb=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Eb(t))!Rb.call(e,o)&&o!==r&&fs(e,o,{get:()=>t[o],enumerable:!(n=Sb(t,o))||n.enumerable});return e};var ps=(e,t,r)=>(r=e!=null?$b(Tb(e)):{},Pb(t||!e||!e.__esModule?fs(r,"default",{value:e,enumerable:!0}):r,e));var xn=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var bn=class{};Z._CodeOrName=bn;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ht=class extends bn{constructor(t){if(super(),!Z.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}}};Z.Name=Ht;var Ze=class extends bn{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Ht&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Ze;Z.nil=new Ze("");function pm(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ia(r,t[n]),r.push(e[++n]);return new Ze(r)}Z._=pm;var Aa=new Ze("+");function mm(e,...t){let r=[vn(e[0])],n=0;for(;n<t.length;)r.push(Aa),Ia(r,t[n]),r.push(Aa,vn(e[++n]));return A0(r),new Ze(r)}Z.str=mm;function Ia(e,t){t instanceof Ze?e.push(...t._items):t instanceof Ht?e.push(t):e.push(N0(t))}Z.addCodeArg=Ia;function A0(e){let t=1;for(;t<e.length-1;){if(e[t]===Aa){let r=I0(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function I0(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ht||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 Ht))return`"${e}${t.slice(1)}`}function C0(e,t){return t.emptyStr()?e:e.emptyStr()?t:mm`${e}${t}`}Z.strConcat=C0;function N0(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:vn(Array.isArray(e)?e.join(","):e)}function D0(e){return new Ze(vn(e))}Z.stringify=D0;function vn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=vn;function j0(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Ze(`.${e}`):pm`[${e}]`}Z.getProperty=j0;function L0(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Ze(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=L0;function M0(e){return new Ze(e.toString())}Z.regexpCode=M0});var Da=v(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.ValueScope=Ae.ValueScopeName=Ae.Scope=Ae.varKinds=Ae.UsedValueState=void 0;var Oe=xn(),Ca=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Ho;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Ho||(Ae.UsedValueState=Ho={}));Ae.varKinds={const:new Oe.Name("const"),let:new Oe.Name("let"),var:new Oe.Name("var")};var Wo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Oe.Name?t:this.name(t)}name(t){return new Oe.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}}};Ae.Scope=Wo;var Go=class extends Oe.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Oe._)`.${new Oe.Name(r)}[${n}]`}};Ae.ValueScopeName=Go;var q0=(0,Oe._)`\n`,Na=class extends Wo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?q0:Oe.nil}}get(){return this._scope}name(t){return new Go(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,Oe._)`${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=Oe.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,Ho.Started);let u=r(l);if(u){let d=this.opts.es5?Ae.varKinds.var:Ae.varKinds.const;i=(0,Oe._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Oe._)`${i}${u}${this.opts._n}`;else throw new Ca(l);c.set(l,Ho.Completed)})}return i}};Ae.ValueScope=Na});var N=v(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var M=xn(),Ye=Da(),Ot=xn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Xo=Da();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Xo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Xo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Xo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Xo.varKinds}});D.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var yt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ja=class extends yt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ye.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=wr(this.rhs,t,r)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},Jo=class extends yt{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 M.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=wr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof M.Name?{}:{...this.lhs.names};return Qo(t,this.rhs)}},La=class extends Jo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Ma=class extends yt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},qa=class extends yt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ba=class extends yt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Za=class extends yt{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=wr(this.code,t,r),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},kn=class extends yt{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)||(B0(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Jt(t,r.names),{})}},_t=class extends kn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ua=class extends kn{},_r=class extends _t{};_r.kind="else";var Wt=class e extends _t{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 _r(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(hm(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=wr(this.condition,t,r),this}get names(){let t=super.names;return Qo(t,this.condition),this.else&&Jt(t,this.else.names),t}};Wt.kind="if";var Gt=class extends _t{};Gt.kind="for";var Fa=class extends Gt{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=wr(this.iteration,t,r),this}get names(){return Jt(super.names,this.iteration.names)}},Va=class extends Gt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ye.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=Qo(super.names,this.from);return Qo(t,this.to)}},Yo=class extends Gt{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=wr(this.iterable,t,r),this}get names(){return Jt(super.names,this.iterable.names)}},$n=class extends _t{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)}};$n.kind="func";var Sn=class extends kn{render(t){return"return "+super.render(t)}};Sn.kind="return";var Ka=class extends _t{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&&Jt(t,this.catch.names),this.finally&&Jt(t,this.finally.names),t}},En=class extends _t{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};En.kind="catch";var Tn=class extends _t{render(t){return"finally"+super.render(t)}};Tn.kind="finally";var Ha=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
4
|
-
`:""},this._extScope=t,this._scope=new Ye.Scope({parent:t}),this._nodes=[new Ua]}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 ja(t,i,n)),i}const(t,r,n){return this._def(Ye.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ye.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ye.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Jo(t,r,n))}add(t,r){return this._leafNode(new La(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==M.nil&&this._leafNode(new Za(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,M.addCodeArg)(r,o));return r.push("}"),new M._Code(r)}if(t,r,n){if(this._blockNode(new Wt(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 Wt(t))}else(){return this._elseNode(new _r)}endIf(){return this._endBlockNode(Wt,_r)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Fa(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let s=this._scope.toName(t);return this._for(new Va(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ye.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof M.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,M._)`${s}.length`,a=>{this.var(i,(0,M._)`${s}[${a}]`),n(i)})}return this._for(new Yo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,M._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Yo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Gt)}label(t){return this._leafNode(new Ma(t))}break(t){return this._leafNode(new qa(t))}return(t){let r=new Sn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Sn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ka;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new En(i),r(i)}return n&&(this._currNode=o.finally=new Tn,this.code(n)),this._endBlockNode(En,Tn)}throw(t){return this._leafNode(new Ba(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=M.nil,n,o){return this._blockNode(new $n(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode($n)}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 Wt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};D.CodeGen=Ha;function Jt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Qo(e,t){return t instanceof M._CodeOrName?Jt(e,t.names):e}function wr(e,t,r){if(e instanceof M.Name)return n(e);if(!o(e))return e;return new M._Code(e._items.reduce((i,s)=>(s instanceof M.Name&&(s=n(s)),s instanceof M._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 M._Code&&i._items.some(s=>s instanceof M.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function B0(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function hm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,M._)`!${Wa(e)}`}D.not=hm;var Z0=gm(D.operators.AND);function U0(...e){return e.reduce(Z0)}D.and=U0;var F0=gm(D.operators.OR);function V0(...e){return e.reduce(F0)}D.or=V0;function gm(e){return(t,r)=>t===M.nil?r:r===M.nil?t:(0,M._)`${Wa(t)} ${e} ${Wa(r)}`}function Wa(e){return e instanceof M.Name?e:(0,M._)`(${e})`}});var q=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var H=N(),K0=xn();function H0(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=H0;function W0(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(wm(e,t),!bm(t,e.self.RULES.all))}j.alwaysValidSchema=W0;function wm(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]||km(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=wm;function bm(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=bm;function G0(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=G0;function J0({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)}`}j.schemaRefOrVal=J0;function Y0(e){return vm(decodeURIComponent(e))}j.unescapeFragment=Y0;function Q0(e){return encodeURIComponent(Ja(e))}j.escapeFragment=Q0;function Ja(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Ja;function vm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=vm;function X0(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=X0;function ym({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}}j.mergeEvaluated={props:ym({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} || {}`),Ya(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:xm}),items:ym({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 xm(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Ya(e,r,t),r}j.evaluatedPropsToName=xm;function Ya(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Ya;var _m={};function ek(e,t){return e.scopeValue("func",{ref:t,code:_m[t.code]||(_m[t.code]=new K0._Code(t.code))})}j.useFunc=ek;var Ga;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ga||(j.Type=Ga={}));function tk(e,t,r){if(e instanceof H.Name){let n=t===Ga.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():"/"+Ja(e)}j.getErrorPath=tk;function km(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=km});var wt=v(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var _e=N(),rk={data:new _e.Name("data"),valCxt:new _e.Name("valCxt"),instancePath:new _e.Name("instancePath"),parentData:new _e.Name("parentData"),parentDataProperty:new _e.Name("parentDataProperty"),rootData:new _e.Name("rootData"),dynamicAnchors:new _e.Name("dynamicAnchors"),vErrors:new _e.Name("vErrors"),errors:new _e.Name("errors"),this:new _e.Name("this"),self:new _e.Name("self"),scope:new _e.Name("scope"),json:new _e.Name("json"),jsonPos:new _e.Name("jsonPos"),jsonLen:new _e.Name("jsonLen"),jsonPart:new _e.Name("jsonPart")};Qa.default=rk});var Rn=v(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.extendErrors=we.resetErrorsCount=we.reportExtraError=we.reportError=we.keyword$DataError=we.keywordError=void 0;var B=N(),ei=q(),Ee=wt();we.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};we.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function nk(e,t=we.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Em(e,t,r);n??(s||a)?$m(i,c):Sm(o,(0,B._)`[${c}]`)}we.reportError=nk;function ok(e,t=we.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Em(e,t,r);$m(o,a),i||s||Sm(n,Ee.default.vErrors)}we.reportExtraError=ok;function ik(e,t){e.assign(Ee.default.errors,t),e.if((0,B._)`${Ee.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Ee.default.vErrors}.length`,t),()=>e.assign(Ee.default.vErrors,null)))}we.resetErrorsCount=ik;function sk({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,Ee.default.errors,a=>{e.const(s,(0,B._)`${Ee.default.vErrors}[${a}]`),e.if((0,B._)`${s}.instancePath === undefined`,()=>e.assign((0,B._)`${s}.instancePath`,(0,B.strConcat)(Ee.default.instancePath,i.errorPath))),e.assign((0,B._)`${s}.schemaPath`,(0,B.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,B._)`${s}.schema`,r),e.assign((0,B._)`${s}.data`,n))})}we.extendErrors=sk;function $m(e,t){let r=e.const("err",t);e.if((0,B._)`${Ee.default.vErrors} === null`,()=>e.assign(Ee.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Ee.default.vErrors}.push(${r})`),e.code((0,B._)`${Ee.default.errors}++`)}function Sm(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Yt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Em(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:ak(e,t,r)}function ak(e,t,r={}){let{gen:n,it:o}=e,i=[ck(o,r),uk(e,r)];return lk(e,t,i),n.object(...i)}function ck({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,ei.getErrorPath)(t,ei.Type.Str)}`:e;return[Ee.default.instancePath,(0,B.strConcat)(Ee.default.instancePath,r)]}function uk({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,B.str)`${t}/${e}`;return r&&(o=(0,B.str)`${o}${(0,ei.getErrorPath)(r,ei.Type.Str)}`),[Yt.schemaPath,o]}function lk(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([Yt.keyword,o],[Yt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Yt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Yt.schema,s],[Yt.parentSchema,(0,B._)`${u}${d}`],[Ee.default.data,i]),l&&n.push([Yt.propertyName,l])}});var Rm=v(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.boolOrEmptySchema=br.topBoolOrEmptySchema=void 0;var dk=Rn(),fk=N(),pk=wt(),mk={message:"boolean schema is false"};function hk(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Tm(e,!1):typeof r=="object"&&r.$async===!0?t.return(pk.default.data):(t.assign((0,fk._)`${n}.errors`,null),t.return(!0))}br.topBoolOrEmptySchema=hk;function gk(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Tm(e)):r.var(t,!0)}br.boolOrEmptySchema=gk;function Tm(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,dk.reportError)(o,mk,void 0,t)}});var Xa=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getRules=vr.isJSONType=void 0;var yk=["string","number","integer","boolean","null","object","array"],_k=new Set(yk);function wk(e){return typeof e=="string"&&_k.has(e)}vr.isJSONType=wk;function bk(){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:{}}}vr.getRules=bk});var ec=v(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.shouldUseRule=At.shouldUseGroup=At.schemaHasRulesForType=void 0;function vk({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pm(e,n)}At.schemaHasRulesForType=vk;function Pm(e,t){return t.rules.some(r=>zm(e,r))}At.shouldUseGroup=Pm;function zm(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))}At.shouldUseRule=zm});var Pn=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.reportTypeError=be.checkDataTypes=be.checkDataType=be.coerceAndCheckDataType=be.getJSONTypes=be.getSchemaTypes=be.DataType=void 0;var xk=Xa(),kk=ec(),$k=Rn(),C=N(),Om=q(),xr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(xr||(be.DataType=xr={}));function Sk(e){let t=Am(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}be.getSchemaTypes=Sk;function Am(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(xk.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}be.getJSONTypes=Am;function Ek(e,t){let{gen:r,data:n,opts:o}=e,i=Tk(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,kk.schemaHasRulesForType)(e,t[0]));if(s){let a=rc(t,n,o.strictNumbers,xr.Wrong);r.if(a,()=>{i.length?Rk(e,t,i):nc(e)})}return s}be.coerceAndCheckDataType=Ek;var Im=new Set(["string","number","integer","boolean","null"]);function Tk(e,t){return t?e.filter(r=>Im.has(r)||t==="array"&&r==="array"):[]}function Rk(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,C._)`typeof ${o}`),a=n.let("coerced",(0,C._)`undefined`);i.coerceTypes==="array"&&n.if((0,C._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,C._)`${o}[0]`).assign(s,(0,C._)`typeof ${o}`).if(rc(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,C._)`${a} !== undefined`);for(let l of r)(Im.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),nc(e),n.endIf(),n.if((0,C._)`${a} !== undefined`,()=>{n.assign(o,a),Pk(e,a)});function c(l){switch(l){case"string":n.elseIf((0,C._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,C._)`"" + ${o}`).elseIf((0,C._)`${o} === null`).assign(a,(0,C._)`""`);return;case"number":n.elseIf((0,C._)`${s} == "boolean" || ${o} === null
|
|
3
|
+
var Ob=Object.create;var fs=Object.defineProperty;var Ab=Object.getOwnPropertyDescriptor;var Ib=Object.getOwnPropertyNames;var Cb=Object.getPrototypeOf,Nb=Object.prototype.hasOwnProperty;var Et=(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 v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ml=(e,t)=>{for(var r in t)fs(e,r,{get:t[r],enumerable:!0})},Db=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ib(t))!Nb.call(e,o)&&o!==r&&fs(e,o,{get:()=>t[o],enumerable:!(n=Ab(t,o))||n.enumerable});return e};var ps=(e,t,r)=>(r=e!=null?Ob(Cb(e)):{},Db(t||!e||!e.__esModule?fs(r,"default",{value:e,enumerable:!0}):r,e));var xn=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var bn=class{};Z._CodeOrName=bn;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ht=class extends bn{constructor(t){if(super(),!Z.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}}};Z.Name=Ht;var Ze=class extends bn{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Ht&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Ze;Z.nil=new Ze("");function pm(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ia(r,t[n]),r.push(e[++n]);return new Ze(r)}Z._=pm;var Aa=new Ze("+");function mm(e,...t){let r=[vn(e[0])],n=0;for(;n<t.length;)r.push(Aa),Ia(r,t[n]),r.push(Aa,vn(e[++n]));return M0(r),new Ze(r)}Z.str=mm;function Ia(e,t){t instanceof Ze?e.push(...t._items):t instanceof Ht?e.push(t):e.push(Z0(t))}Z.addCodeArg=Ia;function M0(e){let t=1;for(;t<e.length-1;){if(e[t]===Aa){let r=q0(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function q0(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ht||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 Ht))return`"${e}${t.slice(1)}`}function B0(e,t){return t.emptyStr()?e:e.emptyStr()?t:mm`${e}${t}`}Z.strConcat=B0;function Z0(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:vn(Array.isArray(e)?e.join(","):e)}function U0(e){return new Ze(vn(e))}Z.stringify=U0;function vn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=vn;function F0(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Ze(`.${e}`):pm`[${e}]`}Z.getProperty=F0;function V0(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Ze(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=V0;function K0(e){return new Ze(e.toString())}Z.regexpCode=K0});var Da=v(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.ValueScope=Ae.ValueScopeName=Ae.Scope=Ae.varKinds=Ae.UsedValueState=void 0;var Oe=xn(),Ca=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Ko;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Ko||(Ae.UsedValueState=Ko={}));Ae.varKinds={const:new Oe.Name("const"),let:new Oe.Name("let"),var:new Oe.Name("var")};var Ho=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Oe.Name?t:this.name(t)}name(t){return new Oe.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}}};Ae.Scope=Ho;var Wo=class extends Oe.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Oe._)`.${new Oe.Name(r)}[${n}]`}};Ae.ValueScopeName=Wo;var H0=(0,Oe._)`\n`,Na=class extends Ho{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?H0:Oe.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,Oe._)`${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=Oe.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,Ko.Started);let u=r(l);if(u){let d=this.opts.es5?Ae.varKinds.var:Ae.varKinds.const;i=(0,Oe._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Oe._)`${i}${u}${this.opts._n}`;else throw new Ca(l);c.set(l,Ko.Completed)})}return i}};Ae.ValueScope=Na});var N=v(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var M=xn(),Ye=Da(),Ot=xn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Qo=Da();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Qo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Qo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Qo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Qo.varKinds}});D.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var yt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ja=class extends yt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ye.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=br(this.rhs,t,r)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},Go=class extends yt{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 M.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=br(this.rhs,t,r),this}get names(){let t=this.lhs instanceof M.Name?{}:{...this.lhs.names};return Yo(t,this.rhs)}},La=class extends Go{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Ma=class extends yt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},qa=class extends yt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ba=class extends yt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Za=class extends yt{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=br(this.code,t,r),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},kn=class extends yt{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)||(W0(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Jt(t,r.names),{})}},_t=class extends kn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ua=class extends kn{},wr=class extends _t{};wr.kind="else";var Wt=class e extends _t{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 wr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(hm(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=br(this.condition,t,r),this}get names(){let t=super.names;return Yo(t,this.condition),this.else&&Jt(t,this.else.names),t}};Wt.kind="if";var Gt=class extends _t{};Gt.kind="for";var Fa=class extends Gt{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=br(this.iteration,t,r),this}get names(){return Jt(super.names,this.iteration.names)}},Va=class extends Gt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ye.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=Yo(super.names,this.from);return Yo(t,this.to)}},Jo=class extends Gt{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=br(this.iterable,t,r),this}get names(){return Jt(super.names,this.iterable.names)}},$n=class extends _t{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)}};$n.kind="func";var Sn=class extends kn{render(t){return"return "+super.render(t)}};Sn.kind="return";var Ka=class extends _t{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&&Jt(t,this.catch.names),this.finally&&Jt(t,this.finally.names),t}},En=class extends _t{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};En.kind="catch";var Tn=class extends _t{render(t){return"finally"+super.render(t)}};Tn.kind="finally";var Ha=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
4
|
+
`:""},this._extScope=t,this._scope=new Ye.Scope({parent:t}),this._nodes=[new Ua]}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 ja(t,i,n)),i}const(t,r,n){return this._def(Ye.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ye.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ye.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Go(t,r,n))}add(t,r){return this._leafNode(new La(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==M.nil&&this._leafNode(new Za(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,M.addCodeArg)(r,o));return r.push("}"),new M._Code(r)}if(t,r,n){if(this._blockNode(new Wt(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 Wt(t))}else(){return this._elseNode(new wr)}endIf(){return this._endBlockNode(Wt,wr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Fa(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let s=this._scope.toName(t);return this._for(new Va(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ye.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof M.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,M._)`${s}.length`,a=>{this.var(i,(0,M._)`${s}[${a}]`),n(i)})}return this._for(new Jo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,M._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Jo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Gt)}label(t){return this._leafNode(new Ma(t))}break(t){return this._leafNode(new qa(t))}return(t){let r=new Sn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Sn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ka;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new En(i),r(i)}return n&&(this._currNode=o.finally=new Tn,this.code(n)),this._endBlockNode(En,Tn)}throw(t){return this._leafNode(new Ba(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=M.nil,n,o){return this._blockNode(new $n(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode($n)}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 Wt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};D.CodeGen=Ha;function Jt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Yo(e,t){return t instanceof M._CodeOrName?Jt(e,t.names):e}function br(e,t,r){if(e instanceof M.Name)return n(e);if(!o(e))return e;return new M._Code(e._items.reduce((i,s)=>(s instanceof M.Name&&(s=n(s)),s instanceof M._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 M._Code&&i._items.some(s=>s instanceof M.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function W0(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function hm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,M._)`!${Wa(e)}`}D.not=hm;var G0=gm(D.operators.AND);function J0(...e){return e.reduce(G0)}D.and=J0;var Y0=gm(D.operators.OR);function Q0(...e){return e.reduce(Y0)}D.or=Q0;function gm(e){return(t,r)=>t===M.nil?r:r===M.nil?t:(0,M._)`${Wa(t)} ${e} ${Wa(r)}`}function Wa(e){return e instanceof M.Name?e:(0,M._)`(${e})`}});var q=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var H=N(),X0=xn();function ek(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=ek;function tk(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(wm(e,t),!bm(t,e.self.RULES.all))}j.alwaysValidSchema=tk;function wm(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]||km(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=wm;function bm(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=bm;function rk(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=rk;function nk({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)}`}j.schemaRefOrVal=nk;function ok(e){return vm(decodeURIComponent(e))}j.unescapeFragment=ok;function ik(e){return encodeURIComponent(Ja(e))}j.escapeFragment=ik;function Ja(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Ja;function vm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=vm;function sk(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=sk;function ym({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}}j.mergeEvaluated={props:ym({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} || {}`),Ya(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:xm}),items:ym({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 xm(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Ya(e,r,t),r}j.evaluatedPropsToName=xm;function Ya(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Ya;var _m={};function ak(e,t){return e.scopeValue("func",{ref:t,code:_m[t.code]||(_m[t.code]=new X0._Code(t.code))})}j.useFunc=ak;var Ga;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ga||(j.Type=Ga={}));function ck(e,t,r){if(e instanceof H.Name){let n=t===Ga.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():"/"+Ja(e)}j.getErrorPath=ck;function km(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=km});var wt=v(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var _e=N(),uk={data:new _e.Name("data"),valCxt:new _e.Name("valCxt"),instancePath:new _e.Name("instancePath"),parentData:new _e.Name("parentData"),parentDataProperty:new _e.Name("parentDataProperty"),rootData:new _e.Name("rootData"),dynamicAnchors:new _e.Name("dynamicAnchors"),vErrors:new _e.Name("vErrors"),errors:new _e.Name("errors"),this:new _e.Name("this"),self:new _e.Name("self"),scope:new _e.Name("scope"),json:new _e.Name("json"),jsonPos:new _e.Name("jsonPos"),jsonLen:new _e.Name("jsonLen"),jsonPart:new _e.Name("jsonPart")};Qa.default=uk});var Rn=v(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.extendErrors=we.resetErrorsCount=we.reportExtraError=we.reportError=we.keyword$DataError=we.keywordError=void 0;var B=N(),Xo=q(),Ee=wt();we.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};we.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function lk(e,t=we.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Em(e,t,r);n??(s||a)?$m(i,c):Sm(o,(0,B._)`[${c}]`)}we.reportError=lk;function dk(e,t=we.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Em(e,t,r);$m(o,a),i||s||Sm(n,Ee.default.vErrors)}we.reportExtraError=dk;function fk(e,t){e.assign(Ee.default.errors,t),e.if((0,B._)`${Ee.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Ee.default.vErrors}.length`,t),()=>e.assign(Ee.default.vErrors,null)))}we.resetErrorsCount=fk;function pk({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,Ee.default.errors,a=>{e.const(s,(0,B._)`${Ee.default.vErrors}[${a}]`),e.if((0,B._)`${s}.instancePath === undefined`,()=>e.assign((0,B._)`${s}.instancePath`,(0,B.strConcat)(Ee.default.instancePath,i.errorPath))),e.assign((0,B._)`${s}.schemaPath`,(0,B.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,B._)`${s}.schema`,r),e.assign((0,B._)`${s}.data`,n))})}we.extendErrors=pk;function $m(e,t){let r=e.const("err",t);e.if((0,B._)`${Ee.default.vErrors} === null`,()=>e.assign(Ee.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Ee.default.vErrors}.push(${r})`),e.code((0,B._)`${Ee.default.errors}++`)}function Sm(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Yt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Em(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:mk(e,t,r)}function mk(e,t,r={}){let{gen:n,it:o}=e,i=[hk(o,r),gk(e,r)];return yk(e,t,i),n.object(...i)}function hk({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,Xo.getErrorPath)(t,Xo.Type.Str)}`:e;return[Ee.default.instancePath,(0,B.strConcat)(Ee.default.instancePath,r)]}function gk({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,B.str)`${t}/${e}`;return r&&(o=(0,B.str)`${o}${(0,Xo.getErrorPath)(r,Xo.Type.Str)}`),[Yt.schemaPath,o]}function yk(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([Yt.keyword,o],[Yt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Yt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Yt.schema,s],[Yt.parentSchema,(0,B._)`${u}${d}`],[Ee.default.data,i]),l&&n.push([Yt.propertyName,l])}});var Rm=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.boolOrEmptySchema=vr.topBoolOrEmptySchema=void 0;var _k=Rn(),wk=N(),bk=wt(),vk={message:"boolean schema is false"};function xk(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Tm(e,!1):typeof r=="object"&&r.$async===!0?t.return(bk.default.data):(t.assign((0,wk._)`${n}.errors`,null),t.return(!0))}vr.topBoolOrEmptySchema=xk;function kk(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Tm(e)):r.var(t,!0)}vr.boolOrEmptySchema=kk;function Tm(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,_k.reportError)(o,vk,void 0,t)}});var Xa=v(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.getRules=xr.isJSONType=void 0;var $k=["string","number","integer","boolean","null","object","array"],Sk=new Set($k);function Ek(e){return typeof e=="string"&&Sk.has(e)}xr.isJSONType=Ek;function Tk(){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:{}}}xr.getRules=Tk});var ec=v(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.shouldUseRule=At.shouldUseGroup=At.schemaHasRulesForType=void 0;function Rk({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pm(e,n)}At.schemaHasRulesForType=Rk;function Pm(e,t){return t.rules.some(r=>zm(e,r))}At.shouldUseGroup=Pm;function zm(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))}At.shouldUseRule=zm});var Pn=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.reportTypeError=be.checkDataTypes=be.checkDataType=be.coerceAndCheckDataType=be.getJSONTypes=be.getSchemaTypes=be.DataType=void 0;var Pk=Xa(),zk=ec(),Ok=Rn(),C=N(),Om=q(),kr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(kr||(be.DataType=kr={}));function Ak(e){let t=Am(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}be.getSchemaTypes=Ak;function Am(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Pk.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}be.getJSONTypes=Am;function Ik(e,t){let{gen:r,data:n,opts:o}=e,i=Ck(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,zk.schemaHasRulesForType)(e,t[0]));if(s){let a=rc(t,n,o.strictNumbers,kr.Wrong);r.if(a,()=>{i.length?Nk(e,t,i):nc(e)})}return s}be.coerceAndCheckDataType=Ik;var Im=new Set(["string","number","integer","boolean","null"]);function Ck(e,t){return t?e.filter(r=>Im.has(r)||t==="array"&&r==="array"):[]}function Nk(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,C._)`typeof ${o}`),a=n.let("coerced",(0,C._)`undefined`);i.coerceTypes==="array"&&n.if((0,C._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,C._)`${o}[0]`).assign(s,(0,C._)`typeof ${o}`).if(rc(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,C._)`${a} !== undefined`);for(let l of r)(Im.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),nc(e),n.endIf(),n.if((0,C._)`${a} !== undefined`,()=>{n.assign(o,a),Dk(e,a)});function c(l){switch(l){case"string":n.elseIf((0,C._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,C._)`"" + ${o}`).elseIf((0,C._)`${o} === null`).assign(a,(0,C._)`""`);return;case"number":n.elseIf((0,C._)`${s} == "boolean" || ${o} === null
|
|
5
5
|
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,C._)`+${o}`);return;case"integer":n.elseIf((0,C._)`${s} === "boolean" || ${o} === null
|
|
6
6
|
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,C._)`+${o}`);return;case"boolean":n.elseIf((0,C._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,C._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,C._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,C._)`${s} === "string" || ${s} === "number"
|
|
7
|
-
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,C._)`[${o}]`)}}}function Pk({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,C._)`${t} !== undefined`,()=>e.assign((0,C._)`${t}[${r}]`,n))}function tc(e,t,r,n=xr.Correct){let o=n===xr.Correct?C.operators.EQ:C.operators.NEQ,i;switch(e){case"null":return(0,C._)`${t} ${o} null`;case"array":i=(0,C._)`Array.isArray(${t})`;break;case"object":i=(0,C._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,C._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,C._)`typeof ${t} ${o} ${e}`}return n===xr.Correct?i:(0,C.not)(i);function s(a=C.nil){return(0,C.and)((0,C._)`typeof ${t} == "number"`,a,r?(0,C._)`isFinite(${t})`:C.nil)}}be.checkDataType=tc;function rc(e,t,r,n){if(e.length===1)return tc(e[0],t,r,n);let o,i=(0,Om.toHash)(e);if(i.array&&i.object){let s=(0,C._)`typeof ${t} != "object"`;o=i.null?s:(0,C._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=C.nil;i.number&&delete i.integer;for(let s in i)o=(0,C.and)(o,tc(s,t,r,n));return o}be.checkDataTypes=rc;var zk={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,C._)`{type: ${e}}`:(0,C._)`{type: ${t}}`};function nc(e){let t=Ok(e);(0,$k.reportError)(t,zk)}be.reportTypeError=nc;function Ok(e){let{gen:t,data:r,schema:n}=e,o=(0,Om.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Nm=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.assignDefaults=void 0;var kr=N(),Ak=q();function Ik(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Cm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Cm(e,i,o.default))}ti.assignDefaults=Ik;function Cm(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,kr._)`${i}${(0,kr.getProperty)(t)}`;if(o){(0,Ak.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,kr._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,kr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,kr._)`${a} = ${(0,kr.stringify)(r)}`)}});var Ue=v(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 ee=N(),oc=q(),It=wt(),Ck=q();function Nk(e,t){let{gen:r,data:n,it:o}=e;r.if(sc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=Nk;function Dk({gen:e,data:t,it:{opts:r}},n,o){return(0,ee.or)(...n.map(i=>(0,ee.and)(sc(e,t,i,r.ownProperties),(0,ee._)`${o} = ${i}`)))}K.checkMissingProp=Dk;function jk(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=jk;function Dm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Dm;function ic(e,t,r){return(0,ee._)`${Dm(e)}.call(${t}, ${r})`}K.isOwnProperty=ic;function Lk(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} !== undefined`;return n?(0,ee._)`${o} && ${ic(e,t,r)}`:o}K.propertyInData=Lk;function sc(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} === undefined`;return n?(0,ee.or)(o,(0,ee.not)(ic(e,t,r))):o}K.noPropertyInData=sc;function jm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=jm;function Mk(e,t){return jm(t).filter(r=>!(0,oc.alwaysValidSchema)(e,t[r]))}K.schemaProperties=Mk;function qk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,ee._)`${e}, ${t}, ${n}${o}`:t,d=[[It.default.instancePath,(0,ee.strConcat)(It.default.instancePath,i)],[It.default.parentData,s.parentData],[It.default.parentDataProperty,s.parentDataProperty],[It.default.rootData,It.default.rootData]];s.opts.dynamicRef&&d.push([It.default.dynamicAnchors,It.default.dynamicAnchors]);let f=(0,ee._)`${u}, ${r.object(...d)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${f})`:(0,ee._)`${a}(${f})`}K.callValidateCode=qk;var Bk=(0,ee._)`new RegExp`;function Zk({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,ee._)`${o.code==="new RegExp"?Bk:(0,Ck.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=Zk;function Uk(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,ee._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:oc.Type.Num},i),t.if((0,ee.not)(i),a)})}}K.validateArray=Uk;function Fk(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,oc.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,ee._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=Fk});var qm=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateKeywordUsage=st.validSchemaType=st.funcKeywordCode=st.macroKeywordCode=void 0;var Te=N(),Qt=wt(),Vk=Ue(),Kk=Rn();function Hk(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Mm(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Te.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}st.macroKeywordCode=Hk;function Wk(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;Jk(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Mm(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&&Lm(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&Lm(e),_(()=>Gk(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Te._)`await `),x=>n.assign(d,!1).if((0,Te._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Te._)`${x}.errors`),()=>n.throw(x))),w}function m(){let w=(0,Te._)`${u}.errors`;return n.assign(w,null),h(Te.nil),w}function h(w=t.async?(0,Te._)`await `:Te.nil){let x=c.opts.passContext?Qt.default.this:Qt.default.self,k=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Te._)`${w}${(0,Vk.callValidateCode)(e,u,x,k)}`,t.modifying)}function _(w){var x;n.if((0,Te.not)((x=t.valid)!==null&&x!==void 0?x:d),w)}}st.funcKeywordCode=Wk;function Lm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Te._)`${n.parentData}[${n.parentDataProperty}]`))}function Gk(e,t){let{gen:r}=e;r.if((0,Te._)`Array.isArray(${t})`,()=>{r.assign(Qt.default.vErrors,(0,Te._)`${Qt.default.vErrors} === null ? ${t} : ${Qt.default.vErrors}.concat(${t})`).assign(Qt.default.errors,(0,Te._)`${Qt.default.vErrors}.length`),(0,Kk.extendErrors)(e)},()=>e.error())}function Jk({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Mm(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,Te.stringify)(r)})}function Yk(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}st.validSchemaType=Yk;function Qk({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)}}st.validateKeywordUsage=Qk});var Zm=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendSubschemaMode=Ct.extendSubschemaData=Ct.getSubschema=void 0;var at=N(),Bm=q();function Xk(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,at._)`${e.schemaPath}${(0,at.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,at._)`${e.schemaPath}${(0,at.getProperty)(t)}${(0,at.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Bm.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')}Ct.getSubschema=Xk;function e$(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,at._)`${t.data}${(0,at.getProperty)(r)}`,!0);c(f),e.errorPath=(0,at.str)`${l}${(0,Bm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,at._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof at.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]}}Ct.extendSubschemaData=e$;function t$(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}Ct.extendSubschemaMode=t$});var ac=v((IM,Um)=>{"use strict";Um.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 Vm=v((CM,Fm)=>{"use strict";var Nt=Fm.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(){};ri(t,n,o,e,"",e)};Nt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nt.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 ri(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 Nt.arrayKeywords)for(var f=0;f<d.length;f++)ri(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in Nt.propsKeywords){if(d&&typeof d=="object")for(var p in d)ri(e,t,r,d[p],o+"/"+u+"/"+r$(p),i,o,u,n,p)}else(u in Nt.keywords||e.allKeys&&!(u in Nt.skipKeywords))&&ri(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function r$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var zn=v(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.getSchemaRefs=Ie.resolveUrl=Ie.normalizeId=Ie._getFullPath=Ie.getFullPath=Ie.inlineRef=void 0;var n$=q(),o$=ac(),i$=Vm(),s$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!cc(e):t?Km(e)<=t:!1}Ie.inlineRef=a$;var c$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cc(e){for(let t in e){if(c$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(cc)||typeof r=="object"&&cc(r))return!0}return!1}function Km(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!s$.has(r)&&(typeof e[r]=="object"&&(0,n$.eachItem)(e[r],n=>t+=Km(n)),t===1/0))return 1/0}return t}function Hm(e,t="",r){r!==!1&&(t=$r(t));let n=e.parse(t);return Wm(e,n)}Ie.getFullPath=Hm;function Wm(e,t){return e.serialize(t).split("#")[0]+"#"}Ie._getFullPath=Wm;var u$=/#\/?$/;function $r(e){return e?e.replace(u$,""):""}Ie.normalizeId=$r;function l$(e,t,r){return r=$r(r),e.resolve(t,r)}Ie.resolveUrl=l$;var d$=/^[a-z_][-a-z0-9._]*$/i;function f$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=$r(e[r]||t),i={"":o},s=Hm(n,o,!1),a={},c=new Set;return i$(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=w.call(this,d[r])),x.call(this,d.$anchor),x.call(this,d.$dynamicAnchor),i[f]=_;function w(k){let R=this.opts.uriResolver.resolve;if(k=$r(_?R(_,k):k),c.has(k))throw u(k);c.add(k);let O=this.refs[k];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,k):k!==$r(h)&&(k[0]==="#"?(l(d,a[k],k),a[k]=d):this.refs[k]=h),k}function x(k){if(typeof k=="string"){if(!d$.test(k))throw new Error(`invalid anchor "${k}"`);w.call(this,`#${k}`)}}}),a;function l(d,f,p){if(f!==void 0&&!o$(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ie.getSchemaRefs=f$});var In=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.getData=Dt.KeywordCxt=Dt.validateFunctionCode=void 0;var Xm=Rm(),Gm=Pn(),lc=ec(),ni=Pn(),p$=Nm(),An=qm(),uc=Zm(),E=N(),I=wt(),m$=zn(),bt=q(),On=Rn();function h$(e){if(rh(e)&&(nh(e),th(e))){_$(e);return}eh(e,()=>(0,Xm.topBoolOrEmptySchema)(e))}Dt.validateFunctionCode=h$;function eh({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,E._)`${I.default.data}, ${I.default.valCxt}`,n.$async,()=>{e.code((0,E._)`"use strict"; ${Jm(r,o)}`),y$(e,o),e.code(i)}):e.func(t,(0,E._)`${I.default.data}, ${g$(o)}`,n.$async,()=>e.code(Jm(r,o)).code(i))}function g$(e){return(0,E._)`{${I.default.instancePath}="", ${I.default.parentData}, ${I.default.parentDataProperty}, ${I.default.rootData}=${I.default.data}${e.dynamicRef?(0,E._)`, ${I.default.dynamicAnchors}={}`:E.nil}}={}`}function y$(e,t){e.if(I.default.valCxt,()=>{e.var(I.default.instancePath,(0,E._)`${I.default.valCxt}.${I.default.instancePath}`),e.var(I.default.parentData,(0,E._)`${I.default.valCxt}.${I.default.parentData}`),e.var(I.default.parentDataProperty,(0,E._)`${I.default.valCxt}.${I.default.parentDataProperty}`),e.var(I.default.rootData,(0,E._)`${I.default.valCxt}.${I.default.rootData}`),t.dynamicRef&&e.var(I.default.dynamicAnchors,(0,E._)`${I.default.valCxt}.${I.default.dynamicAnchors}`)},()=>{e.var(I.default.instancePath,(0,E._)`""`),e.var(I.default.parentData,(0,E._)`undefined`),e.var(I.default.parentDataProperty,(0,E._)`undefined`),e.var(I.default.rootData,I.default.data),t.dynamicRef&&e.var(I.default.dynamicAnchors,(0,E._)`{}`)})}function _$(e){let{schema:t,opts:r,gen:n}=e;eh(e,()=>{r.$comment&&t.$comment&&ih(e),k$(e),n.let(I.default.vErrors,null),n.let(I.default.errors,0),r.unevaluated&&w$(e),oh(e),E$(e)})}function w$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,E._)`${r}.evaluated`),t.if((0,E._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,E._)`${e.evaluated}.props`,(0,E._)`undefined`)),t.if((0,E._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,E._)`${e.evaluated}.items`,(0,E._)`undefined`))}function Jm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,E._)`/*# sourceURL=${r} */`:E.nil}function b$(e,t){if(rh(e)&&(nh(e),th(e))){v$(e,t);return}(0,Xm.boolOrEmptySchema)(e,t)}function th({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 rh(e){return typeof e.schema!="boolean"}function v$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&ih(e),$$(e),S$(e);let i=n.const("_errs",I.default.errors);oh(e,i),n.var(t,(0,E._)`${i} === ${I.default.errors}`)}function nh(e){(0,bt.checkUnknownRules)(e),x$(e)}function oh(e,t){if(e.opts.jtd)return Ym(e,[],!1,t);let r=(0,Gm.getSchemaTypes)(e.schema),n=(0,Gm.coerceAndCheckDataType)(e,r);Ym(e,r,!n,t)}function x$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function k$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(e,"default is ignored in the schema root")}function $$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,m$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function S$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function ih({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,E._)`${I.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,E.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,E._)`${I.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function E$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,E._)`${I.default.errors} === 0`,()=>t.return(I.default.data),()=>t.throw((0,E._)`new ${o}(${I.default.vErrors})`)):(t.assign((0,E._)`${n}.errors`,I.default.vErrors),i.unevaluated&&T$(e),t.return((0,E._)`${I.default.errors} === 0`))}function T$({gen:e,evaluated:t,props:r,items:n}){r instanceof E.Name&&e.assign((0,E._)`${t}.props`,r),n instanceof E.Name&&e.assign((0,E._)`${t}.items`,n)}function Ym(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,bt.schemaHasRulesButRef)(i,u))){o.block(()=>ah(e,"$ref",u.all.$ref.definition));return}c.jtd||R$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,lc.shouldUseGroup)(i,f)&&(f.type?(o.if((0,ni.checkDataType)(f.type,s,c.strictNumbers)),Qm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,ni.reportTypeError)(e)),o.endIf()):Qm(e,f),a||o.if((0,E._)`${I.default.errors} === ${n||0}`))}}function Qm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,p$.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,lc.shouldUseRule)(n,i)&&ah(e,i.keyword,i.definition,t.type)})}function R$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P$(e,t),e.opts.allowUnionTypes||z$(e,t),O$(e,e.dataTypes))}function P$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{sh(e.dataTypes,r)||dc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),I$(e,t)}}function z$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&dc(e,"use allowUnionTypes to allow union type keyword")}function O$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,lc.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>A$(t,s))&&dc(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function A$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function sh(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function I$(e,t){let r=[];for(let n of e.dataTypes)sh(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function dc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(e,t,e.opts.strictTypes)}var oi=class{constructor(t,r,n){if((0,An.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.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",ch(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,An.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",I.default.errors))}result(t,r,n){this.failResult((0,E.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,E.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,E._)`${r} !== undefined && (${(0,E.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=E.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=E.nil,r=E.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,E.or)((0,E._)`${o} === undefined`,r)),t!==E.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==E.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,E.or)(s(),a());function s(){if(n.length){if(!(r instanceof E.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,E._)`${(0,ni.checkDataTypes)(c,r,i.opts.strictNumbers,ni.DataType.Wrong)}`}return E.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,E._)`!${c}(${r})`}return E.nil}}subschema(t,r){let n=(0,uc.getSubschema)(this.it,t);(0,uc.extendSubschemaData)(n,this.it,t),(0,uc.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return b$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=bt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=bt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,E.Name)),!0}};Dt.KeywordCxt=oi;function ah(e,t,r,n){let o=new oi(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,An.funcKeywordCode)(o,r):"macro"in r?(0,An.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,An.funcKeywordCode)(o,r)}var C$=/^\/(?:[^~]|~0|~1)*$/,N$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ch(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return I.default.rootData;if(e[0]==="/"){if(!C$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=I.default.rootData}else{let l=N$.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,E._)`${i}${(0,E.getProperty)((0,bt.unescapeJsonPointer)(l))}`,s=(0,E._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Dt.getData=ch});var ii=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var fc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};pc.default=fc});var Cn=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var mc=zn(),hc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,mc.resolveUrl)(t,r,n),this.missingSchema=(0,mc.normalizeId)((0,mc.getFullPath)(t,this.missingRef))}};gc.default=hc});var ai=v(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Qe=N(),D$=ii(),Xt=wt(),Xe=zn(),uh=q(),j$=In(),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,Xe.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Fe.SchemaEnv=Sr;function _c(e){let t=lh.call(this,e);if(t)return t;let r=(0,Xe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Qe.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:D$.default,code:(0,Qe._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Xt.default.data,parentData:Xt.default.parentData,parentDataProperty:Xt.default.parentDataProperty,dataNames:[Xt.default.data],dataPathArr:[Qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Qe.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Qe.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qe._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,j$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Xt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Xt.default.self}`,`${Xt.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 Qe.Name?void 0:m,items:h instanceof Qe.Name?void 0:h,dynamicProps:m instanceof Qe.Name,dynamicItems:h instanceof Qe.Name},p.source&&(p.source.evaluated=(0,Qe.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)}}Fe.compileSchema=_c;function L$(e,t,r){var n;r=(0,Xe.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=B$.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]=M$.call(this,i)}Fe.resolveRef=L$;function M$(e){return(0,Xe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:_c.call(this,e)}function lh(e){for(let t of this._compilations)if(q$(t,e))return t}Fe.getCompilingSchema=lh;function q$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function B$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||si.call(this,e,t)}function si(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Xe._getFullPath)(this.opts.uriResolver,r),o=(0,Xe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return yc.call(this,r,e);let i=(0,Xe.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=si.call(this,e,s);return typeof a?.schema!="object"?void 0:yc.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||_c.call(this,s),i===(0,Xe.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Xe.resolveUrl)(this.opts.uriResolver,o,l)),new Sr({schema:a,schemaId:c,root:e,baseId:o})}return yc.call(this,r,s)}}Fe.resolveSchema=si;var Z$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function yc(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,uh.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Z$.has(a)&&l&&(t=(0,Xe.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,uh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Xe.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=si.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 dh=v((qM,U$)=>{U$.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 vc=v((BM,yh)=>{"use strict";var F$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ph=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),wc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),mh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),V$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function bc(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 K$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fh(e){return e.length=0,!0}function H$(e,t,r){if(e.length){let n=bc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function W$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=H$;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=fh}else{o.push(l);continue}}return o.length&&(a===fh?r.zone=o.join(""):s?n.push(o.join("")):n.push(bc(o))),r.address=n.join(""),r}function hh(e){if(G$(e,":")<2)return{host:e,isIPV6:!1};let t=W$(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 G$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function J$(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 Y$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Q$=/[@/?#:]/g,X$=/[@/?#]/g;function gh(e,t){let r=t?X$:Q$;return r.lastIndex=0,e.replace(r,n=>Y$[n])}function eS(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(wc(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&mh(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function tS(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(wc(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&mh(i)?t+=i:t+="%"+o,r+=2;continue}}V$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function rS(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(wc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function nS(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!ph(r)){let n=hh(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=gh(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}yh.exports={nonSimpleDomain:K$,recomposeAuthority:nS,reescapeHostDelimiters:gh,normalizePercentEncoding:eS,normalizePathEncoding:tS,escapePreservingEscapes:rS,removeDotSegments:J$,isIPv4:ph,isUUID:F$,normalizeIPv6:hh,stringArrayToHexStripped:bc}});var xh=v((ZM,vh)=>{"use strict";var{isUUID:oS}=vc(),iS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,sS=["http","https","ws","wss","urn","urn:uuid"];function aS(e){return sS.indexOf(e)!==-1}function xc(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 _h(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function wh(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 cS(e){return e.secure=xc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function uS(e){if((e.port===(xc(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 lS(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(iS);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=kc(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function dS(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=kc(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 fS(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!oS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function pS(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var bh={scheme:"http",domainHost:!0,parse:_h,serialize:wh},mS={scheme:"https",domainHost:bh.domainHost,parse:_h,serialize:wh},ci={scheme:"ws",domainHost:!0,parse:cS,serialize:uS},hS={scheme:"wss",domainHost:ci.domainHost,parse:ci.parse,serialize:ci.serialize},gS={scheme:"urn",parse:lS,serialize:dS,skipNormalize:!0},yS={scheme:"urn:uuid",parse:fS,serialize:pS,skipNormalize:!0},ui={http:bh,https:mS,ws:ci,wss:hS,urn:gS,"urn:uuid":yS};Object.setPrototypeOf(ui,null);function kc(e){return e&&(ui[e]||ui[e.toLowerCase()])||void 0}vh.exports={wsIsSecure:xc,SCHEMES:ui,isValidSchemeName:aS,getSchemeHandler:kc}});var Rh=v((UM,li)=>{"use strict";var{normalizeIPv6:_S,removeDotSegments:Nn,recomposeAuthority:wS,normalizePercentEncoding:bS,normalizePathEncoding:vS,escapePreservingEscapes:xS,reescapeHostDelimiters:kS,isIPv4:$S,nonSimpleDomain:SS}=vc(),{SCHEMES:ES,getSchemeHandler:$h}=xh();function TS(e,t){return typeof e=="string"?e=AS(e,t):typeof e=="object"&&(e=Er(er(e,t),t)),e}function RS(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Sh(Er(e,n),Er(t,n),n,!0);return n.skipEscape=!0,er(o,n)}function Sh(e,t,r,n){let o={};return n||(e=Er(er(e,r),r),t=Er(er(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=Nn(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=Nn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Nn(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=Nn(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 PS(e,t,r){let n=kh(e,r),o=kh(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function er(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=$h(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=bS(r.path):(r.path=xS(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=wS(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=Nn(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 zS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function OS(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 Eh(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(zS);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=OS(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if($S(n.host)===!1){let u=_S(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=$h(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&SS(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=kS(unescape(n.host),i))),n.path&&(n.path=vS(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 Er(e,t){return Eh(e,t).parsed}function AS(e,t){return Th(e,t).normalized}function Th(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Eh(e,t);return{normalized:n?e:er(r,t),malformedAuthorityOrPort:n}}function kh(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Th(e,t);return n?void 0:r}if(typeof e=="object")return er(e,t)}var $c={SCHEMES:ES,normalize:TS,resolve:RS,resolveComponent:Sh,equal:PS,serialize:er,parse:Er};li.exports=$c;li.exports.default=$c;li.exports.fastUri=$c});var zh=v(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Ph=Rh();Ph.code='require("ajv/dist/runtime/uri").default';Sc.default=Ph});var Lh=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=void 0;var IS=In();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return IS.KeywordCxt}});var Tr=N();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return Tr._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return Tr.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return Tr.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return Tr.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return Tr.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return Tr.CodeGen}});var CS=ii(),Nh=Cn(),NS=Xa(),Dn=ai(),DS=N(),jn=zn(),di=Pn(),Tc=q(),Oh=dh(),jS=zh(),Dh=(e,t)=>new RegExp(e,t);Dh.code="new RegExp";var LS=["removeAdditional","useDefaults","coerceTypes"],MS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),qS={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."},BS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ah=200;function ZS(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,x,k,R,O,$e,Le,lr,ls;let Jr=e.strict,ds=(t=e.code)===null||t===void 0?void 0:t.optimize,jl=ds===!0||ds===void 0?1:ds||0,Ll=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Dh,kb=(o=e.uriResolver)!==null&&o!==void 0?o:jS.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Jr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Jr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Jr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Jr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Jr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:jl,regExp:Ll}:{optimize:jl,regExp:Ll},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Ah,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Ah,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(x=e.messages)!==null&&x!==void 0?x:!0,inlineRefs:(k=e.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:($e=e.validateSchema)!==null&&$e!==void 0?$e:!0,validateFormats:(Le=e.validateFormats)!==null&&Le!==void 0?Le:!0,unicodeRegExp:(lr=e.unicodeRegExp)!==null&&lr!==void 0?lr:!0,int32range:(ls=e.int32range)!==null&&ls!==void 0?ls:!0,uriResolver:kb}}var Ln=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,...ZS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new DS.ValueScope({scope:{},prefixes:MS,es5:r,lines:n}),this.logger=WS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,NS.getRules)(),Ih.call(this,qS,t,"NOT SUPPORTED"),Ih.call(this,BS,t,"DEPRECATED","warn"),this._metaOpts=KS.call(this),t.formats&&FS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&VS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),US.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Oh;n==="id"&&(o={...Oh},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 Nh.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,jn.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=Ch.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Dn.SchemaEnv({schema:{},schemaId:n});if(r=Dn.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=Ch.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,jn.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(JS.call(this,n,r),!r)return(0,Tc.eachItem)(n,i=>Ec.call(this,i)),this;QS.call(this,r);let o={...r,type:(0,di.getJSONTypes)(r.type),schemaType:(0,di.getJSONTypes)(r.schemaType)};return(0,Tc.eachItem)(n,o.type.length===0?i=>Ec.call(this,i,o):i=>o.type.forEach(s=>Ec.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]=jh(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,jn.normalizeId)(s||n);let l=jn.getSchemaRefs.call(this,t,n);return c=new Dn.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):Dn.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{Dn.compileSchema.call(this,t)}finally{this.opts=r}}};Ln.ValidationError=CS.default;Ln.MissingRefError=Nh.default;me.default=Ln;function Ih(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 Ch(e){return e=(0,jn.normalizeId)(e),this.schemas[e]||this.refs[e]}function US(){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 FS(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function VS(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 KS(){let e={...this.opts};for(let t of LS)delete e[t];return e}var HS={log(){},warn(){},error(){}};function WS(e){if(e===!1)return HS;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 GS=/^[a-z_$][a-z0-9_$:-]*$/i;function JS(e,t){let{RULES:r}=this;if((0,Tc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!GS.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 Ec(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,di.getJSONTypes)(t.type),schemaType:(0,di.getJSONTypes)(t.schemaType)}};t.before?YS.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 YS(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 QS(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=jh(t)),e.validateSchema=this.compile(t,!0))}var XS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jh(e){return{anyOf:[e,XS]}}});var Mh=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var eE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Rc.default=eE});var Uh=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.callRef=tr.getValidate=void 0;var tE=Cn(),qh=Ue(),Ce=N(),Rr=wt(),Bh=ai(),fi=q(),rE={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=Bh.resolveRef.call(c,l,o,r);if(u===void 0)throw new tE.default(n.opts.uriResolver,o,r);if(u instanceof Bh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return pi(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return pi(e,(0,Ce._)`${m}.validate`,l,l.$async)}function f(m){let h=Zh(e,m);pi(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ce.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Ce.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Zh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ce._)`${r.scopeValue("wrapper",{ref:t})}.validate`}tr.getValidate=Zh;function pi(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Rr.default.this:Ce.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,Ce._)`await ${(0,qh.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Ce._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,qh.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Ce._)`${m}.errors`;o.assign(Rr.default.vErrors,(0,Ce._)`${Rr.default.vErrors} === null ? ${h} : ${Rr.default.vErrors}.concat(${h})`),o.assign(Rr.default.errors,(0,Ce._)`${Rr.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=fi.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Ce._)`${m}.evaluated.props`);i.props=fi.mergeEvaluated.props(o,w,i.props,Ce.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=fi.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Ce._)`${m}.evaluated.items`);i.items=fi.mergeEvaluated.items(o,w,i.items,Ce.Name)}}}tr.callRef=pi;tr.default=rE});var Fh=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var nE=Mh(),oE=Uh(),iE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",nE.default,oE.default];Pc.default=iE});var Vh=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var mi=N(),jt=mi.operators,hi={maximum:{okStr:"<=",ok:jt.LTE,fail:jt.GT},minimum:{okStr:">=",ok:jt.GTE,fail:jt.LT},exclusiveMaximum:{okStr:"<",ok:jt.LT,fail:jt.GTE},exclusiveMinimum:{okStr:">",ok:jt.GT,fail:jt.LTE}},sE={message:({keyword:e,schemaCode:t})=>(0,mi.str)`must be ${hi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,mi._)`{comparison: ${hi[e].okStr}, limit: ${t}}`},aE={keyword:Object.keys(hi),type:"number",schemaType:"number",$data:!0,error:sE,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,mi._)`${r} ${hi[t].fail} ${n} || isNaN(${r})`)}};zc.default=aE});var Kh=v(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Mn=N(),cE={message:({schemaCode:e})=>(0,Mn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Mn._)`{multipleOf: ${e}}`},uE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:cE,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Mn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Mn._)`${s} !== parseInt(${s})`;e.fail$data((0,Mn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Oc.default=uE});var Wh=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});function Hh(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}Ac.default=Hh;Hh.code='require("ajv/dist/runtime/ucs2length").default'});var Gh=v(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var rr=N(),lE=q(),dE=Wh(),fE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,rr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,rr._)`{limit: ${e}}`},pE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fE,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?rr.operators.GT:rr.operators.LT,s=o.opts.unicode===!1?(0,rr._)`${r}.length`:(0,rr._)`${(0,lE.useFunc)(e.gen,dE.default)}(${r})`;e.fail$data((0,rr._)`${s} ${i} ${n}`)}};Ic.default=pE});var Jh=v(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var mE=Ue(),hE=q(),Pr=N(),gE={message:({schemaCode:e})=>(0,Pr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Pr._)`{pattern: ${e}}`},yE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gE,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,Pr._)`new RegExp`:(0,hE.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Pr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Pr._)`!${u}`)}else{let c=(0,mE.usePattern)(e,o);e.fail$data((0,Pr._)`!${c}.test(${r})`)}}};Cc.default=yE});var Yh=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var qn=N(),_E={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,qn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,qn._)`{limit: ${e}}`},wE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_E,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?qn.operators.GT:qn.operators.LT;e.fail$data((0,qn._)`Object.keys(${r}).length ${o} ${n}`)}};Nc.default=wE});var Qh=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Bn=Ue(),Zn=N(),bE=q(),vE={message:({params:{missingProperty:e}})=>(0,Zn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Zn._)`{missingProperty: ${e}}`},xE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vE,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,w=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,bE.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(Zn.nil,d);else for(let p of r)(0,Bn.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,Bn.checkMissingProp)(e,r,p)),(0,Bn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Bn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Bn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,Zn.not)(m),()=>{e.error(),t.break()})},Zn.nil)}}};Dc.default=xE});var Xh=v(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Un=N(),kE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Un.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Un._)`{limit: ${e}}`},$E={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kE,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Un.operators.GT:Un.operators.LT;e.fail$data((0,Un._)`${r}.length ${o} ${n}`)}};jc.default=$E});var gi=v(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var eg=ac();eg.code='require("ajv/dist/runtime/equal").default';Lc.default=eg});var tg=v(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Mc=Pn(),he=N(),SE=q(),EE=gi(),TE={message:({params:{i:e,j:t}})=>(0,he.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,he._)`{i: ${e}, j: ${t}}`},RE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:TE,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,Mc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,he._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,he._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,he._)`${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"),w=(0,Mc.checkDataTypes)(l,_,a.opts.strictNumbers,Mc.DataType.Wrong),x=t.const("indices",(0,he._)`{}`);t.for((0,he._)`;${m}--;`,()=>{t.let(_,(0,he._)`${r}[${m}]`),t.if(w,(0,he._)`continue`),l.length>1&&t.if((0,he._)`typeof ${_} == "string"`,(0,he._)`${_} += "_"`),t.if((0,he._)`typeof ${x}[${_}] == "number"`,()=>{t.assign(h,(0,he._)`${x}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,he._)`${x}[${_}] = ${m}`)})}function p(m,h){let _=(0,SE.useFunc)(t,EE.default),w=t.name("outer");t.label(w).for((0,he._)`;${m}--;`,()=>t.for((0,he._)`${h} = ${m}; ${h}--;`,()=>t.if((0,he._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};qc.default=RE});var rg=v(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Bc=N(),PE=q(),zE=gi(),OE={message:"must be equal to constant",params:({schemaCode:e})=>(0,Bc._)`{allowedValue: ${e}}`},AE={keyword:"const",$data:!0,error:OE,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Bc._)`!${(0,PE.useFunc)(t,zE.default)}(${r}, ${o})`):e.fail((0,Bc._)`${i} !== ${r}`)}};Zc.default=AE});var ng=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Fn=N(),IE=q(),CE=gi(),NE={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Fn._)`{allowedValues: ${e}}`},DE={keyword:"enum",schemaType:"array",$data:!0,error:NE,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,IE.useFunc)(t,CE.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,Fn.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,Fn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Fn._)`${l()}(${r}, ${p}[${m}])`:(0,Fn._)`${r} === ${h}`}}};Uc.default=DE});var og=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var jE=Vh(),LE=Kh(),ME=Gh(),qE=Jh(),BE=Yh(),ZE=Qh(),UE=Xh(),FE=tg(),VE=rg(),KE=ng(),HE=[jE.default,LE.default,ME.default,qE.default,BE.default,ZE.default,UE.default,FE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},VE.default,KE.default];Fc.default=HE});var Kc=v(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.validateAdditionalItems=void 0;var nr=N(),Vc=q(),WE={message:({params:{len:e}})=>(0,nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,nr._)`{limit: ${e}}`},GE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WE,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Vc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ig(e,n)}};function ig(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,nr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,nr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Vc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,nr._)`${a} <= ${t.length}`);r.if((0,nr.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Vc.Type.Num},l),s.allErrors||r.if((0,nr.not)(l),()=>r.break())})}}Vn.validateAdditionalItems=ig;Vn.default=GE});var Hc=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateTuple=void 0;var sg=N(),yi=q(),JE=Ue(),YE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return ag(e,"additionalItems",t);r.items=!0,!(0,yi.alwaysValidSchema)(r,t)&&e.ok((0,JE.validateArray)(e))}};function ag(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=yi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,sg._)`${i}.length`);r.forEach((d,f)=>{(0,yi.alwaysValidSchema)(a,d)||(n.if((0,sg._)`${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,yi.checkStrictMode)(a,_,f.strictTuples)}}}Kn.validateTuple=ag;Kn.default=YE});var cg=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var QE=Hc(),XE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,QE.validateTuple)(e,"items")};Wc.default=XE});var lg=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ug=N(),eT=q(),tT=Ue(),rT=Kc(),nT={message:({params:{len:e}})=>(0,ug.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ug._)`{limit: ${e}}`},oT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:nT,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,eT.alwaysValidSchema)(n,t)&&(o?(0,rT.validateAdditionalItems)(e,o):e.ok((0,tT.validateArray)(e)))}};Gc.default=oT});var dg=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Ve=N(),_i=q(),iT={message:({params:{min:e,max:t}})=>t===void 0?(0,Ve.str)`must contain at least ${e} valid item(s)`:(0,Ve.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ve._)`{minContains: ${e}}`:(0,Ve._)`{minContains: ${e}, maxContains: ${t}}`},sT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iT,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,Ve._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,_i.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,_i.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,_i.alwaysValidSchema)(i,r)){let h=(0,Ve._)`${u} >= ${s}`;a!==void 0&&(h=(0,Ve._)`${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,Ve._)`${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,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:_i.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Ve._)`${h}++`),a===void 0?t.if((0,Ve._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Ve._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Ve._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};Jc.default=sT});var mg=v(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.validateSchemaDeps=ct.validatePropertyDeps=ct.error=void 0;var Yc=N(),aT=q(),Hn=Ue();ct.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Yc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Yc._)`{property: ${e},
|
|
7
|
+
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,C._)`[${o}]`)}}}function Dk({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,C._)`${t} !== undefined`,()=>e.assign((0,C._)`${t}[${r}]`,n))}function tc(e,t,r,n=kr.Correct){let o=n===kr.Correct?C.operators.EQ:C.operators.NEQ,i;switch(e){case"null":return(0,C._)`${t} ${o} null`;case"array":i=(0,C._)`Array.isArray(${t})`;break;case"object":i=(0,C._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,C._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,C._)`typeof ${t} ${o} ${e}`}return n===kr.Correct?i:(0,C.not)(i);function s(a=C.nil){return(0,C.and)((0,C._)`typeof ${t} == "number"`,a,r?(0,C._)`isFinite(${t})`:C.nil)}}be.checkDataType=tc;function rc(e,t,r,n){if(e.length===1)return tc(e[0],t,r,n);let o,i=(0,Om.toHash)(e);if(i.array&&i.object){let s=(0,C._)`typeof ${t} != "object"`;o=i.null?s:(0,C._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=C.nil;i.number&&delete i.integer;for(let s in i)o=(0,C.and)(o,tc(s,t,r,n));return o}be.checkDataTypes=rc;var jk={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,C._)`{type: ${e}}`:(0,C._)`{type: ${t}}`};function nc(e){let t=Lk(e);(0,Ok.reportError)(t,jk)}be.reportTypeError=nc;function Lk(e){let{gen:t,data:r,schema:n}=e,o=(0,Om.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Nm=v(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.assignDefaults=void 0;var $r=N(),Mk=q();function qk(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Cm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Cm(e,i,o.default))}ei.assignDefaults=qk;function Cm(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,$r._)`${i}${(0,$r.getProperty)(t)}`;if(o){(0,Mk.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,$r._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$r._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,$r._)`${a} = ${(0,$r.stringify)(r)}`)}});var Ue=v(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 ee=N(),oc=q(),It=wt(),Bk=q();function Zk(e,t){let{gen:r,data:n,it:o}=e;r.if(sc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=Zk;function Uk({gen:e,data:t,it:{opts:r}},n,o){return(0,ee.or)(...n.map(i=>(0,ee.and)(sc(e,t,i,r.ownProperties),(0,ee._)`${o} = ${i}`)))}K.checkMissingProp=Uk;function Fk(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=Fk;function Dm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Dm;function ic(e,t,r){return(0,ee._)`${Dm(e)}.call(${t}, ${r})`}K.isOwnProperty=ic;function Vk(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} !== undefined`;return n?(0,ee._)`${o} && ${ic(e,t,r)}`:o}K.propertyInData=Vk;function sc(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} === undefined`;return n?(0,ee.or)(o,(0,ee.not)(ic(e,t,r))):o}K.noPropertyInData=sc;function jm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=jm;function Kk(e,t){return jm(t).filter(r=>!(0,oc.alwaysValidSchema)(e,t[r]))}K.schemaProperties=Kk;function Hk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,ee._)`${e}, ${t}, ${n}${o}`:t,d=[[It.default.instancePath,(0,ee.strConcat)(It.default.instancePath,i)],[It.default.parentData,s.parentData],[It.default.parentDataProperty,s.parentDataProperty],[It.default.rootData,It.default.rootData]];s.opts.dynamicRef&&d.push([It.default.dynamicAnchors,It.default.dynamicAnchors]);let f=(0,ee._)`${u}, ${r.object(...d)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${f})`:(0,ee._)`${a}(${f})`}K.callValidateCode=Hk;var Wk=(0,ee._)`new RegExp`;function Gk({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,ee._)`${o.code==="new RegExp"?Wk:(0,Bk.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=Gk;function Jk(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,ee._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:oc.Type.Num},i),t.if((0,ee.not)(i),a)})}}K.validateArray=Jk;function Yk(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,oc.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,ee._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=Yk});var qm=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateKeywordUsage=st.validSchemaType=st.funcKeywordCode=st.macroKeywordCode=void 0;var Te=N(),Qt=wt(),Qk=Ue(),Xk=Rn();function e$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Mm(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Te.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}st.macroKeywordCode=e$;function t$(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;n$(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Mm(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&&Lm(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&Lm(e),_(()=>r$(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Te._)`await `),x=>n.assign(d,!1).if((0,Te._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Te._)`${x}.errors`),()=>n.throw(x))),w}function m(){let w=(0,Te._)`${u}.errors`;return n.assign(w,null),h(Te.nil),w}function h(w=t.async?(0,Te._)`await `:Te.nil){let x=c.opts.passContext?Qt.default.this:Qt.default.self,k=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Te._)`${w}${(0,Qk.callValidateCode)(e,u,x,k)}`,t.modifying)}function _(w){var x;n.if((0,Te.not)((x=t.valid)!==null&&x!==void 0?x:d),w)}}st.funcKeywordCode=t$;function Lm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Te._)`${n.parentData}[${n.parentDataProperty}]`))}function r$(e,t){let{gen:r}=e;r.if((0,Te._)`Array.isArray(${t})`,()=>{r.assign(Qt.default.vErrors,(0,Te._)`${Qt.default.vErrors} === null ? ${t} : ${Qt.default.vErrors}.concat(${t})`).assign(Qt.default.errors,(0,Te._)`${Qt.default.vErrors}.length`),(0,Xk.extendErrors)(e)},()=>e.error())}function n$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Mm(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,Te.stringify)(r)})}function o$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}st.validSchemaType=o$;function i$({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)}}st.validateKeywordUsage=i$});var Zm=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendSubschemaMode=Ct.extendSubschemaData=Ct.getSubschema=void 0;var at=N(),Bm=q();function s$(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,at._)`${e.schemaPath}${(0,at.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,at._)`${e.schemaPath}${(0,at.getProperty)(t)}${(0,at.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Bm.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')}Ct.getSubschema=s$;function a$(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,at._)`${t.data}${(0,at.getProperty)(r)}`,!0);c(f),e.errorPath=(0,at.str)`${l}${(0,Bm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,at._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof at.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]}}Ct.extendSubschemaData=a$;function c$(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}Ct.extendSubschemaMode=c$});var ac=v((VM,Um)=>{"use strict";Um.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 Vm=v((KM,Fm)=>{"use strict";var Nt=Fm.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(){};ti(t,n,o,e,"",e)};Nt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nt.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 ti(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 Nt.arrayKeywords)for(var f=0;f<d.length;f++)ti(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in Nt.propsKeywords){if(d&&typeof d=="object")for(var p in d)ti(e,t,r,d[p],o+"/"+u+"/"+u$(p),i,o,u,n,p)}else(u in Nt.keywords||e.allKeys&&!(u in Nt.skipKeywords))&&ti(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function u$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var zn=v(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.getSchemaRefs=Ie.resolveUrl=Ie.normalizeId=Ie._getFullPath=Ie.getFullPath=Ie.inlineRef=void 0;var l$=q(),d$=ac(),f$=Vm(),p$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function m$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!cc(e):t?Km(e)<=t:!1}Ie.inlineRef=m$;var h$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cc(e){for(let t in e){if(h$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(cc)||typeof r=="object"&&cc(r))return!0}return!1}function Km(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!p$.has(r)&&(typeof e[r]=="object"&&(0,l$.eachItem)(e[r],n=>t+=Km(n)),t===1/0))return 1/0}return t}function Hm(e,t="",r){r!==!1&&(t=Sr(t));let n=e.parse(t);return Wm(e,n)}Ie.getFullPath=Hm;function Wm(e,t){return e.serialize(t).split("#")[0]+"#"}Ie._getFullPath=Wm;var g$=/#\/?$/;function Sr(e){return e?e.replace(g$,""):""}Ie.normalizeId=Sr;function y$(e,t,r){return r=Sr(r),e.resolve(t,r)}Ie.resolveUrl=y$;var _$=/^[a-z_][-a-z0-9._]*$/i;function w$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Sr(e[r]||t),i={"":o},s=Hm(n,o,!1),a={},c=new Set;return f$(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=w.call(this,d[r])),x.call(this,d.$anchor),x.call(this,d.$dynamicAnchor),i[f]=_;function w(k){let R=this.opts.uriResolver.resolve;if(k=Sr(_?R(_,k):k),c.has(k))throw u(k);c.add(k);let O=this.refs[k];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,k):k!==Sr(h)&&(k[0]==="#"?(l(d,a[k],k),a[k]=d):this.refs[k]=h),k}function x(k){if(typeof k=="string"){if(!_$.test(k))throw new Error(`invalid anchor "${k}"`);w.call(this,`#${k}`)}}}),a;function l(d,f,p){if(f!==void 0&&!d$(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ie.getSchemaRefs=w$});var In=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.getData=Dt.KeywordCxt=Dt.validateFunctionCode=void 0;var Xm=Rm(),Gm=Pn(),lc=ec(),ri=Pn(),b$=Nm(),An=qm(),uc=Zm(),E=N(),I=wt(),v$=zn(),bt=q(),On=Rn();function x$(e){if(rh(e)&&(nh(e),th(e))){S$(e);return}eh(e,()=>(0,Xm.topBoolOrEmptySchema)(e))}Dt.validateFunctionCode=x$;function eh({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,E._)`${I.default.data}, ${I.default.valCxt}`,n.$async,()=>{e.code((0,E._)`"use strict"; ${Jm(r,o)}`),$$(e,o),e.code(i)}):e.func(t,(0,E._)`${I.default.data}, ${k$(o)}`,n.$async,()=>e.code(Jm(r,o)).code(i))}function k$(e){return(0,E._)`{${I.default.instancePath}="", ${I.default.parentData}, ${I.default.parentDataProperty}, ${I.default.rootData}=${I.default.data}${e.dynamicRef?(0,E._)`, ${I.default.dynamicAnchors}={}`:E.nil}}={}`}function $$(e,t){e.if(I.default.valCxt,()=>{e.var(I.default.instancePath,(0,E._)`${I.default.valCxt}.${I.default.instancePath}`),e.var(I.default.parentData,(0,E._)`${I.default.valCxt}.${I.default.parentData}`),e.var(I.default.parentDataProperty,(0,E._)`${I.default.valCxt}.${I.default.parentDataProperty}`),e.var(I.default.rootData,(0,E._)`${I.default.valCxt}.${I.default.rootData}`),t.dynamicRef&&e.var(I.default.dynamicAnchors,(0,E._)`${I.default.valCxt}.${I.default.dynamicAnchors}`)},()=>{e.var(I.default.instancePath,(0,E._)`""`),e.var(I.default.parentData,(0,E._)`undefined`),e.var(I.default.parentDataProperty,(0,E._)`undefined`),e.var(I.default.rootData,I.default.data),t.dynamicRef&&e.var(I.default.dynamicAnchors,(0,E._)`{}`)})}function S$(e){let{schema:t,opts:r,gen:n}=e;eh(e,()=>{r.$comment&&t.$comment&&ih(e),z$(e),n.let(I.default.vErrors,null),n.let(I.default.errors,0),r.unevaluated&&E$(e),oh(e),I$(e)})}function E$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,E._)`${r}.evaluated`),t.if((0,E._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,E._)`${e.evaluated}.props`,(0,E._)`undefined`)),t.if((0,E._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,E._)`${e.evaluated}.items`,(0,E._)`undefined`))}function Jm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,E._)`/*# sourceURL=${r} */`:E.nil}function T$(e,t){if(rh(e)&&(nh(e),th(e))){R$(e,t);return}(0,Xm.boolOrEmptySchema)(e,t)}function th({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 rh(e){return typeof e.schema!="boolean"}function R$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&ih(e),O$(e),A$(e);let i=n.const("_errs",I.default.errors);oh(e,i),n.var(t,(0,E._)`${i} === ${I.default.errors}`)}function nh(e){(0,bt.checkUnknownRules)(e),P$(e)}function oh(e,t){if(e.opts.jtd)return Ym(e,[],!1,t);let r=(0,Gm.getSchemaTypes)(e.schema),n=(0,Gm.coerceAndCheckDataType)(e,r);Ym(e,r,!n,t)}function P$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function z$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(e,"default is ignored in the schema root")}function O$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,v$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function A$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function ih({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,E._)`${I.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,E.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,E._)`${I.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function I$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,E._)`${I.default.errors} === 0`,()=>t.return(I.default.data),()=>t.throw((0,E._)`new ${o}(${I.default.vErrors})`)):(t.assign((0,E._)`${n}.errors`,I.default.vErrors),i.unevaluated&&C$(e),t.return((0,E._)`${I.default.errors} === 0`))}function C$({gen:e,evaluated:t,props:r,items:n}){r instanceof E.Name&&e.assign((0,E._)`${t}.props`,r),n instanceof E.Name&&e.assign((0,E._)`${t}.items`,n)}function Ym(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,bt.schemaHasRulesButRef)(i,u))){o.block(()=>ah(e,"$ref",u.all.$ref.definition));return}c.jtd||N$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,lc.shouldUseGroup)(i,f)&&(f.type?(o.if((0,ri.checkDataType)(f.type,s,c.strictNumbers)),Qm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,ri.reportTypeError)(e)),o.endIf()):Qm(e,f),a||o.if((0,E._)`${I.default.errors} === ${n||0}`))}}function Qm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,b$.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,lc.shouldUseRule)(n,i)&&ah(e,i.keyword,i.definition,t.type)})}function N$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(D$(e,t),e.opts.allowUnionTypes||j$(e,t),L$(e,e.dataTypes))}function D$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{sh(e.dataTypes,r)||dc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),q$(e,t)}}function j$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&dc(e,"use allowUnionTypes to allow union type keyword")}function L$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,lc.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>M$(t,s))&&dc(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function M$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function sh(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function q$(e,t){let r=[];for(let n of e.dataTypes)sh(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function dc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(e,t,e.opts.strictTypes)}var ni=class{constructor(t,r,n){if((0,An.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.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",ch(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,An.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",I.default.errors))}result(t,r,n){this.failResult((0,E.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,E.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,E._)`${r} !== undefined && (${(0,E.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=E.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=E.nil,r=E.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,E.or)((0,E._)`${o} === undefined`,r)),t!==E.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==E.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,E.or)(s(),a());function s(){if(n.length){if(!(r instanceof E.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,E._)`${(0,ri.checkDataTypes)(c,r,i.opts.strictNumbers,ri.DataType.Wrong)}`}return E.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,E._)`!${c}(${r})`}return E.nil}}subschema(t,r){let n=(0,uc.getSubschema)(this.it,t);(0,uc.extendSubschemaData)(n,this.it,t),(0,uc.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return T$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=bt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=bt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,E.Name)),!0}};Dt.KeywordCxt=ni;function ah(e,t,r,n){let o=new ni(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,An.funcKeywordCode)(o,r):"macro"in r?(0,An.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,An.funcKeywordCode)(o,r)}var B$=/^\/(?:[^~]|~0|~1)*$/,Z$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ch(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return I.default.rootData;if(e[0]==="/"){if(!B$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=I.default.rootData}else{let l=Z$.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,E._)`${i}${(0,E.getProperty)((0,bt.unescapeJsonPointer)(l))}`,s=(0,E._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Dt.getData=ch});var oi=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var fc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};pc.default=fc});var Cn=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var mc=zn(),hc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,mc.resolveUrl)(t,r,n),this.missingSchema=(0,mc.normalizeId)((0,mc.getFullPath)(t,this.missingRef))}};gc.default=hc});var si=v(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Qe=N(),U$=oi(),Xt=wt(),Xe=zn(),uh=q(),F$=In(),Er=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,Xe.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Fe.SchemaEnv=Er;function _c(e){let t=lh.call(this,e);if(t)return t;let r=(0,Xe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Qe.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:U$.default,code:(0,Qe._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Xt.default.data,parentData:Xt.default.parentData,parentDataProperty:Xt.default.parentDataProperty,dataNames:[Xt.default.data],dataPathArr:[Qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Qe.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Qe.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qe._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,F$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Xt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Xt.default.self}`,`${Xt.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 Qe.Name?void 0:m,items:h instanceof Qe.Name?void 0:h,dynamicProps:m instanceof Qe.Name,dynamicItems:h instanceof Qe.Name},p.source&&(p.source.evaluated=(0,Qe.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)}}Fe.compileSchema=_c;function V$(e,t,r){var n;r=(0,Xe.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=W$.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 Er({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=K$.call(this,i)}Fe.resolveRef=V$;function K$(e){return(0,Xe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:_c.call(this,e)}function lh(e){for(let t of this._compilations)if(H$(t,e))return t}Fe.getCompilingSchema=lh;function H$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function W$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ii.call(this,e,t)}function ii(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Xe._getFullPath)(this.opts.uriResolver,r),o=(0,Xe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return yc.call(this,r,e);let i=(0,Xe.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=ii.call(this,e,s);return typeof a?.schema!="object"?void 0:yc.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||_c.call(this,s),i===(0,Xe.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Xe.resolveUrl)(this.opts.uriResolver,o,l)),new Er({schema:a,schemaId:c,root:e,baseId:o})}return yc.call(this,r,s)}}Fe.resolveSchema=ii;var G$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function yc(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,uh.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!G$.has(a)&&l&&(t=(0,Xe.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,uh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Xe.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=ii.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new Er({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var dh=v((QM,J$)=>{J$.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 vc=v((XM,yh)=>{"use strict";var Y$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ph=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),wc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),mh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Q$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function bc(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 X$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fh(e){return e.length=0,!0}function eS(e,t,r){if(e.length){let n=bc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function tS(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=eS;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=fh}else{o.push(l);continue}}return o.length&&(a===fh?r.zone=o.join(""):s?n.push(o.join("")):n.push(bc(o))),r.address=n.join(""),r}function hh(e){if(rS(e,":")<2)return{host:e,isIPV6:!1};let t=tS(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 rS(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function nS(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 oS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},iS=/[@/?#:]/g,sS=/[@/?#]/g;function gh(e,t){let r=t?sS:iS;return r.lastIndex=0,e.replace(r,n=>oS[n])}function aS(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(wc(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&mh(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function cS(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(wc(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&mh(i)?t+=i:t+="%"+o,r+=2;continue}}Q$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function uS(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(wc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function lS(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!ph(r)){let n=hh(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=gh(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}yh.exports={nonSimpleDomain:X$,recomposeAuthority:lS,reescapeHostDelimiters:gh,normalizePercentEncoding:aS,normalizePathEncoding:cS,escapePreservingEscapes:uS,removeDotSegments:nS,isIPv4:ph,isUUID:Y$,normalizeIPv6:hh,stringArrayToHexStripped:bc}});var xh=v((eq,vh)=>{"use strict";var{isUUID:dS}=vc(),fS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,pS=["http","https","ws","wss","urn","urn:uuid"];function mS(e){return pS.indexOf(e)!==-1}function xc(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 _h(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function wh(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 hS(e){return e.secure=xc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function gS(e){if((e.port===(xc(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 yS(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(fS);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=kc(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function _S(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=kc(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 wS(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!dS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function bS(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var bh={scheme:"http",domainHost:!0,parse:_h,serialize:wh},vS={scheme:"https",domainHost:bh.domainHost,parse:_h,serialize:wh},ai={scheme:"ws",domainHost:!0,parse:hS,serialize:gS},xS={scheme:"wss",domainHost:ai.domainHost,parse:ai.parse,serialize:ai.serialize},kS={scheme:"urn",parse:yS,serialize:_S,skipNormalize:!0},$S={scheme:"urn:uuid",parse:wS,serialize:bS,skipNormalize:!0},ci={http:bh,https:vS,ws:ai,wss:xS,urn:kS,"urn:uuid":$S};Object.setPrototypeOf(ci,null);function kc(e){return e&&(ci[e]||ci[e.toLowerCase()])||void 0}vh.exports={wsIsSecure:xc,SCHEMES:ci,isValidSchemeName:mS,getSchemeHandler:kc}});var Rh=v((tq,ui)=>{"use strict";var{normalizeIPv6:SS,removeDotSegments:Nn,recomposeAuthority:ES,normalizePercentEncoding:TS,normalizePathEncoding:RS,escapePreservingEscapes:PS,reescapeHostDelimiters:zS,isIPv4:OS,nonSimpleDomain:AS}=vc(),{SCHEMES:IS,getSchemeHandler:$h}=xh();function CS(e,t){return typeof e=="string"?e=MS(e,t):typeof e=="object"&&(e=Tr(er(e,t),t)),e}function NS(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Sh(Tr(e,n),Tr(t,n),n,!0);return n.skipEscape=!0,er(o,n)}function Sh(e,t,r,n){let o={};return n||(e=Tr(er(e,r),r),t=Tr(er(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=Nn(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=Nn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Nn(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=Nn(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 DS(e,t,r){let n=kh(e,r),o=kh(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function er(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=$h(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=TS(r.path):(r.path=PS(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=ES(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=Nn(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 jS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function LS(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 Eh(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(jS);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=LS(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(OS(n.host)===!1){let u=SS(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=$h(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&AS(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=zS(unescape(n.host),i))),n.path&&(n.path=RS(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 Tr(e,t){return Eh(e,t).parsed}function MS(e,t){return Th(e,t).normalized}function Th(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Eh(e,t);return{normalized:n?e:er(r,t),malformedAuthorityOrPort:n}}function kh(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Th(e,t);return n?void 0:r}if(typeof e=="object")return er(e,t)}var $c={SCHEMES:IS,normalize:CS,resolve:NS,resolveComponent:Sh,equal:DS,serialize:er,parse:Tr};ui.exports=$c;ui.exports.default=$c;ui.exports.fastUri=$c});var zh=v(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Ph=Rh();Ph.code='require("ajv/dist/runtime/uri").default';Sc.default=Ph});var Lh=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=void 0;var qS=In();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return qS.KeywordCxt}});var Rr=N();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return Rr._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return Rr.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return Rr.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return Rr.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return Rr.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return Rr.CodeGen}});var BS=oi(),Nh=Cn(),ZS=Xa(),Dn=si(),US=N(),jn=zn(),li=Pn(),Tc=q(),Oh=dh(),FS=zh(),Dh=(e,t)=>new RegExp(e,t);Dh.code="new RegExp";var VS=["removeAdditional","useDefaults","coerceTypes"],KS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),HS={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."},WS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ah=200;function GS(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,x,k,R,O,$e,Le,dr,ls;let Jr=e.strict,ds=(t=e.code)===null||t===void 0?void 0:t.optimize,jl=ds===!0||ds===void 0?1:ds||0,Ll=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Dh,zb=(o=e.uriResolver)!==null&&o!==void 0?o:FS.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Jr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Jr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Jr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Jr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Jr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:jl,regExp:Ll}:{optimize:jl,regExp:Ll},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Ah,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Ah,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(x=e.messages)!==null&&x!==void 0?x:!0,inlineRefs:(k=e.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:($e=e.validateSchema)!==null&&$e!==void 0?$e:!0,validateFormats:(Le=e.validateFormats)!==null&&Le!==void 0?Le:!0,unicodeRegExp:(dr=e.unicodeRegExp)!==null&&dr!==void 0?dr:!0,int32range:(ls=e.int32range)!==null&&ls!==void 0?ls:!0,uriResolver:zb}}var Ln=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,...GS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new US.ValueScope({scope:{},prefixes:KS,es5:r,lines:n}),this.logger=tE(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,ZS.getRules)(),Ih.call(this,HS,t,"NOT SUPPORTED"),Ih.call(this,WS,t,"DEPRECATED","warn"),this._metaOpts=XS.call(this),t.formats&&YS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&QS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),JS.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Oh;n==="id"&&(o={...Oh},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 Nh.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,jn.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=Ch.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Dn.SchemaEnv({schema:{},schemaId:n});if(r=Dn.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=Ch.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,jn.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(nE.call(this,n,r),!r)return(0,Tc.eachItem)(n,i=>Ec.call(this,i)),this;iE.call(this,r);let o={...r,type:(0,li.getJSONTypes)(r.type),schemaType:(0,li.getJSONTypes)(r.schemaType)};return(0,Tc.eachItem)(n,o.type.length===0?i=>Ec.call(this,i,o):i=>o.type.forEach(s=>Ec.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]=jh(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,jn.normalizeId)(s||n);let l=jn.getSchemaRefs.call(this,t,n);return c=new Dn.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):Dn.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{Dn.compileSchema.call(this,t)}finally{this.opts=r}}};Ln.ValidationError=BS.default;Ln.MissingRefError=Nh.default;me.default=Ln;function Ih(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 Ch(e){return e=(0,jn.normalizeId)(e),this.schemas[e]||this.refs[e]}function JS(){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 YS(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function QS(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 XS(){let e={...this.opts};for(let t of VS)delete e[t];return e}var eE={log(){},warn(){},error(){}};function tE(e){if(e===!1)return eE;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 rE=/^[a-z_$][a-z0-9_$:-]*$/i;function nE(e,t){let{RULES:r}=this;if((0,Tc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!rE.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 Ec(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,li.getJSONTypes)(t.type),schemaType:(0,li.getJSONTypes)(t.schemaType)}};t.before?oE.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 oE(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 iE(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=jh(t)),e.validateSchema=this.compile(t,!0))}var sE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jh(e){return{anyOf:[e,sE]}}});var Mh=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var aE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Rc.default=aE});var Uh=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.callRef=tr.getValidate=void 0;var cE=Cn(),qh=Ue(),Ce=N(),Pr=wt(),Bh=si(),di=q(),uE={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=Bh.resolveRef.call(c,l,o,r);if(u===void 0)throw new cE.default(n.opts.uriResolver,o,r);if(u instanceof Bh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return fi(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return fi(e,(0,Ce._)`${m}.validate`,l,l.$async)}function f(m){let h=Zh(e,m);fi(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ce.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Ce.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Zh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ce._)`${r.scopeValue("wrapper",{ref:t})}.validate`}tr.getValidate=Zh;function fi(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Pr.default.this:Ce.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,Ce._)`await ${(0,qh.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Ce._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,qh.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Ce._)`${m}.errors`;o.assign(Pr.default.vErrors,(0,Ce._)`${Pr.default.vErrors} === null ? ${h} : ${Pr.default.vErrors}.concat(${h})`),o.assign(Pr.default.errors,(0,Ce._)`${Pr.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=di.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Ce._)`${m}.evaluated.props`);i.props=di.mergeEvaluated.props(o,w,i.props,Ce.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=di.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Ce._)`${m}.evaluated.items`);i.items=di.mergeEvaluated.items(o,w,i.items,Ce.Name)}}}tr.callRef=fi;tr.default=uE});var Fh=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var lE=Mh(),dE=Uh(),fE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lE.default,dE.default];Pc.default=fE});var Vh=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var pi=N(),jt=pi.operators,mi={maximum:{okStr:"<=",ok:jt.LTE,fail:jt.GT},minimum:{okStr:">=",ok:jt.GTE,fail:jt.LT},exclusiveMaximum:{okStr:"<",ok:jt.LT,fail:jt.GTE},exclusiveMinimum:{okStr:">",ok:jt.GT,fail:jt.LTE}},pE={message:({keyword:e,schemaCode:t})=>(0,pi.str)`must be ${mi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,pi._)`{comparison: ${mi[e].okStr}, limit: ${t}}`},mE={keyword:Object.keys(mi),type:"number",schemaType:"number",$data:!0,error:pE,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,pi._)`${r} ${mi[t].fail} ${n} || isNaN(${r})`)}};zc.default=mE});var Kh=v(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Mn=N(),hE={message:({schemaCode:e})=>(0,Mn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Mn._)`{multipleOf: ${e}}`},gE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hE,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Mn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Mn._)`${s} !== parseInt(${s})`;e.fail$data((0,Mn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Oc.default=gE});var Wh=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});function Hh(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}Ac.default=Hh;Hh.code='require("ajv/dist/runtime/ucs2length").default'});var Gh=v(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var rr=N(),yE=q(),_E=Wh(),wE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,rr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,rr._)`{limit: ${e}}`},bE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wE,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?rr.operators.GT:rr.operators.LT,s=o.opts.unicode===!1?(0,rr._)`${r}.length`:(0,rr._)`${(0,yE.useFunc)(e.gen,_E.default)}(${r})`;e.fail$data((0,rr._)`${s} ${i} ${n}`)}};Ic.default=bE});var Jh=v(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var vE=Ue(),xE=q(),zr=N(),kE={message:({schemaCode:e})=>(0,zr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,zr._)`{pattern: ${e}}`},$E={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:kE,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,zr._)`new RegExp`:(0,xE.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,zr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,zr._)`!${u}`)}else{let c=(0,vE.usePattern)(e,o);e.fail$data((0,zr._)`!${c}.test(${r})`)}}};Cc.default=$E});var Yh=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var qn=N(),SE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,qn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,qn._)`{limit: ${e}}`},EE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:SE,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?qn.operators.GT:qn.operators.LT;e.fail$data((0,qn._)`Object.keys(${r}).length ${o} ${n}`)}};Nc.default=EE});var Qh=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Bn=Ue(),Zn=N(),TE=q(),RE={message:({params:{missingProperty:e}})=>(0,Zn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Zn._)`{missingProperty: ${e}}`},PE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RE,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,w=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,TE.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(Zn.nil,d);else for(let p of r)(0,Bn.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,Bn.checkMissingProp)(e,r,p)),(0,Bn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Bn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Bn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,Zn.not)(m),()=>{e.error(),t.break()})},Zn.nil)}}};Dc.default=PE});var Xh=v(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Un=N(),zE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Un.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Un._)`{limit: ${e}}`},OE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zE,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Un.operators.GT:Un.operators.LT;e.fail$data((0,Un._)`${r}.length ${o} ${n}`)}};jc.default=OE});var hi=v(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var eg=ac();eg.code='require("ajv/dist/runtime/equal").default';Lc.default=eg});var tg=v(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Mc=Pn(),he=N(),AE=q(),IE=hi(),CE={message:({params:{i:e,j:t}})=>(0,he.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,he._)`{i: ${e}, j: ${t}}`},NE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:CE,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,Mc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,he._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,he._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,he._)`${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"),w=(0,Mc.checkDataTypes)(l,_,a.opts.strictNumbers,Mc.DataType.Wrong),x=t.const("indices",(0,he._)`{}`);t.for((0,he._)`;${m}--;`,()=>{t.let(_,(0,he._)`${r}[${m}]`),t.if(w,(0,he._)`continue`),l.length>1&&t.if((0,he._)`typeof ${_} == "string"`,(0,he._)`${_} += "_"`),t.if((0,he._)`typeof ${x}[${_}] == "number"`,()=>{t.assign(h,(0,he._)`${x}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,he._)`${x}[${_}] = ${m}`)})}function p(m,h){let _=(0,AE.useFunc)(t,IE.default),w=t.name("outer");t.label(w).for((0,he._)`;${m}--;`,()=>t.for((0,he._)`${h} = ${m}; ${h}--;`,()=>t.if((0,he._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};qc.default=NE});var rg=v(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Bc=N(),DE=q(),jE=hi(),LE={message:"must be equal to constant",params:({schemaCode:e})=>(0,Bc._)`{allowedValue: ${e}}`},ME={keyword:"const",$data:!0,error:LE,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Bc._)`!${(0,DE.useFunc)(t,jE.default)}(${r}, ${o})`):e.fail((0,Bc._)`${i} !== ${r}`)}};Zc.default=ME});var ng=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Fn=N(),qE=q(),BE=hi(),ZE={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Fn._)`{allowedValues: ${e}}`},UE={keyword:"enum",schemaType:"array",$data:!0,error:ZE,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,qE.useFunc)(t,BE.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,Fn.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,Fn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Fn._)`${l()}(${r}, ${p}[${m}])`:(0,Fn._)`${r} === ${h}`}}};Uc.default=UE});var og=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var FE=Vh(),VE=Kh(),KE=Gh(),HE=Jh(),WE=Yh(),GE=Qh(),JE=Xh(),YE=tg(),QE=rg(),XE=ng(),eT=[FE.default,VE.default,KE.default,HE.default,WE.default,GE.default,JE.default,YE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},QE.default,XE.default];Fc.default=eT});var Kc=v(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.validateAdditionalItems=void 0;var nr=N(),Vc=q(),tT={message:({params:{len:e}})=>(0,nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,nr._)`{limit: ${e}}`},rT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:tT,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Vc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ig(e,n)}};function ig(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,nr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,nr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Vc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,nr._)`${a} <= ${t.length}`);r.if((0,nr.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Vc.Type.Num},l),s.allErrors||r.if((0,nr.not)(l),()=>r.break())})}}Vn.validateAdditionalItems=ig;Vn.default=rT});var Hc=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateTuple=void 0;var sg=N(),gi=q(),nT=Ue(),oT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return ag(e,"additionalItems",t);r.items=!0,!(0,gi.alwaysValidSchema)(r,t)&&e.ok((0,nT.validateArray)(e))}};function ag(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=gi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,sg._)`${i}.length`);r.forEach((d,f)=>{(0,gi.alwaysValidSchema)(a,d)||(n.if((0,sg._)`${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,gi.checkStrictMode)(a,_,f.strictTuples)}}}Kn.validateTuple=ag;Kn.default=oT});var cg=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var iT=Hc(),sT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,iT.validateTuple)(e,"items")};Wc.default=sT});var lg=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ug=N(),aT=q(),cT=Ue(),uT=Kc(),lT={message:({params:{len:e}})=>(0,ug.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ug._)`{limit: ${e}}`},dT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:lT,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,aT.alwaysValidSchema)(n,t)&&(o?(0,uT.validateAdditionalItems)(e,o):e.ok((0,cT.validateArray)(e)))}};Gc.default=dT});var dg=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Ve=N(),yi=q(),fT={message:({params:{min:e,max:t}})=>t===void 0?(0,Ve.str)`must contain at least ${e} valid item(s)`:(0,Ve.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ve._)`{minContains: ${e}}`:(0,Ve._)`{minContains: ${e}, maxContains: ${t}}`},pT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:fT,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,Ve._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,yi.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,yi.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,yi.alwaysValidSchema)(i,r)){let h=(0,Ve._)`${u} >= ${s}`;a!==void 0&&(h=(0,Ve._)`${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,Ve._)`${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,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:yi.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Ve._)`${h}++`),a===void 0?t.if((0,Ve._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Ve._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Ve._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};Jc.default=pT});var mg=v(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.validateSchemaDeps=ct.validatePropertyDeps=ct.error=void 0;var Yc=N(),mT=q(),Hn=Ue();ct.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Yc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Yc._)`{property: ${e},
|
|
8
8
|
missingProperty: ${n},
|
|
9
9
|
depsCount: ${t},
|
|
10
|
-
deps: ${r}}`};var cT={keyword:"dependencies",type:"object",schemaType:"object",error:ct.error,code(e){let[t,r]=uT(e);fg(e,t),pg(e,r)}};function uT({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 fg(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,Hn.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,Hn.checkReportMissingProp)(e,l)}):(r.if((0,Yc._)`${c} && (${(0,Hn.checkMissingProp)(e,a,i)})`),(0,Hn.reportMissingProp)(e,i),r.else())}}ct.validatePropertyDeps=fg;function pg(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,aT.alwaysValidSchema)(i,t[a])||(r.if((0,Hn.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))}ct.validateSchemaDeps=pg;ct.default=cT});var gg=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var hg=N(),lT=q(),dT={message:"property name must be valid",params:({params:e})=>(0,hg._)`{propertyName: ${e.propertyName}}`},fT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dT,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,lT.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,hg.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Qc.default=fT});var eu=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var wi=Ue(),et=N(),pT=wt(),bi=q(),mT={message:"must NOT have additional properties",params:({params:e})=>(0,et._)`{additionalProperty: ${e.additionalProperty}}`},hT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mT,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,bi.alwaysValidSchema)(s,r))return;let l=(0,wi.allSchemaProperties)(n.properties),u=(0,wi.allSchemaProperties)(n.patternProperties);d(),e.ok((0,et._)`${i} === ${pT.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let w;if(l.length>8){let x=(0,bi.schemaRefOrVal)(s,n.properties,"properties");w=(0,wi.isOwnProperty)(t,x,_)}else l.length?w=(0,et.or)(...l.map(x=>(0,et._)`${_} === ${x}`)):w=et.nil;return u.length&&(w=(0,et.or)(w,...u.map(x=>(0,et._)`${(0,wi.usePattern)(e,x)}.test(${_})`))),(0,et.not)(w)}function p(_){t.code((0,et._)`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,bi.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,et.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,et.not)(w),()=>t.break()))}}function h(_,w,x){let k={keyword:"additionalProperties",dataProp:_,dataPropType:bi.Type.Str};x===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(k,w)}}};Xc.default=hT});var wg=v(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var gT=In(),yg=Ue(),tu=q(),_g=eu(),yT={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&&_g.default.code(new gT.KeywordCxt(i,_g.default,"additionalProperties"));let s=(0,yg.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=tu.mergeEvaluated.props(t,(0,tu.toHash)(s),i.props));let a=s.filter(d=>!(0,tu.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,yg.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)}}};ru.default=yT});var kg=v(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var bg=Ue(),vi=N(),vg=q(),xg=q(),_T={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,bg.allSchemaProperties)(r),c=a.filter(h=>(0,vg.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 vi.Name)&&(i.props=(0,xg.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,vg.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,vi._)`${(0,bg.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:xg.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,vi._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,vi.not)(u),()=>t.break())})})}}};nu.default=_T});var $g=v(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var wT=q(),bT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,wT.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"}};ou.default=bT});var Sg=v(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var vT=Ue(),xT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vT.validateUnion,error:{message:"must match a schema in anyOf"}};iu.default=xT});var Eg=v(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var xi=N(),kT=q(),$T={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,xi._)`{passingSchemas: ${e.passing}}`},ST={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$T,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,kT.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,xi._)`${c} && ${s}`).assign(s,!1).assign(a,(0,xi._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,xi.Name)})})}}};su.default=ST});var Tg=v(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var ET=q(),TT={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,ET.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};au.default=TT});var zg=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var ki=N(),Pg=q(),RT={message:({params:e})=>(0,ki.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,ki._)`{failingKeyword: ${e.ifClause}}`},PT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:RT,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Pg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Rg(n,"then"),i=Rg(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,ki.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,ki._)`${u}`):e.setParams({ifClause:u})}}}};function Rg(e,t){let r=e.schema[t];return r!==void 0&&!(0,Pg.alwaysValidSchema)(e,r)}cu.default=PT});var Og=v(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var zT=q(),OT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,zT.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};uu.default=OT});var Ag=v(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var AT=Kc(),IT=cg(),CT=Hc(),NT=lg(),DT=dg(),jT=mg(),LT=gg(),MT=eu(),qT=wg(),BT=kg(),ZT=$g(),UT=Sg(),FT=Eg(),VT=Tg(),KT=zg(),HT=Og();function WT(e=!1){let t=[ZT.default,UT.default,FT.default,VT.default,KT.default,HT.default,LT.default,MT.default,jT.default,qT.default,BT.default];return e?t.push(IT.default,NT.default):t.push(AT.default,CT.default),t.push(DT.default),t}lu.default=WT});var Ig=v(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var se=N(),GT={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},JT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:GT,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,se._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,se._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,se._)`${h}.type || "string"`).assign(w,(0,se._)`${h}.validate`),()=>r.assign(_,(0,se._)`"string"`).assign(w,h)),e.fail$data((0,se.or)(x(),k()));function x(){return c.strictSchema===!1?se.nil:(0,se._)`${s} && !${w}`}function k(){let R=u.$async?(0,se._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,se._)`${w}(${n})`,O=(0,se._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${n}))`;return(0,se._)`${w} && ${w} !== true && ${_} === ${t} && !${O}`}}function p(){let m=d.formats[i];if(!m){x();return}if(m===!0)return;let[h,_,w]=k(m);h===t&&e.pass(R());function x(){if(c.strictSchema===!1){d.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function k(O){let $e=O instanceof RegExp?(0,se.regexpCode)(O):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(i)}`:void 0,Le=r.scopeValue("formats",{key:i,ref:O,code:$e});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,se._)`${Le}.validate`]:["string",O,Le]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,se._)`await ${w}(${n})`}return typeof _=="function"?(0,se._)`${w}(${n})`:(0,se._)`${w}.test(${n})`}}}};du.default=JT});var Cg=v(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var YT=Ig(),QT=[YT.default];fu.default=QT});var Ng=v(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.contentVocabulary=zr.metadataVocabulary=void 0;zr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var jg=v(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var XT=Fh(),eR=og(),tR=Ag(),rR=Cg(),Dg=Ng(),nR=[XT.default,eR.default,(0,tR.default)(),rR.default,Dg.metadataVocabulary,Dg.contentVocabulary];pu.default=nR});var Mg=v($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.DiscrError=void 0;var Lg;(function(e){e.Tag="tag",e.Mapping="mapping"})(Lg||($i.DiscrError=Lg={}))});var Bg=v(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var Or=N(),mu=Mg(),qg=ai(),oR=Cn(),iR=q(),sR={message:({params:{discrError:e,tagName:t}})=>e===mu.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Or._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},aR={keyword:"discriminator",type:"object",schemaType:"object",error:sR,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,Or._)`${r}${(0,Or.getProperty)(a)}`);t.if((0,Or._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:mu.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,Or._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:mu.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,Or.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let R=0;R<s.length;R++){let O=s[R];if(O?.$ref&&!(0,iR.schemaHasRulesButRef)(O,i.self.RULES)){let Le=O.$ref;if(O=qg.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Le),O instanceof qg.SchemaEnv&&(O=O.schema),O===void 0)throw new oR.default(i.opts.uriResolver,i.baseId,Le)}let $e=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof $e!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),x($e,R)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(a)}function x(R,O){if(R.const)k(R.const,O);else if(R.enum)for(let $e of R.enum)k($e,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(R,O){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[R]=O}}}};hu.default=aR});var Zg=v((Oq,cR)=>{cR.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 yu=v((te,gu)=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.MissingRefError=te.ValidationError=te.CodeGen=te.Name=te.nil=te.stringify=te.str=te._=te.KeywordCxt=te.Ajv=void 0;var uR=Lh(),lR=jg(),dR=Bg(),Ug=Zg(),fR=["/properties"],Si="http://json-schema.org/draft-07/schema",Ar=class extends uR.default{_addVocabularies(){super._addVocabularies(),lR.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(dR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Ug,fR):Ug;this.addMetaSchema(t,Si,!1),this.refs["http://json-schema.org/schema"]=Si}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Si)?Si:void 0)}};te.Ajv=Ar;gu.exports=te=Ar;gu.exports.Ajv=Ar;Object.defineProperty(te,"__esModule",{value:!0});te.default=Ar;var pR=In();Object.defineProperty(te,"KeywordCxt",{enumerable:!0,get:function(){return pR.KeywordCxt}});var Ir=N();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Ir._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Ir.str}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Ir.stringify}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Ir.nil}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Ir.Name}});Object.defineProperty(te,"CodeGen",{enumerable:!0,get:function(){return Ir.CodeGen}});var mR=ii();Object.defineProperty(te,"ValidationError",{enumerable:!0,get:function(){return mR.default}});var hR=Cn();Object.defineProperty(te,"MissingRefError",{enumerable:!0,get:function(){return hR.default}})});var Yg=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatNames=lt.fastFormats=lt.fullFormats=void 0;function ut(e,t){return{validate:e,compare:t}}lt.fullFormats={date:ut(Hg,vu),time:ut(wu(!0),xu),"date-time":ut(Fg(!0),Gg),"iso-time":ut(wu(),Wg),"iso-date-time":ut(Fg(),Jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:vR,"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:RR,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:xR,int32:{type:"number",validate:SR},int64:{type:"number",validate:ER},float:{type:"number",validate:Kg},double:{type:"number",validate:Kg},password:!0,binary:!0};lt.fastFormats={...lt.fullFormats,date:ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vu),time:ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xu),"date-time":ut(/^\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,Gg),"iso-time":ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Wg),"iso-date-time":ut(/^\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,Jg),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};lt.formatNames=Object.keys(lt.fullFormats);function gR(e){return e%4===0&&(e%100!==0||e%400===0)}var yR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_R=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Hg(e){let t=yR.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&&gR(r)?29:_R[n])}function vu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var _u=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wu(e){return function(r){let n=_u.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 xu(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 Wg(e,t){if(!(e&&t))return;let r=_u.exec(e),n=_u.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 bu=/t|\s/i;function Fg(e){let t=wu(e);return function(n){let o=n.split(bu);return o.length===2&&Hg(o[0])&&t(o[1])}}function Gg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Jg(e,t){if(!(e&&t))return;let[r,n]=e.split(bu),[o,i]=t.split(bu),s=vu(r,o);if(s!==void 0)return s||xu(n,i)}var wR=/\/|:/,bR=/^(?:[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 vR(e){return wR.test(e)&&bR.test(e)}var Vg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function xR(e){return Vg.lastIndex=0,Vg.test(e)}var kR=-(2**31),$R=2**31-1;function SR(e){return Number.isInteger(e)&&e<=$R&&e>=kR}function ER(e){return Number.isInteger(e)}function Kg(){return!0}var TR=/[^\\]\\Z/;function RR(e){if(TR.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Qg=v(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.formatLimitDefinition=void 0;var PR=yu(),tt=N(),Lt=tt.operators,Ei={formatMaximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},formatMinimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},formatExclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},formatExclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},zR={message:({keyword:e,schemaCode:t})=>(0,tt.str)`should be ${Ei[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,tt._)`{comparison: ${Ei[e].okStr}, limit: ${t}}`};Cr.formatLimitDefinition={keyword:Object.keys(Ei),type:"string",schemaType:"string",$data:!0,error:zR,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 PR.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,tt._)`${f}[${c.schemaCode}]`);e.fail$data((0,tt.or)((0,tt._)`typeof ${p} != "object"`,(0,tt._)`${p} instanceof RegExp`,(0,tt._)`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,tt._)`${s.code.formats}${(0,tt.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,tt._)`${f}.compare(${r}, ${n}) ${Ei[o].fail} 0`}},dependencies:["format"]};var OR=e=>(e.addKeyword(Cr.formatLimitDefinition),e);Cr.default=OR});var ry=v((Wn,ty)=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});var Nr=Yg(),AR=Qg(),ku=N(),Xg=new ku.Name("fullFormats"),IR=new ku.Name("fastFormats"),$u=(e,t={keywords:!0})=>{if(Array.isArray(t))return ey(e,t,Nr.fullFormats,Xg),e;let[r,n]=t.mode==="fast"?[Nr.fastFormats,IR]:[Nr.fullFormats,Xg],o=t.formats||Nr.formatNames;return ey(e,o,r,n),t.keywords&&(0,AR.default)(e),e};$u.get=(e,t="full")=>{let n=(t==="fast"?Nr.fastFormats:Nr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function ey(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ku._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}ty.exports=Wn=$u;Object.defineProperty(Wn,"__esModule",{value:!0});Wn.default=$u});var dy=v((Vq,ly)=>{ly.exports=uy;uy.sync=jR;var ay=Et("fs");function DR(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 cy(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:DR(t,r)}function uy(e,t,r){ay.stat(e,function(n,o){r(n,n?!1:cy(o,e,t))})}function jR(e,t){return cy(ay.statSync(e),e,t)}});var gy=v((Kq,hy)=>{hy.exports=py;py.sync=LR;var fy=Et("fs");function py(e,t,r){fy.stat(e,function(n,o){r(n,n?!1:my(o,t))})}function LR(e,t){return my(fy.statSync(e),t)}function my(e,t){return e.isFile()&&MR(e,t)}function MR(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 _y=v((Wq,yy)=>{var Hq=Et("fs"),Oi;process.platform==="win32"||global.TESTING_WINDOWS?Oi=dy():Oi=gy();yy.exports=Su;Su.sync=qR;function Su(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){Su(e,t||{},function(i,s){i?o(i):n(s)})})}Oi(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function qR(e,t){try{return Oi.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var Sy=v((Gq,$y)=>{var Dr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",wy=Et("path"),BR=Dr?";":":",by=_y(),vy=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),xy=(e,t)=>{let r=t.colon||BR,n=e.match(/\//)||Dr&&e.match(/\\/)?[""]:[...Dr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Dr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Dr?o.split(r):[""];return Dr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},ky=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=xy(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(vy(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=wy.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];by(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)},ZR=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=xy(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=wy.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(by.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 vy(e)};$y.exports=ky;ky.sync=ZR});var Ty=v((Jq,Eu)=>{"use strict";var Ey=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Eu.exports=Ey;Eu.exports.default=Ey});var Oy=v((Yq,zy)=>{"use strict";var Ry=Et("path"),UR=Sy(),FR=Ty();function Py(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=UR.sync(e.command,{path:r[FR({env:r})],pathExt:t?Ry.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Ry.resolve(o?e.options.cwd:"",s)),s}function VR(e){return Py(e)||Py(e,!0)}zy.exports=VR});var Ay=v((Qq,Ru)=>{"use strict";var Tu=/([()\][%!^"`<>&|;, *?])/g;function KR(e){return e=e.replace(Tu,"^$1"),e}function HR(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Tu,"^$1"),t&&(e=e.replace(Tu,"^$1")),e}Ru.exports.command=KR;Ru.exports.argument=HR});var Cy=v((Xq,Iy)=>{"use strict";Iy.exports=/^#!(.*)/});var Dy=v((eB,Ny)=>{"use strict";var WR=Cy();Ny.exports=(e="")=>{let t=e.match(WR);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Ly=v((tB,jy)=>{"use strict";var Pu=Et("fs"),GR=Dy();function JR(e){let r=Buffer.alloc(150),n;try{n=Pu.openSync(e,"r"),Pu.readSync(n,r,0,150,0),Pu.closeSync(n)}catch{}return GR(r.toString())}jy.exports=JR});var Zy=v((rB,By)=>{"use strict";var YR=Et("path"),My=Oy(),qy=Ay(),QR=Ly(),XR=process.platform==="win32",eP=/\.(?:com|exe)$/i,tP=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function rP(e){e.file=My(e);let t=e.file&&QR(e.file);return t?(e.args.unshift(e.file),e.command=t,My(e)):e.file}function nP(e){if(!XR)return e;let t=rP(e),r=!eP.test(t);if(e.options.forceShell||r){let n=tP.test(t);e.command=YR.normalize(e.command),e.command=qy.command(e.command),e.args=e.args.map(i=>qy.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 oP(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:nP(n)}By.exports=oP});var Vy=v((nB,Fy)=>{"use strict";var zu=process.platform==="win32";function Ou(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 iP(e,t){if(!zu)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Uy(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Uy(e,t){return zu&&e===1&&!t.file?Ou(t.original,"spawn"):null}function sP(e,t){return zu&&e===1&&!t.file?Ou(t.original,"spawnSync"):null}Fy.exports={hookChildProcess:iP,verifyENOENT:Uy,verifyENOENTSync:sP,notFoundError:Ou}});var Wy=v((oB,jr)=>{"use strict";var Ky=Et("child_process"),Au=Zy(),Iu=Vy();function Hy(e,t,r){let n=Au(e,t,r),o=Ky.spawn(n.command,n.args,n.options);return Iu.hookChildProcess(o,n),o}function aP(e,t,r){let n=Au(e,t,r),o=Ky.spawnSync(n.command,n.args,n.options);return o.error=o.error||Iu.verifyENOENTSync(o.status,n),o}jr.exports=Hy;jr.exports.spawn=Hy;jr.exports.sync=aP;jr.exports._parse=Au;jr.exports._enoent=Iu});import{readFile as xC,mkdir as kC,writeFile as $C}from"node:fs/promises";import{dirname as SC,join as xb}from"node:path";function ql(e){let t={app:e,version:zb(dr("__RED_BUILD_VERSION__",()=>"3.3.13")??"0.0.0-dev"),gitSha:dr("__RED_BUILD_GIT_SHA__",()=>"832f145c84843c71cf5379685dc5a58bdabcaf38")??"unknown",buildTime:dr("__RED_BUILD_TIME__",()=>"2026-08-03T02:28:27-03:00")??"unknown",bundleAsset:dr("__RED_BUNDLE_ASSET__",()=>"brain.bundle.min.mjs")??"unknown"},r=dr("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=dr("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function zb(e){return e.startsWith("v")?e.slice(1):e}function Bl(e){return`${e.app} ${e.version} ${e.gitSha}`}function dr(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var FC=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 VC=Symbol("zod_brand"),ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},yo={};function Me(e){return e&&Object.assign(yo,e),yo}var U={};Ml(U,{BIGINT_FORMAT_RANGES:()=>Ul,Class:()=>hs,NUMBER_FORMAT_RANGES:()=>ks,aborted:()=>Ut,allowsEval:()=>bs,assert:()=>Nb,assertEqual:()=>Ob,assertIs:()=>Ib,assertNever:()=>Cb,assertNotEqual:()=>Ab,assignProp:()=>ws,cached:()=>Qr,captureStackTrace:()=>wo,cleanEnum:()=>Wb,cleanRegex:()=>en,clone:()=>ot,createTransparentProxy:()=>Bb,defineLazy:()=>W,esc:()=>Zt,escapeRegex:()=>Tt,extend:()=>Fb,finalizeIssue:()=>Ge,floatSafeRemainder:()=>_s,getElementAtPath:()=>Db,getEnumValues:()=>gs,getLengthableOrigin:()=>tn,getParsedType:()=>qb,getSizableOrigin:()=>Fl,isObject:()=>fr,isPlainObject:()=>pr,issue:()=>$s,joinValues:()=>_o,jsonStringifyReplacer:()=>ys,merge:()=>Vb,normalizeParams:()=>P,nullish:()=>Xr,numKeys:()=>Mb,omit:()=>Ub,optionalKeys:()=>xs,partial:()=>Kb,pick:()=>Zb,prefixIssues:()=>it,primitiveTypes:()=>Zl,promiseAllObject:()=>jb,propertyKeyTypes:()=>vs,randomString:()=>Lb,required:()=>Hb,stringifyPrimitive:()=>bo,unwrapMessage:()=>Yr});function Ob(e){return e}function Ab(e){return e}function Ib(e){}function Cb(e){throw new Error}function Nb(e){}function gs(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 _o(e,t="|"){return e.map(r=>bo(r)).join(t)}function ys(e,t){return typeof t=="bigint"?t.toString():t}function Qr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Xr(e){return e==null}function en(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function _s(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 W(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 ws(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Db(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function jb(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 Lb(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Zt(e){return JSON.stringify(e)}var wo=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var bs=Qr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function pr(e){if(fr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(fr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Mb(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var qb=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}`)}},vs=new Set(["string","number","symbol"]),Zl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Tt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(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 Bb(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 bo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function xs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ks={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]},Ul={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Zb(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 ot(e,{...e._zod.def,shape:r,checks:[]})}function Ub(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 ot(e,{...e._zod.def,shape:r,checks:[]})}function Fb(e,t){if(!pr(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 ws(this,"shape",n),n},checks:[]};return ot(e,r)}function Vb(e,t){return ot(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ws(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Kb(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 ot(t,{...t._zod.def,shape:o,checks:[]})}function Hb(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 ot(t,{...t._zod.def,shape:o,checks:[]})}function Ut(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function it(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Yr(e){return typeof e=="string"?e:e?.message}function Ge(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Yr(e.inst?._zod.def?.error?.(e))??Yr(t?.error?.(e))??Yr(r.customError?.(e))??Yr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Fl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function tn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function $s(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Wb(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var hs=class{constructor(...t){}};var Vl=(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,ys,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},vo=y("$ZodError",Vl),Ss=y("$ZodError",Vl,{Parent:Error});function Kl(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 Hl(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 Wl=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 ht;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ge(c,i,Me())));throw wo(a,o?.callee),a}return s.value};var Gl=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=>Ge(c,i,Me())));throw wo(a,o?.callee),a}return s.value};var Es=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 ht;return i.issues.length?{success:!1,error:new(e??vo)(i.issues.map(s=>Ge(s,o,Me())))}:{success:!0,data:i.value}},rn=Es(Ss),Ts=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=>Ge(s,o,Me())))}:{success:!0,data:i.value}},xo=Ts(Ss);var Jl=/^[cC][^\s-]{8,}$/,Yl=/^[0-9a-z]+$/,Ql=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xl=/^[0-9a-vA-V]{20}$/,ed=/^[A-Za-z0-9]{27}$/,td=/^[a-zA-Z0-9_-]{21}$/,rd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var nd=/^([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})$/,Rs=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 od=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Jb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function id(){return new RegExp(Jb,"u")}var sd=/^(?:(?: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])$/,ad=/^(([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})$/,cd=/^((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])$/,ud=/^(([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])$/,ld=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ps=/^[A-Za-z0-9_-]*$/,dd=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var fd=/^\+(?:[0-9]){6,14}[0-9]$/,pd="(?:(?:\\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])))",md=new RegExp(`^${pd}$`);function hd(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 gd(e){return new RegExp(`^${hd(e)}$`)}function yd(e){let t=hd({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(`^${pd}T(?:${n})$`)}var _d=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var wd=/^\d+$/,bd=/^-?\d+(?:\.\d+)?/i,vd=/true|false/i,xd=/null/i;var kd=/^[^A-Z]*$/,$d=/^[^a-z]*$/;var ye=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sd={number:"number",bigint:"bigint",object:"date"},Os=y("$ZodCheckLessThan",(e,t)=>{ye.init(e,t);let r=Sd[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})}}),As=y("$ZodCheckGreaterThan",(e,t)=>{ye.init(e,t);let r=Sd[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})}}),Ed=y("$ZodCheckMultipleOf",(e,t)=>{ye.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):_s(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})}}),Td=y("$ZodCheckNumberFormat",(e,t)=>{ye.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=ks[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=wd)}),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 Rd=y("$ZodCheckMaxLength",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Pd=y("$ZodCheckMinLength",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),zd=y("$ZodCheckLengthEquals",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(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})}}),nn=y("$ZodCheckStringFormat",(e,t)=>{var r,n;ye.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=()=>{})}),Od=y("$ZodCheckRegex",(e,t)=>{nn.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})}}),Ad=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kd),nn.init(e,t)}),Id=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$d),nn.init(e,t)}),Cd=y("$ZodCheckIncludes",(e,t)=>{ye.init(e,t);let r=Tt(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})}}),Nd=y("$ZodCheckStartsWith",(e,t)=>{ye.init(e,t);let r=new RegExp(`^${Tt(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})}}),Dd=y("$ZodCheckEndsWith",(e,t)=>{ye.init(e,t);let r=new RegExp(`.*${Tt(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 jd=y("$ZodCheckOverwrite",(e,t)=>{ye.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var ko=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 hT={keyword:"dependencies",type:"object",schemaType:"object",error:ct.error,code(e){let[t,r]=gT(e);fg(e,t),pg(e,r)}};function gT({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 fg(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,Hn.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,Hn.checkReportMissingProp)(e,l)}):(r.if((0,Yc._)`${c} && (${(0,Hn.checkMissingProp)(e,a,i)})`),(0,Hn.reportMissingProp)(e,i),r.else())}}ct.validatePropertyDeps=fg;function pg(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,mT.alwaysValidSchema)(i,t[a])||(r.if((0,Hn.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))}ct.validateSchemaDeps=pg;ct.default=hT});var gg=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var hg=N(),yT=q(),_T={message:"property name must be valid",params:({params:e})=>(0,hg._)`{propertyName: ${e.propertyName}}`},wT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:_T,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,yT.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,hg.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Qc.default=wT});var eu=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var _i=Ue(),et=N(),bT=wt(),wi=q(),vT={message:"must NOT have additional properties",params:({params:e})=>(0,et._)`{additionalProperty: ${e.additionalProperty}}`},xT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vT,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,wi.alwaysValidSchema)(s,r))return;let l=(0,_i.allSchemaProperties)(n.properties),u=(0,_i.allSchemaProperties)(n.patternProperties);d(),e.ok((0,et._)`${i} === ${bT.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let w;if(l.length>8){let x=(0,wi.schemaRefOrVal)(s,n.properties,"properties");w=(0,_i.isOwnProperty)(t,x,_)}else l.length?w=(0,et.or)(...l.map(x=>(0,et._)`${_} === ${x}`)):w=et.nil;return u.length&&(w=(0,et.or)(w,...u.map(x=>(0,et._)`${(0,_i.usePattern)(e,x)}.test(${_})`))),(0,et.not)(w)}function p(_){t.code((0,et._)`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,wi.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,et.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,et.not)(w),()=>t.break()))}}function h(_,w,x){let k={keyword:"additionalProperties",dataProp:_,dataPropType:wi.Type.Str};x===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(k,w)}}};Xc.default=xT});var wg=v(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var kT=In(),yg=Ue(),tu=q(),_g=eu(),$T={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&&_g.default.code(new kT.KeywordCxt(i,_g.default,"additionalProperties"));let s=(0,yg.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=tu.mergeEvaluated.props(t,(0,tu.toHash)(s),i.props));let a=s.filter(d=>!(0,tu.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,yg.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)}}};ru.default=$T});var kg=v(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var bg=Ue(),bi=N(),vg=q(),xg=q(),ST={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,bg.allSchemaProperties)(r),c=a.filter(h=>(0,vg.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 bi.Name)&&(i.props=(0,xg.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,vg.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,bi._)`${(0,bg.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:xg.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,bi._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,bi.not)(u),()=>t.break())})})}}};nu.default=ST});var $g=v(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var ET=q(),TT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,ET.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"}};ou.default=TT});var Sg=v(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var RT=Ue(),PT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:RT.validateUnion,error:{message:"must match a schema in anyOf"}};iu.default=PT});var Eg=v(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var vi=N(),zT=q(),OT={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,vi._)`{passingSchemas: ${e.passing}}`},AT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:OT,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,zT.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,vi._)`${c} && ${s}`).assign(s,!1).assign(a,(0,vi._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,vi.Name)})})}}};su.default=AT});var Tg=v(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var IT=q(),CT={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,IT.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};au.default=CT});var zg=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var xi=N(),Pg=q(),NT={message:({params:e})=>(0,xi.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,xi._)`{failingKeyword: ${e.ifClause}}`},DT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:NT,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Pg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Rg(n,"then"),i=Rg(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,xi.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,xi._)`${u}`):e.setParams({ifClause:u})}}}};function Rg(e,t){let r=e.schema[t];return r!==void 0&&!(0,Pg.alwaysValidSchema)(e,r)}cu.default=DT});var Og=v(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var jT=q(),LT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,jT.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};uu.default=LT});var Ag=v(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var MT=Kc(),qT=cg(),BT=Hc(),ZT=lg(),UT=dg(),FT=mg(),VT=gg(),KT=eu(),HT=wg(),WT=kg(),GT=$g(),JT=Sg(),YT=Eg(),QT=Tg(),XT=zg(),eR=Og();function tR(e=!1){let t=[GT.default,JT.default,YT.default,QT.default,XT.default,eR.default,VT.default,KT.default,FT.default,HT.default,WT.default];return e?t.push(qT.default,ZT.default):t.push(MT.default,BT.default),t.push(UT.default),t}lu.default=tR});var Ig=v(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var se=N(),rR={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},nR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:rR,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,se._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,se._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,se._)`${h}.type || "string"`).assign(w,(0,se._)`${h}.validate`),()=>r.assign(_,(0,se._)`"string"`).assign(w,h)),e.fail$data((0,se.or)(x(),k()));function x(){return c.strictSchema===!1?se.nil:(0,se._)`${s} && !${w}`}function k(){let R=u.$async?(0,se._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,se._)`${w}(${n})`,O=(0,se._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${n}))`;return(0,se._)`${w} && ${w} !== true && ${_} === ${t} && !${O}`}}function p(){let m=d.formats[i];if(!m){x();return}if(m===!0)return;let[h,_,w]=k(m);h===t&&e.pass(R());function x(){if(c.strictSchema===!1){d.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function k(O){let $e=O instanceof RegExp?(0,se.regexpCode)(O):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(i)}`:void 0,Le=r.scopeValue("formats",{key:i,ref:O,code:$e});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,se._)`${Le}.validate`]:["string",O,Le]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,se._)`await ${w}(${n})`}return typeof _=="function"?(0,se._)`${w}(${n})`:(0,se._)`${w}.test(${n})`}}}};du.default=nR});var Cg=v(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var oR=Ig(),iR=[oR.default];fu.default=iR});var Ng=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.contentVocabulary=Or.metadataVocabulary=void 0;Or.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Or.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var jg=v(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var sR=Fh(),aR=og(),cR=Ag(),uR=Cg(),Dg=Ng(),lR=[sR.default,aR.default,(0,cR.default)(),uR.default,Dg.metadataVocabulary,Dg.contentVocabulary];pu.default=lR});var Mg=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.DiscrError=void 0;var Lg;(function(e){e.Tag="tag",e.Mapping="mapping"})(Lg||(ki.DiscrError=Lg={}))});var Bg=v(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var Ar=N(),mu=Mg(),qg=si(),dR=Cn(),fR=q(),pR={message:({params:{discrError:e,tagName:t}})=>e===mu.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Ar._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},mR={keyword:"discriminator",type:"object",schemaType:"object",error:pR,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,Ar._)`${r}${(0,Ar.getProperty)(a)}`);t.if((0,Ar._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:mu.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,Ar._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:mu.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,Ar.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let R=0;R<s.length;R++){let O=s[R];if(O?.$ref&&!(0,fR.schemaHasRulesButRef)(O,i.self.RULES)){let Le=O.$ref;if(O=qg.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Le),O instanceof qg.SchemaEnv&&(O=O.schema),O===void 0)throw new dR.default(i.opts.uriResolver,i.baseId,Le)}let $e=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof $e!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),x($e,R)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(a)}function x(R,O){if(R.const)k(R.const,O);else if(R.enum)for(let $e of R.enum)k($e,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(R,O){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[R]=O}}}};hu.default=mR});var Zg=v((Uq,hR)=>{hR.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 yu=v((te,gu)=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.MissingRefError=te.ValidationError=te.CodeGen=te.Name=te.nil=te.stringify=te.str=te._=te.KeywordCxt=te.Ajv=void 0;var gR=Lh(),yR=jg(),_R=Bg(),Ug=Zg(),wR=["/properties"],$i="http://json-schema.org/draft-07/schema",Ir=class extends gR.default{_addVocabularies(){super._addVocabularies(),yR.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(_R.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Ug,wR):Ug;this.addMetaSchema(t,$i,!1),this.refs["http://json-schema.org/schema"]=$i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($i)?$i:void 0)}};te.Ajv=Ir;gu.exports=te=Ir;gu.exports.Ajv=Ir;Object.defineProperty(te,"__esModule",{value:!0});te.default=Ir;var bR=In();Object.defineProperty(te,"KeywordCxt",{enumerable:!0,get:function(){return bR.KeywordCxt}});var Cr=N();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(te,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var vR=oi();Object.defineProperty(te,"ValidationError",{enumerable:!0,get:function(){return vR.default}});var xR=Cn();Object.defineProperty(te,"MissingRefError",{enumerable:!0,get:function(){return xR.default}})});var Yg=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatNames=lt.fastFormats=lt.fullFormats=void 0;function ut(e,t){return{validate:e,compare:t}}lt.fullFormats={date:ut(Hg,vu),time:ut(wu(!0),xu),"date-time":ut(Fg(!0),Gg),"iso-time":ut(wu(),Wg),"iso-date-time":ut(Fg(),Jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:RR,"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:NR,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:PR,int32:{type:"number",validate:AR},int64:{type:"number",validate:IR},float:{type:"number",validate:Kg},double:{type:"number",validate:Kg},password:!0,binary:!0};lt.fastFormats={...lt.fullFormats,date:ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vu),time:ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xu),"date-time":ut(/^\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,Gg),"iso-time":ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Wg),"iso-date-time":ut(/^\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,Jg),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};lt.formatNames=Object.keys(lt.fullFormats);function kR(e){return e%4===0&&(e%100!==0||e%400===0)}var $R=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,SR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Hg(e){let t=$R.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&&kR(r)?29:SR[n])}function vu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var _u=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wu(e){return function(r){let n=_u.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 xu(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 Wg(e,t){if(!(e&&t))return;let r=_u.exec(e),n=_u.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 bu=/t|\s/i;function Fg(e){let t=wu(e);return function(n){let o=n.split(bu);return o.length===2&&Hg(o[0])&&t(o[1])}}function Gg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Jg(e,t){if(!(e&&t))return;let[r,n]=e.split(bu),[o,i]=t.split(bu),s=vu(r,o);if(s!==void 0)return s||xu(n,i)}var ER=/\/|:/,TR=/^(?:[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 RR(e){return ER.test(e)&&TR.test(e)}var Vg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function PR(e){return Vg.lastIndex=0,Vg.test(e)}var zR=-(2**31),OR=2**31-1;function AR(e){return Number.isInteger(e)&&e<=OR&&e>=zR}function IR(e){return Number.isInteger(e)}function Kg(){return!0}var CR=/[^\\]\\Z/;function NR(e){if(CR.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Qg=v(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.formatLimitDefinition=void 0;var DR=yu(),tt=N(),Lt=tt.operators,Si={formatMaximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},formatMinimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},formatExclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},formatExclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},jR={message:({keyword:e,schemaCode:t})=>(0,tt.str)`should be ${Si[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,tt._)`{comparison: ${Si[e].okStr}, limit: ${t}}`};Nr.formatLimitDefinition={keyword:Object.keys(Si),type:"string",schemaType:"string",$data:!0,error:jR,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 DR.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,tt._)`${f}[${c.schemaCode}]`);e.fail$data((0,tt.or)((0,tt._)`typeof ${p} != "object"`,(0,tt._)`${p} instanceof RegExp`,(0,tt._)`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,tt._)`${s.code.formats}${(0,tt.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,tt._)`${f}.compare(${r}, ${n}) ${Si[o].fail} 0`}},dependencies:["format"]};var LR=e=>(e.addKeyword(Nr.formatLimitDefinition),e);Nr.default=LR});var ry=v((Wn,ty)=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});var Dr=Yg(),MR=Qg(),ku=N(),Xg=new ku.Name("fullFormats"),qR=new ku.Name("fastFormats"),$u=(e,t={keywords:!0})=>{if(Array.isArray(t))return ey(e,t,Dr.fullFormats,Xg),e;let[r,n]=t.mode==="fast"?[Dr.fastFormats,qR]:[Dr.fullFormats,Xg],o=t.formats||Dr.formatNames;return ey(e,o,r,n),t.keywords&&(0,MR.default)(e),e};$u.get=(e,t="full")=>{let n=(t==="fast"?Dr.fastFormats:Dr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function ey(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ku._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}ty.exports=Wn=$u;Object.defineProperty(Wn,"__esModule",{value:!0});Wn.default=$u});var dy=v((nB,ly)=>{ly.exports=uy;uy.sync=FR;var ay=Et("fs");function UR(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 cy(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:UR(t,r)}function uy(e,t,r){ay.stat(e,function(n,o){r(n,n?!1:cy(o,e,t))})}function FR(e,t){return cy(ay.statSync(e),e,t)}});var gy=v((oB,hy)=>{hy.exports=py;py.sync=VR;var fy=Et("fs");function py(e,t,r){fy.stat(e,function(n,o){r(n,n?!1:my(o,t))})}function VR(e,t){return my(fy.statSync(e),t)}function my(e,t){return e.isFile()&&KR(e,t)}function KR(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 _y=v((sB,yy)=>{var iB=Et("fs"),zi;process.platform==="win32"||global.TESTING_WINDOWS?zi=dy():zi=gy();yy.exports=Su;Su.sync=HR;function Su(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){Su(e,t||{},function(i,s){i?o(i):n(s)})})}zi(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function HR(e,t){try{return zi.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var Sy=v((aB,$y)=>{var jr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",wy=Et("path"),WR=jr?";":":",by=_y(),vy=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),xy=(e,t)=>{let r=t.colon||WR,n=e.match(/\//)||jr&&e.match(/\\/)?[""]:[...jr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=jr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=jr?o.split(r):[""];return jr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},ky=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=xy(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(vy(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=wy.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];by(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)},GR=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=xy(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=wy.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(by.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 vy(e)};$y.exports=ky;ky.sync=GR});var Ty=v((cB,Eu)=>{"use strict";var Ey=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Eu.exports=Ey;Eu.exports.default=Ey});var Oy=v((uB,zy)=>{"use strict";var Ry=Et("path"),JR=Sy(),YR=Ty();function Py(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=JR.sync(e.command,{path:r[YR({env:r})],pathExt:t?Ry.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Ry.resolve(o?e.options.cwd:"",s)),s}function QR(e){return Py(e)||Py(e,!0)}zy.exports=QR});var Ay=v((lB,Ru)=>{"use strict";var Tu=/([()\][%!^"`<>&|;, *?])/g;function XR(e){return e=e.replace(Tu,"^$1"),e}function eP(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Tu,"^$1"),t&&(e=e.replace(Tu,"^$1")),e}Ru.exports.command=XR;Ru.exports.argument=eP});var Cy=v((dB,Iy)=>{"use strict";Iy.exports=/^#!(.*)/});var Dy=v((fB,Ny)=>{"use strict";var tP=Cy();Ny.exports=(e="")=>{let t=e.match(tP);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Ly=v((pB,jy)=>{"use strict";var Pu=Et("fs"),rP=Dy();function nP(e){let r=Buffer.alloc(150),n;try{n=Pu.openSync(e,"r"),Pu.readSync(n,r,0,150,0),Pu.closeSync(n)}catch{}return rP(r.toString())}jy.exports=nP});var Zy=v((mB,By)=>{"use strict";var oP=Et("path"),My=Oy(),qy=Ay(),iP=Ly(),sP=process.platform==="win32",aP=/\.(?:com|exe)$/i,cP=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function uP(e){e.file=My(e);let t=e.file&&iP(e.file);return t?(e.args.unshift(e.file),e.command=t,My(e)):e.file}function lP(e){if(!sP)return e;let t=uP(e),r=!aP.test(t);if(e.options.forceShell||r){let n=cP.test(t);e.command=oP.normalize(e.command),e.command=qy.command(e.command),e.args=e.args.map(i=>qy.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 dP(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:lP(n)}By.exports=dP});var Vy=v((hB,Fy)=>{"use strict";var zu=process.platform==="win32";function Ou(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 fP(e,t){if(!zu)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Uy(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Uy(e,t){return zu&&e===1&&!t.file?Ou(t.original,"spawn"):null}function pP(e,t){return zu&&e===1&&!t.file?Ou(t.original,"spawnSync"):null}Fy.exports={hookChildProcess:fP,verifyENOENT:Uy,verifyENOENTSync:pP,notFoundError:Ou}});var Wy=v((gB,Lr)=>{"use strict";var Ky=Et("child_process"),Au=Zy(),Iu=Vy();function Hy(e,t,r){let n=Au(e,t,r),o=Ky.spawn(n.command,n.args,n.options);return Iu.hookChildProcess(o,n),o}function mP(e,t,r){let n=Au(e,t,r),o=Ky.spawnSync(n.command,n.args,n.options);return o.error=o.error||Iu.verifyENOENTSync(o.status,n),o}Lr.exports=Hy;Lr.exports.spawn=Hy;Lr.exports.sync=mP;Lr.exports._parse=Au;Lr.exports._enoent=Iu});import{readFile as CC,mkdir as NC,writeFile as DC}from"node:fs/promises";import{dirname as jC,join as Pb}from"node:path";function ql(e){let t={app:e,version:jb(fr("__RED_BUILD_VERSION__",()=>"3.3.17")??"0.0.0-dev"),gitSha:fr("__RED_BUILD_GIT_SHA__",()=>"0cffb69e054c45494da507f21a0f0458c55044ba")??"unknown",buildTime:fr("__RED_BUILD_TIME__",()=>"2026-08-03T04:15:01-03:00")??"unknown",bundleAsset:fr("__RED_BUNDLE_ASSET__",()=>"brain.bundle.min.mjs")??"unknown"},r=fr("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=fr("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function jb(e){return e.startsWith("v")?e.slice(1):e}function Bl(e){return`${e.app} ${e.version} ${e.gitSha}`}function fr(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var rN=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 nN=Symbol("zod_brand"),ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},go={};function Me(e){return e&&Object.assign(go,e),go}var U={};Ml(U,{BIGINT_FORMAT_RANGES:()=>Ul,Class:()=>hs,NUMBER_FORMAT_RANGES:()=>ks,aborted:()=>Ut,allowsEval:()=>bs,assert:()=>Zb,assertEqual:()=>Lb,assertIs:()=>qb,assertNever:()=>Bb,assertNotEqual:()=>Mb,assignProp:()=>ws,cached:()=>Qr,captureStackTrace:()=>_o,cleanEnum:()=>tv,cleanRegex:()=>en,clone:()=>ot,createTransparentProxy:()=>Wb,defineLazy:()=>W,esc:()=>Zt,escapeRegex:()=>Tt,extend:()=>Yb,finalizeIssue:()=>Ge,floatSafeRemainder:()=>_s,getElementAtPath:()=>Ub,getEnumValues:()=>gs,getLengthableOrigin:()=>tn,getParsedType:()=>Hb,getSizableOrigin:()=>Fl,isObject:()=>pr,isPlainObject:()=>mr,issue:()=>$s,joinValues:()=>yo,jsonStringifyReplacer:()=>ys,merge:()=>Qb,normalizeParams:()=>P,nullish:()=>Xr,numKeys:()=>Kb,omit:()=>Jb,optionalKeys:()=>xs,partial:()=>Xb,pick:()=>Gb,prefixIssues:()=>it,primitiveTypes:()=>Zl,promiseAllObject:()=>Fb,propertyKeyTypes:()=>vs,randomString:()=>Vb,required:()=>ev,stringifyPrimitive:()=>wo,unwrapMessage:()=>Yr});function Lb(e){return e}function Mb(e){return e}function qb(e){}function Bb(e){throw new Error}function Zb(e){}function gs(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 yo(e,t="|"){return e.map(r=>wo(r)).join(t)}function ys(e,t){return typeof t=="bigint"?t.toString():t}function Qr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Xr(e){return e==null}function en(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function _s(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 W(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 ws(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ub(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Fb(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 Vb(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Zt(e){return JSON.stringify(e)}var _o=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var bs=Qr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function mr(e){if(pr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(pr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Kb(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Hb=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}`)}},vs=new Set(["string","number","symbol"]),Zl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Tt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(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 Wb(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 wo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function xs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ks={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]},Ul={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Gb(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 ot(e,{...e._zod.def,shape:r,checks:[]})}function Jb(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 ot(e,{...e._zod.def,shape:r,checks:[]})}function Yb(e,t){if(!mr(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 ws(this,"shape",n),n},checks:[]};return ot(e,r)}function Qb(e,t){return ot(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ws(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Xb(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 ot(t,{...t._zod.def,shape:o,checks:[]})}function ev(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 ot(t,{...t._zod.def,shape:o,checks:[]})}function Ut(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function it(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Yr(e){return typeof e=="string"?e:e?.message}function Ge(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Yr(e.inst?._zod.def?.error?.(e))??Yr(t?.error?.(e))??Yr(r.customError?.(e))??Yr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Fl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function tn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function $s(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function tv(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var hs=class{constructor(...t){}};var Vl=(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,ys,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},bo=y("$ZodError",Vl),Ss=y("$ZodError",Vl,{Parent:Error});function Kl(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 Hl(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 Wl=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 ht;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ge(c,i,Me())));throw _o(a,o?.callee),a}return s.value};var Gl=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=>Ge(c,i,Me())));throw _o(a,o?.callee),a}return s.value};var Es=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 ht;return i.issues.length?{success:!1,error:new(e??bo)(i.issues.map(s=>Ge(s,o,Me())))}:{success:!0,data:i.value}},rn=Es(Ss),Ts=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=>Ge(s,o,Me())))}:{success:!0,data:i.value}},vo=Ts(Ss);var Jl=/^[cC][^\s-]{8,}$/,Yl=/^[0-9a-z]+$/,Ql=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xl=/^[0-9a-vA-V]{20}$/,ed=/^[A-Za-z0-9]{27}$/,td=/^[a-zA-Z0-9_-]{21}$/,rd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var nd=/^([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})$/,Rs=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 od=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var nv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function id(){return new RegExp(nv,"u")}var sd=/^(?:(?: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])$/,ad=/^(([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})$/,cd=/^((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])$/,ud=/^(([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])$/,ld=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ps=/^[A-Za-z0-9_-]*$/,dd=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var fd=/^\+(?:[0-9]){6,14}[0-9]$/,pd="(?:(?:\\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])))",md=new RegExp(`^${pd}$`);function hd(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 gd(e){return new RegExp(`^${hd(e)}$`)}function yd(e){let t=hd({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(`^${pd}T(?:${n})$`)}var _d=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var wd=/^\d+$/,bd=/^-?\d+(?:\.\d+)?/i,vd=/true|false/i,xd=/null/i;var kd=/^[^A-Z]*$/,$d=/^[^a-z]*$/;var ye=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sd={number:"number",bigint:"bigint",object:"date"},Os=y("$ZodCheckLessThan",(e,t)=>{ye.init(e,t);let r=Sd[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})}}),As=y("$ZodCheckGreaterThan",(e,t)=>{ye.init(e,t);let r=Sd[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})}}),Ed=y("$ZodCheckMultipleOf",(e,t)=>{ye.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):_s(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})}}),Td=y("$ZodCheckNumberFormat",(e,t)=>{ye.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=ks[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=wd)}),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 Rd=y("$ZodCheckMaxLength",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Pd=y("$ZodCheckMinLength",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),zd=y("$ZodCheckLengthEquals",(e,t)=>{var r;ye.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Xr(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=tn(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})}}),nn=y("$ZodCheckStringFormat",(e,t)=>{var r,n;ye.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=()=>{})}),Od=y("$ZodCheckRegex",(e,t)=>{nn.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})}}),Ad=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kd),nn.init(e,t)}),Id=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$d),nn.init(e,t)}),Cd=y("$ZodCheckIncludes",(e,t)=>{ye.init(e,t);let r=Tt(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})}}),Nd=y("$ZodCheckStartsWith",(e,t)=>{ye.init(e,t);let r=new RegExp(`^${Tt(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})}}),Dd=y("$ZodCheckEndsWith",(e,t)=>{ye.init(e,t);let r=new RegExp(`.*${Tt(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 jd=y("$ZodCheckOverwrite",(e,t)=>{ye.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var xo=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 Md={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Md;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=Ut(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 ht;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Ut(i,d)))});else{if(i.issues.length===d)continue;c||(c=Ut(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 ht;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=rn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return
|
|
12
|
+
`))}};var Md={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Md;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=Ut(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 ht;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Ut(i,d)))});else{if(i.issues.length===d)continue;c||(c=Ut(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 ht;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=rn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return vo(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),$o=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??_d(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)=>{nn.init(e,t),$o.init(e,t)}),Gd=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=nd),Q.init(e,t)}),Jd=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=Rs(n))}else t.pattern??(t.pattern=Rs());Q.init(e,t)}),Yd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=od),Q.init(e,t)}),Qd=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:dd.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})}}}),Xd=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=id()),Q.init(e,t)}),ef=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=td),Q.init(e,t)}),tf=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Jl),Q.init(e,t)}),rf=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yl),Q.init(e,t)}),nf=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ql),Q.init(e,t)}),of=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xl),Q.init(e,t)}),sf=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ed),Q.init(e,t)}),af=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=yd(t)),Q.init(e,t)}),cf=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=md),Q.init(e,t)}),uf=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gd(t)),Q.init(e,t)}),lf=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=rd),Q.init(e,t)}),df=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=sd),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ff=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ad),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})}}}),pf=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cd),Q.init(e,t)}),mf=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ud),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 hf(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var gf=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ld),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{hf(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ov(e){if(!Ps.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return hf(r)}var yf=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ps),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ov(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),_f=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fd),Q.init(e,t)});function iv(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 wf=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{iv(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Cs=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??bd,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}}),bf=y("$ZodNumber",(e,t)=>{Td.init(e,t),Cs.init(e,t)}),vf=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=vd,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 xf=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=xd,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 kf=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),$f=y("$ZodNever",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function qd(e,t,r){e.issues.length&&t.issues.push(...it(r,e.issues)),t.value[r]=e.value}var Sf=y("$ZodArray",(e,t)=>{G.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=>qd(l,r,s))):qd(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function ko(e,t,r){e.issues.length&&t.issues.push(...it(r,e.issues)),t.value[r]=e.value}function Bd(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(...it(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Ef=y("$ZodObject",(e,t)=>{G.init(e,t);let r=Qr(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof G))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=xs(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});W(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 xo(["shape","payload","ctx"]),p=r.value,m=x=>{let k=Zt(x);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let x of p.keys)h[x]=`key_${_++}`;f.write("const newResult = {}");for(let x of p.keys)if(p.optionalKeys.has(x)){let k=h[x];f.write(`const ${k} = ${m(x)};`);let R=Zt(x);f.write(`
|
|
13
13
|
if (${k}.issues.length) {
|
|
14
14
|
if (input[${R}] === undefined) {
|
|
15
15
|
if (${R} in input) {
|
|
@@ -32,19 +32,19 @@ var $b=Object.create;var fs=Object.defineProperty;var Sb=Object.getOwnPropertyDe
|
|
|
32
32
|
if (${k}.issues.length) payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
33
33
|
...iss,
|
|
34
34
|
path: iss.path ? [${Zt(x)}, ...iss.path] : [${Zt(x)}]
|
|
35
|
-
})));`),f.write(`newResult[${Zt(x)}] = ${k}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(x,k)=>w(d,x,k)},o,i=fr,s=!yo.jitless,c=s&&bs.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 k=u.shape;for(let R of u.keys){let O=k[R],$e=O._zod.run({value:p[R],issues:[]},f),Le=O._zod.optin==="optional"&&O._zod.optout==="optional";$e instanceof Promise?m.push($e.then(lr=>Le?Bd(lr,d,R,p):$o(lr,d,R))):Le?Bd($e,d,R,p):$o($e,d,R)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,x=w.def.type;for(let k of Object.keys(p)){if(_.has(k))continue;if(x==="never"){h.push(k);continue}let R=w.run({value:p[k],issues:[]},f);R instanceof Promise?m.push(R.then(O=>$o(O,d,k))):$o(R,d,k)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function Zd(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=>Ge(i,n,Me())))}),t}var Ns=y("$ZodUnion",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),W(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),W(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),W(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=>en(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=>Zd(s,r,e,n)):Zd(i,r,e,n)}}),Tf=y("$ZodDiscriminatedUnion",(e,t)=>{Ns.init(e,t);let r=e._zod.parse;W(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=Qr(()=>{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(!fr(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)}}),Rf=y("$ZodIntersection",(e,t)=>{G.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])=>Ud(r,c,l)):Ud(r,i,s)}});function Is(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(pr(e)&&pr(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=Is(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=Is(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 Ud(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ut(e))return e;let n=Is(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 Pf=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!pr(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(...it(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...it(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=>Ge(l,n,Me())),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(...it(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...it(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var zf=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=gs(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>vs.has(typeof n)).map(n=>typeof n=="string"?Tt(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}}),Of=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Tt(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 Af=y("$ZodTransform",(e,t)=>{G.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 ht;return r.value=o,r}}),If=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",W(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${en(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)}),Cf=y("$ZodNullable",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.innerType._zod.optin),W(e._zod,"optout",()=>t.innerType._zod.optout),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${en(r.source)}|null)$`):void 0}),W(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)}),Nf=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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=>Fd(i,t)):Fd(o,t)}});function Fd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Df=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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))}),jf=y("$ZodNonOptional",(e,t)=>{G.init(e,t),W(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=>Vd(i,e)):Vd(o,e)}});function Vd(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 Lf=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(e._zod,"optout",()=>t.innerType._zod.optout),W(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=>Ge(s,n,Me()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ge(i,n,Me()))},input:r.value}),r.issues=[]),r)}});var Mf=y("$ZodPipe",(e,t)=>{G.init(e,t),W(e._zod,"values",()=>t.in._zod.values),W(e._zod,"optin",()=>t.in._zod.optin),W(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=>Kd(i,t,n)):Kd(o,t,n)}});function Kd(e,t,r){return Ut(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var qf=y("$ZodReadonly",(e,t)=>{G.init(e,t),W(e._zod,"propValues",()=>t.innerType._zod.propValues),W(e._zod,"values",()=>t.innerType._zod.values),W(e._zod,"optin",()=>t.innerType._zod.optin),W(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(Hd):Hd(o)}});function Hd(e){return e.value=Object.freeze(e.value),e}var Bf=y("$ZodCustom",(e,t)=>{ye.init(e,t),G.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=>Wd(i,r,n,e));Wd(o,r,n,e)}});function Wd(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($s(o))}}var Xb=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},ev=()=>{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 ${Xb(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${bo(n.values[0])}`:`Invalid option: expected one of ${_o(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":""}: ${_o(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 Zf(){return{localeError:ev()}}var iN=Symbol("ZodOutput"),sN=Symbol("ZodInput"),Ds=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 tv(){return new Ds}var on=tv();function Uf(e,t){return new e({type:"string",...P(t)})}function Ff(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function js(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function Vf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function Kf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function Hf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function Wf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Gf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Jf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Yf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Qf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Xf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function ep(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function tp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function rp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function np(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function op(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function ip(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function sp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function ap(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function cp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function up(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function lp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function dp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function fp(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function pp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function mp(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function hp(e,t){return new e({type:"number",checks:[],...P(t)})}function gp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function yp(e,t){return new e({type:"boolean",...P(t)})}function _p(e,t){return new e({type:"null",...P(t)})}function wp(e){return new e({type:"unknown"})}function bp(e,t){return new e({type:"never",...P(t)})}function Eo(e,t){return new Os({check:"less_than",...P(t),value:e,inclusive:!1})}function sn(e,t){return new Os({check:"less_than",...P(t),value:e,inclusive:!0})}function To(e,t){return new As({check:"greater_than",...P(t),value:e,inclusive:!1})}function an(e,t){return new As({check:"greater_than",...P(t),value:e,inclusive:!0})}function Ro(e,t){return new Ed({check:"multiple_of",...P(t),value:e})}function Po(e,t){return new Rd({check:"max_length",...P(t),maximum:e})}function mr(e,t){return new Pd({check:"min_length",...P(t),minimum:e})}function zo(e,t){return new zd({check:"length_equals",...P(t),length:e})}function Ls(e,t){return new Od({check:"string_format",format:"regex",...P(t),pattern:e})}function Ms(e){return new Ad({check:"string_format",format:"lowercase",...P(e)})}function qs(e){return new Id({check:"string_format",format:"uppercase",...P(e)})}function Bs(e,t){return new Cd({check:"string_format",format:"includes",...P(t),includes:e})}function Zs(e,t){return new Nd({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Us(e,t){return new Dd({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Ft(e){return new jd({check:"overwrite",tx:e})}function Fs(e){return Ft(t=>t.normalize(e))}function Vs(){return Ft(e=>e.trim())}function Ks(){return Ft(e=>e.toLowerCase())}function Hs(){return Ft(e=>e.toUpperCase())}function vp(e,t,r){return new e({type:"array",element:t,...P(r)})}function xp(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function kp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function hr(e){return!!e._zod}function Je(e,t){return hr(e)?rn(e,t):e.safeParse(t)}function Oo(e){if(!e)return;let t;if(hr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $p(e){if(hr(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 un={};Ml(un,{ZodISODate:()=>Ep,ZodISODateTime:()=>Sp,ZodISODuration:()=>Rp,ZodISOTime:()=>Tp,date:()=>Gs,datetime:()=>Ws,duration:()=>Ys,time:()=>Js});var Sp=y("ZodISODateTime",(e,t)=>{af.init(e,t),re.init(e,t)});function Ws(e){return dp(Sp,e)}var Ep=y("ZodISODate",(e,t)=>{cf.init(e,t),re.init(e,t)});function Gs(e){return fp(Ep,e)}var Tp=y("ZodISOTime",(e,t)=>{uf.init(e,t),re.init(e,t)});function Js(e){return pp(Tp,e)}var Rp=y("ZodISODuration",(e,t)=>{lf.init(e,t),re.init(e,t)});function Ys(e){return mp(Rp,e)}var Pp=(e,t)=>{vo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Hl(e,r)},flatten:{value:r=>Kl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},qN=y("ZodError",Pp),ln=y("ZodError",Pp,{Parent:Error});var zp=Wl(ln),Op=Gl(ln),Ap=Es(ln),Ip=Ts(ln);var ie=y("ZodType",(e,t)=>(G.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)=>ot(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>zp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ap(e,r,n),e.parseAsync=async(r,n)=>Op(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ip(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Qv(r,n)),e.superRefine=r=>e.check(Xv(r)),e.overwrite=r=>e.check(Ft(r)),e.optional=()=>oe(e),e.nullable=()=>Dp(e),e.nullish=()=>oe(Dp(e)),e.nonoptional=r=>Vv(e,r),e.array=()=>L(e),e.or=r=>X([e,r]),e.and=r=>Io(e,r),e.transform=r=>Xs(e,Zp(r)),e.default=r=>Zv(e,r),e.prefault=r=>Fv(e,r),e.catch=r=>Hv(e,r),e.pipe=r=>Xs(e,r),e.readonly=()=>Jv(e),e.describe=r=>{let n=e.clone();return on.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return on.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return on.get(e);let n=e.clone();return on.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),jp=y("_ZodString",(e,t)=>{So.init(e,t),ie.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(Ls(...n)),e.includes=(...n)=>e.check(Bs(...n)),e.startsWith=(...n)=>e.check(Zs(...n)),e.endsWith=(...n)=>e.check(Us(...n)),e.min=(...n)=>e.check(mr(...n)),e.max=(...n)=>e.check(Po(...n)),e.length=(...n)=>e.check(zo(...n)),e.nonempty=(...n)=>e.check(mr(1,...n)),e.lowercase=n=>e.check(Ms(n)),e.uppercase=n=>e.check(qs(n)),e.trim=()=>e.check(Vs()),e.normalize=(...n)=>e.check(Fs(...n)),e.toLowerCase=()=>e.check(Ks()),e.toUpperCase=()=>e.check(Hs())}),lv=y("ZodString",(e,t)=>{So.init(e,t),jp.init(e,t),e.email=r=>e.check(Ff(dv,r)),e.url=r=>e.check(Gf(fv,r)),e.jwt=r=>e.check(lp(Tv,r)),e.emoji=r=>e.check(Jf(pv,r)),e.guid=r=>e.check(js(Cp,r)),e.uuid=r=>e.check(Vf(Ao,r)),e.uuidv4=r=>e.check(Kf(Ao,r)),e.uuidv6=r=>e.check(Hf(Ao,r)),e.uuidv7=r=>e.check(Wf(Ao,r)),e.nanoid=r=>e.check(Yf(mv,r)),e.guid=r=>e.check(js(Cp,r)),e.cuid=r=>e.check(Qf(hv,r)),e.cuid2=r=>e.check(Xf(gv,r)),e.ulid=r=>e.check(ep(yv,r)),e.base64=r=>e.check(ap($v,r)),e.base64url=r=>e.check(cp(Sv,r)),e.xid=r=>e.check(tp(_v,r)),e.ksuid=r=>e.check(rp(wv,r)),e.ipv4=r=>e.check(np(bv,r)),e.ipv6=r=>e.check(op(vv,r)),e.cidrv4=r=>e.check(ip(xv,r)),e.cidrv6=r=>e.check(sp(kv,r)),e.e164=r=>e.check(up(Ev,r)),e.datetime=r=>e.check(Ws(r)),e.date=r=>e.check(Gs(r)),e.time=r=>e.check(Js(r)),e.duration=r=>e.check(Ys(r))});function g(e){return Uf(lv,e)}var re=y("ZodStringFormat",(e,t)=>{Q.init(e,t),jp.init(e,t)}),dv=y("ZodEmail",(e,t)=>{Yd.init(e,t),re.init(e,t)});var Cp=y("ZodGUID",(e,t)=>{Gd.init(e,t),re.init(e,t)});var Ao=y("ZodUUID",(e,t)=>{Jd.init(e,t),re.init(e,t)});var fv=y("ZodURL",(e,t)=>{Qd.init(e,t),re.init(e,t)});var pv=y("ZodEmoji",(e,t)=>{Xd.init(e,t),re.init(e,t)});var mv=y("ZodNanoID",(e,t)=>{ef.init(e,t),re.init(e,t)});var hv=y("ZodCUID",(e,t)=>{tf.init(e,t),re.init(e,t)});var gv=y("ZodCUID2",(e,t)=>{rf.init(e,t),re.init(e,t)});var yv=y("ZodULID",(e,t)=>{nf.init(e,t),re.init(e,t)});var _v=y("ZodXID",(e,t)=>{of.init(e,t),re.init(e,t)});var wv=y("ZodKSUID",(e,t)=>{sf.init(e,t),re.init(e,t)});var bv=y("ZodIPv4",(e,t)=>{df.init(e,t),re.init(e,t)});var vv=y("ZodIPv6",(e,t)=>{ff.init(e,t),re.init(e,t)});var xv=y("ZodCIDRv4",(e,t)=>{pf.init(e,t),re.init(e,t)});var kv=y("ZodCIDRv6",(e,t)=>{mf.init(e,t),re.init(e,t)});var $v=y("ZodBase64",(e,t)=>{gf.init(e,t),re.init(e,t)});var Sv=y("ZodBase64URL",(e,t)=>{yf.init(e,t),re.init(e,t)});var Ev=y("ZodE164",(e,t)=>{_f.init(e,t),re.init(e,t)});var Tv=y("ZodJWT",(e,t)=>{wf.init(e,t),re.init(e,t)});var Lp=y("ZodNumber",(e,t)=>{Cs.init(e,t),ie.init(e,t),e.gt=(n,o)=>e.check(To(n,o)),e.gte=(n,o)=>e.check(an(n,o)),e.min=(n,o)=>e.check(an(n,o)),e.lt=(n,o)=>e.check(Eo(n,o)),e.lte=(n,o)=>e.check(sn(n,o)),e.max=(n,o)=>e.check(sn(n,o)),e.int=n=>e.check(Np(n)),e.safe=n=>e.check(Np(n)),e.positive=n=>e.check(To(0,n)),e.nonnegative=n=>e.check(an(0,n)),e.negative=n=>e.check(Eo(0,n)),e.nonpositive=n=>e.check(sn(0,n)),e.multipleOf=(n,o)=>e.check(Ro(n,o)),e.step=(n,o)=>e.check(Ro(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 hp(Lp,e)}var Rv=y("ZodNumberFormat",(e,t)=>{bf.init(e,t),Lp.init(e,t)});function Np(e){return gp(Rv,e)}var Pv=y("ZodBoolean",(e,t)=>{vf.init(e,t),ie.init(e,t)});function le(e){return yp(Pv,e)}var zv=y("ZodNull",(e,t)=>{xf.init(e,t),ie.init(e,t)});function Mp(e){return _p(zv,e)}var Ov=y("ZodUnknown",(e,t)=>{kf.init(e,t),ie.init(e,t)});function ne(){return wp(Ov)}var Av=y("ZodNever",(e,t)=>{$f.init(e,t),ie.init(e,t)});function Iv(e){return bp(Av,e)}var Cv=y("ZodArray",(e,t)=>{Sf.init(e,t),ie.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(mr(r,n)),e.nonempty=r=>e.check(mr(1,r)),e.max=(r,n)=>e.check(Po(r,n)),e.length=(r,n)=>e.check(zo(r,n)),e.unwrap=()=>e.element});function L(e,t){return vp(Cv,e,t)}var qp=y("ZodObject",(e,t)=>{Ef.init(e,t),ie.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ze(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ne()}),e.loose=()=>e.clone({...e._zod.def,catchall:ne()}),e.strict=()=>e.clone({...e._zod.def,catchall:Iv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>U.extend(e,r),e.merge=r=>U.merge(e,r),e.pick=r=>U.pick(e,r),e.omit=r=>U.omit(e,r),e.partial=(...r)=>U.partial(Up,e,r[0]),e.required=(...r)=>U.required(Fp,e,r[0])});function $(e,t){let r={type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},...U.normalizeParams(t)};return new qp(r)}function Se(e,t){return new qp({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:ne(),...U.normalizeParams(t)})}var Bp=y("ZodUnion",(e,t)=>{Ns.init(e,t),ie.init(e,t),e.options=t.options});function X(e,t){return new Bp({type:"union",options:e,...U.normalizeParams(t)})}var Nv=y("ZodDiscriminatedUnion",(e,t)=>{Bp.init(e,t),Tf.init(e,t)});function ea(e,t,r){return new Nv({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Dv=y("ZodIntersection",(e,t)=>{Rf.init(e,t),ie.init(e,t)});function Io(e,t){return new Dv({type:"intersection",left:e,right:t})}var jv=y("ZodRecord",(e,t)=>{Pf.init(e,t),ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new jv({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var Qs=y("ZodEnum",(e,t)=>{zf.init(e,t),ie.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 Qs({...t,checks:[],...U.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 Qs({...t,checks:[],...U.normalizeParams(o),entries:i})}});function ze(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Qs({type:"enum",entries:r,...U.normalizeParams(t)})}var Lv=y("ZodLiteral",(e,t)=>{Of.init(e,t),ie.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 S(e,t){return new Lv({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var Mv=y("ZodTransform",(e,t)=>{Af.init(e,t),ie.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(U.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(U.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 Zp(e){return new Mv({type:"transform",transform:e})}var Up=y("ZodOptional",(e,t)=>{If.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function oe(e){return new Up({type:"optional",innerType:e})}var qv=y("ZodNullable",(e,t)=>{Cf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Dp(e){return new qv({type:"nullable",innerType:e})}var Bv=y("ZodDefault",(e,t)=>{Nf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zv(e,t){return new Bv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Uv=y("ZodPrefault",(e,t)=>{Df.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Fv(e,t){return new Uv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Fp=y("ZodNonOptional",(e,t)=>{jf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vv(e,t){return new Fp({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var Kv=y("ZodCatch",(e,t)=>{Lf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Hv(e,t){return new Kv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Wv=y("ZodPipe",(e,t)=>{Mf.init(e,t),ie.init(e,t),e.in=t.in,e.out=t.out});function Xs(e,t){return new Wv({type:"pipe",in:e,out:t})}var Gv=y("ZodReadonly",(e,t)=>{qf.init(e,t),ie.init(e,t)});function Jv(e){return new Gv({type:"readonly",innerType:e})}var Vp=y("ZodCustom",(e,t)=>{Bf.init(e,t),ie.init(e,t)});function Yv(e){let t=new ye({check:"custom"});return t._zod.check=e,t}function Kp(e,t){return xp(Vp,e??(()=>!0),t)}function Qv(e,t={}){return kp(Vp,e,t)}function Xv(e){let t=Yv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(U.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(U.issue(o))}},e(r.value,r)));return t}function ta(e,t){return Xs(Zp(e),t)}Me(Zf());var na="2025-11-25";var Hp=[na,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rt="io.modelcontextprotocol/related-task",No="2.0",ce=Kp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Wp=X([g(),V().int()]),Gp=g(),I1=Se({ttl:V().optional(),pollInterval:V().optional()}),ex=$({ttl:V().optional()}),tx=$({taskId:g()}),oa=Se({progressToken:Wp.optional(),[Rt]:tx.optional()}),Ne=$({_meta:oa.optional()}),dn=Ne.extend({task:ex.optional()}),Jp=e=>dn.safeParse(e).success,de=$({method:g(),params:Ne.loose().optional()}),qe=$({_meta:oa.optional()}),Be=$({method:g(),params:qe.loose().optional()}),fe=Se({_meta:oa.optional()}),Do=X([g(),V().int()]),Yp=$({jsonrpc:S(No),id:Do,...de.shape}).strict(),ia=e=>Yp.safeParse(e).success,Qp=$({jsonrpc:S(No),...Be.shape}).strict(),Xp=e=>Qp.safeParse(e).success,sa=$({jsonrpc:S(No),id:Do,result:fe}).strict(),fn=e=>sa.safeParse(e).success;var A;(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"})(A||(A={}));var aa=$({jsonrpc:S(No),id:Do.optional(),error:$({code:V().int(),message:g(),data:ne().optional()})}).strict();var em=e=>aa.safeParse(e).success;var tm=X([Yp,Qp,sa,aa]),C1=X([sa,aa]),Vt=fe.strict(),rx=qe.extend({requestId:Do.optional(),reason:g().optional()}),jo=Be.extend({method:S("notifications/cancelled"),params:rx}),nx=$({src:g(),mimeType:g().optional(),sizes:L(g()).optional(),theme:ze(["light","dark"]).optional()}),pn=$({icons:L(nx).optional()}),gr=$({name:g(),title:g().optional()}),rm=gr.extend({...gr.shape,...pn.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),ox=Io($({applyDefaults:le().optional()}),J(g(),ne())),ix=ta(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Io($({form:ox.optional(),url:ce.optional()}),J(g(),ne()).optional())),sx=Se({list:ce.optional(),cancel:ce.optional(),requests:Se({sampling:Se({createMessage:ce.optional()}).optional(),elicitation:Se({create:ce.optional()}).optional()}).optional()}),ax=Se({list:ce.optional(),cancel:ce.optional(),requests:Se({tools:Se({call:ce.optional()}).optional()}).optional()}),cx=$({experimental:J(g(),ce).optional(),sampling:$({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:ix.optional(),roots:$({listChanged:le().optional()}).optional(),tasks:sx.optional(),extensions:J(g(),ce).optional()}),ux=Ne.extend({protocolVersion:g(),capabilities:cx,clientInfo:rm}),lx=de.extend({method:S("initialize"),params:ux});var dx=$({experimental:J(g(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:$({listChanged:le().optional()}).optional(),resources:$({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:$({listChanged:le().optional()}).optional(),tasks:ax.optional(),extensions:J(g(),ce).optional()}),ca=fe.extend({protocolVersion:g(),capabilities:dx,serverInfo:rm,instructions:g().optional()}),fx=Be.extend({method:S("notifications/initialized"),params:qe.optional()});var Lo=de.extend({method:S("ping"),params:Ne.optional()}),px=$({progress:V(),total:oe(V()),message:oe(g())}),mx=$({...qe.shape,...px.shape,progressToken:Wp}),Mo=Be.extend({method:S("notifications/progress"),params:mx}),hx=Ne.extend({cursor:Gp.optional()}),mn=de.extend({params:hx.optional()}),hn=fe.extend({nextCursor:Gp.optional()}),gx=ze(["working","input_required","completed","failed","cancelled"]),gn=$({taskId:g(),status:gx,ttl:X([V(),Mp()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:oe(V()),statusMessage:oe(g())}),Kt=fe.extend({task:gn}),yx=qe.merge(gn),yn=Be.extend({method:S("notifications/tasks/status"),params:yx}),qo=de.extend({method:S("tasks/get"),params:Ne.extend({taskId:g()})}),Bo=fe.merge(gn),Zo=de.extend({method:S("tasks/result"),params:Ne.extend({taskId:g()})}),N1=fe.loose(),Uo=mn.extend({method:S("tasks/list")}),Fo=hn.extend({tasks:L(gn)}),Vo=de.extend({method:S("tasks/cancel"),params:Ne.extend({taskId:g()})}),nm=fe.merge(gn),om=$({uri:g(),mimeType:oe(g()),_meta:J(g(),ne()).optional()}),im=om.extend({text:g()}),ua=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),sm=om.extend({blob:ua}),_n=ze(["user","assistant"]),yr=$({audience:L(_n).optional(),priority:V().min(0).max(1).optional(),lastModified:un.datetime({offset:!0}).optional()}),am=$({...gr.shape,...pn.shape,uri:g(),description:oe(g()),mimeType:oe(g()),size:oe(V()),annotations:yr.optional(),_meta:oe(Se({}))}),_x=$({...gr.shape,...pn.shape,uriTemplate:g(),description:oe(g()),mimeType:oe(g()),annotations:yr.optional(),_meta:oe(Se({}))}),wx=mn.extend({method:S("resources/list")}),la=hn.extend({resources:L(am)}),bx=mn.extend({method:S("resources/templates/list")}),da=hn.extend({resourceTemplates:L(_x)}),fa=Ne.extend({uri:g()}),vx=fa,xx=de.extend({method:S("resources/read"),params:vx}),pa=fe.extend({contents:L(X([im,sm]))}),ma=Be.extend({method:S("notifications/resources/list_changed"),params:qe.optional()}),kx=fa,$x=de.extend({method:S("resources/subscribe"),params:kx}),Sx=fa,Ex=de.extend({method:S("resources/unsubscribe"),params:Sx}),Tx=qe.extend({uri:g()}),Rx=Be.extend({method:S("notifications/resources/updated"),params:Tx}),Px=$({name:g(),description:oe(g()),required:oe(le())}),zx=$({...gr.shape,...pn.shape,description:oe(g()),arguments:oe(L(Px)),_meta:oe(Se({}))}),Ox=mn.extend({method:S("prompts/list")}),ha=hn.extend({prompts:L(zx)}),Ax=Ne.extend({name:g(),arguments:J(g(),g()).optional()}),Ix=de.extend({method:S("prompts/get"),params:Ax}),ga=$({type:S("text"),text:g(),annotations:yr.optional(),_meta:J(g(),ne()).optional()}),ya=$({type:S("image"),data:ua,mimeType:g(),annotations:yr.optional(),_meta:J(g(),ne()).optional()}),_a=$({type:S("audio"),data:ua,mimeType:g(),annotations:yr.optional(),_meta:J(g(),ne()).optional()}),Cx=$({type:S("tool_use"),name:g(),id:g(),input:J(g(),ne()),_meta:J(g(),ne()).optional()}),Nx=$({type:S("resource"),resource:X([im,sm]),annotations:yr.optional(),_meta:J(g(),ne()).optional()}),Dx=am.extend({type:S("resource_link")}),wa=X([ga,ya,_a,Dx,Nx]),jx=$({role:_n,content:wa}),ba=fe.extend({description:g().optional(),messages:L(jx)}),va=Be.extend({method:S("notifications/prompts/list_changed"),params:qe.optional()}),Lx=$({title:g().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),Mx=$({taskSupport:ze(["required","optional","forbidden"]).optional()}),cm=$({...gr.shape,...pn.shape,description:g().optional(),inputSchema:$({type:S("object"),properties:J(g(),ce).optional(),required:L(g()).optional()}).catchall(ne()),outputSchema:$({type:S("object"),properties:J(g(),ce).optional(),required:L(g()).optional()}).catchall(ne()).optional(),annotations:Lx.optional(),execution:Mx.optional(),_meta:J(g(),ne()).optional()}),qx=mn.extend({method:S("tools/list")}),xa=hn.extend({tools:L(cm)}),Pt=fe.extend({content:L(wa).default([]),structuredContent:J(g(),ne()).optional(),isError:le().optional()}),D1=Pt.or(fe.extend({toolResult:ne()})),Bx=dn.extend({name:g(),arguments:J(g(),ne()).optional()}),Zx=de.extend({method:S("tools/call"),params:Bx}),ka=Be.extend({method:S("notifications/tools/list_changed"),params:qe.optional()}),um=$({autoRefresh:le().default(!0),debounceMs:V().int().nonnegative().default(300)}),lm=ze(["debug","info","notice","warning","error","critical","alert","emergency"]),Ux=Ne.extend({level:lm}),Fx=de.extend({method:S("logging/setLevel"),params:Ux}),Vx=qe.extend({level:lm,logger:g().optional(),data:ne()}),Kx=Be.extend({method:S("notifications/message"),params:Vx}),Hx=$({name:g().optional()}),Wx=$({hints:L(Hx).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),Gx=$({mode:ze(["auto","required","none"]).optional()}),Jx=$({type:S("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:L(wa).default([]),structuredContent:$({}).loose().optional(),isError:le().optional(),_meta:J(g(),ne()).optional()}),Yx=ea("type",[ga,ya,_a]),Co=ea("type",[ga,ya,_a,Cx,Jx]),Qx=$({role:_n,content:X([Co,L(Co)]),_meta:J(g(),ne()).optional()}),Xx=dn.extend({messages:L(Qx),modelPreferences:Wx.optional(),systemPrompt:g().optional(),includeContext:ze(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:L(g()).optional(),metadata:ce.optional(),tools:L(cm).optional(),toolChoice:Gx.optional()}),$a=de.extend({method:S("sampling/createMessage"),params:Xx}),Sa=fe.extend({model:g(),stopReason:oe(ze(["endTurn","stopSequence","maxTokens"]).or(g())),role:_n,content:Yx}),Ea=fe.extend({model:g(),stopReason:oe(ze(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:_n,content:X([Co,L(Co)])}),e0=$({type:S("boolean"),title:g().optional(),description:g().optional(),default:le().optional()}),t0=$({type:S("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:ze(["email","uri","date","date-time"]).optional(),default:g().optional()}),r0=$({type:ze(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),n0=$({type:S("string"),title:g().optional(),description:g().optional(),enum:L(g()),default:g().optional()}),o0=$({type:S("string"),title:g().optional(),description:g().optional(),oneOf:L($({const:g(),title:g()})),default:g().optional()}),i0=$({type:S("string"),title:g().optional(),description:g().optional(),enum:L(g()),enumNames:L(g()).optional(),default:g().optional()}),s0=X([n0,o0]),a0=$({type:S("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:S("string"),enum:L(g())}),default:L(g()).optional()}),c0=$({type:S("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:L($({const:g(),title:g()}))}),default:L(g()).optional()}),u0=X([a0,c0]),l0=X([i0,s0,u0]),d0=X([l0,e0,t0,r0]),f0=dn.extend({mode:S("form").optional(),message:g(),requestedSchema:$({type:S("object"),properties:J(g(),d0),required:L(g()).optional()})}),p0=dn.extend({mode:S("url"),message:g(),elicitationId:g(),url:g().url()}),m0=X([f0,p0]),Ta=de.extend({method:S("elicitation/create"),params:m0}),h0=qe.extend({elicitationId:g()}),g0=Be.extend({method:S("notifications/elicitation/complete"),params:h0}),Ra=fe.extend({action:ze(["accept","decline","cancel"]),content:ta(e=>e===null?void 0:e,J(g(),X([g(),V(),le(),L(g())])).optional())}),y0=$({type:S("ref/resource"),uri:g()});var _0=$({type:S("ref/prompt"),name:g()}),w0=Ne.extend({ref:X([_0,y0]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),b0=de.extend({method:S("completion/complete"),params:w0});var Pa=fe.extend({completion:Se({values:L(g()).max(100),total:oe(V().int()),hasMore:oe(le())})}),v0=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),ne()).optional()}),x0=de.extend({method:S("roots/list"),params:Ne.optional()}),k0=fe.extend({roots:L(v0)}),$0=Be.extend({method:S("notifications/roots/list_changed"),params:qe.optional()}),j1=X([Lo,lx,b0,Fx,Ix,Ox,wx,bx,xx,$x,Ex,Zx,qx,qo,Zo,Uo,Vo]),L1=X([jo,Mo,fx,$0,yn]),M1=X([Vt,Sa,Ea,Ra,k0,Bo,Fo,Kt]),q1=X([Lo,$a,Ta,x0,qo,Zo,Uo,Vo]),B1=X([jo,Mo,Kx,Rx,ma,ka,va,yn,g0]),Z1=X([Vt,ca,Pa,ba,ha,la,da,pa,Pt,xa,Bo,Fo,Kt]),T=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===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ra(o.elicitations,r)}return new e(t,r,n)}},ra=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function zt(e){return e==="completed"||e==="failed"||e==="cancelled"}var S0=Symbol("Let zodToJsonSchema decide on which parser to use");var vD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function za(e){let r=Oo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$p(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Oa(e,t){let r=Je(e,t);if(!r.success)throw r.error;return r.data}var O0=6e4,Ko=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(jo,r=>{this._oncancel(r)}),this.setNotificationHandler(Mo,r=>{this._onprogress(r)}),this.setRequestHandler(Lo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Zo,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 T(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 T(A.InvalidParams,`Task not found: ${i}`);if(!zt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(zt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Rt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Uo,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 T(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Vo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(zt(o.status))throw new T(A.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 T(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(A.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),T.fromError(A.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),fn(i)||em(i)?this._onresponse(i):ia(i)?this._onrequest(i,s):Xp(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=T.fromError(A.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?.[Rt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:A.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=Jp(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 T(A.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:A.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),fn(t))n(t);else{let s=new T(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(fn(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),fn(t))o(t);else{let s=T.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 T?s:new T(A.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Kt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},zt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(A.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(A.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 T?s:new T(A.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=x=>{u(x)};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(x){d(x);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||{},[Rt]:c}});let m=x=>{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(x)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let k=x instanceof T?x:new T(A.RequestTimeout,String(x));u(k)};this._responseHandlers.set(f,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return u(x);try{let k=Je(r,x.result);k.success?l(k.data):u(k.error)}catch(k){u(k)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??O0,_=()=>m(T.fromError(A.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let x=k=>{let R=this._responseHandlers.get(f);R?R(k):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,x),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(f),u(k)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(x=>{this._cleanupTimeout(f),u(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Bo,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},Fo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},nm,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||{},[Rt]: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||{},[Rt]: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||{},[Rt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=za(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Oa(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=za(t);this._notificationHandlers.set(n,o=>{let i=Oa(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"&&ia(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(A.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 T(A.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(A.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 T(A.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=yn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),zt(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 T(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(zt(a.status))throw new T(A.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=yn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),zt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function dm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fm(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];dm(s)&&dm(i)?r[o]={...s,...i}:r[o]=i}return r}var ny=ps(yu(),1),oy=ps(ry(),1);function CR(){let e=new ny.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,oy.default)(e),e}var Ti=class{constructor(t){this._ajv=t??CR()}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 Ri=class{constructor(t){this._client=t}async*callToolStream(t,r=Pt,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 T(A.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 T(A.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof T){yield{type:"error",error:u};return}yield{type:"error",error:new T(A.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 iy(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 sy(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 Pi(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&&Pi(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Pi(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Pi(r,t)}}function NR(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 zi=class extends Ko{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 Ti,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ka,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",va,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ma,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ri(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fm(this._capabilities,t)}setRequestHandler(t,r){let o=Oo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(hr(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=Je(Ta,c);if(!u.success){let x=u.error instanceof Error?u.error.message:String(u.error);throw new T(A.InvalidParams,`Invalid elicitation request: ${x}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=NR(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(A.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(A.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let x=Je(Kt,m);if(!x.success){let k=x.error instanceof Error?x.error.message:String(x.error);throw new T(A.InvalidParams,`Invalid task creation result: ${k}`)}return x.data}let h=Je(Ra,m);if(!h.success){let x=h.error instanceof Error?h.error.message:String(h.error);throw new T(A.InvalidParams,`Invalid elicitation result: ${x}`)}let _=h.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Pi(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Je($a,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(A.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Je(Kt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(A.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?Ea:Sa,h=Je(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(A.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:na,capabilities:this._capabilities,clientInfo:this._clientInfo}},ca,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Hp.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){iy(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&sy(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Vt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Pa,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Vt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},ba,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},ha,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},la,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},da,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},pa,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Vt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Vt,r)}async callTool(t,r=Pt,n){if(this.isToolTaskRequired(t.name))throw new T(A.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 T(A.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 T(A.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(A.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},xa,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=um.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 Jy=ps(Wy(),1);import Cu from"node:process";import{PassThrough as uP}from"node:stream";var Ai=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),
|
|
37
|
-
`}var
|
|
38
|
-
`).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function
|
|
39
|
-
`);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(r=>r.endsWith("\r")?r.slice(0,-1):r)}function dt(e){return b(e,"invalid quoted string")}function ft(e,t){if(e==="")return"";if(e.startsWith('"'))return r_(e,t);if(e.includes('"'))throw dt(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:
|
|
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 dt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw dt(t);r+=String.fromCharCode(a),n+=4;break}default:throw dt(t)}}throw dt(t)}function n_(e,t,r){for(;;){let n=e.indexOf('"',t),o=e.indexOf("\\",t);if(o!==-1&&(n===-1||o<n)){if(o===e.length-1)throw dt(r);t=o+2;continue}if(n===-1)throw dt(r);return n+1}}function xt(e,t,r){if(e==="")return[];let n=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(t,i);if(a!==-1&&(s===-1||a<s))n.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=n_(e,s+1,r);else break}return n.push(e.slice(o).trim()),n}function Re(e,t,r){let n=0;for(;n<e.length;){let o=e.indexOf('"',n),i=e.indexOf(t,n);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;n=n_(e,o+1,r)}return-1}function
|
|
35
|
+
})));`),f.write(`newResult[${Zt(x)}] = ${k}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(x,k)=>w(d,x,k)},o,i=pr,s=!go.jitless,c=s&&bs.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 k=u.shape;for(let R of u.keys){let O=k[R],$e=O._zod.run({value:p[R],issues:[]},f),Le=O._zod.optin==="optional"&&O._zod.optout==="optional";$e instanceof Promise?m.push($e.then(dr=>Le?Bd(dr,d,R,p):ko(dr,d,R))):Le?Bd($e,d,R,p):ko($e,d,R)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,x=w.def.type;for(let k of Object.keys(p)){if(_.has(k))continue;if(x==="never"){h.push(k);continue}let R=w.run({value:p[k],issues:[]},f);R instanceof Promise?m.push(R.then(O=>ko(O,d,k))):ko(R,d,k)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function Zd(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=>Ge(i,n,Me())))}),t}var Ns=y("$ZodUnion",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),W(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),W(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),W(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=>en(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=>Zd(s,r,e,n)):Zd(i,r,e,n)}}),Tf=y("$ZodDiscriminatedUnion",(e,t)=>{Ns.init(e,t);let r=e._zod.parse;W(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=Qr(()=>{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(!pr(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)}}),Rf=y("$ZodIntersection",(e,t)=>{G.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])=>Ud(r,c,l)):Ud(r,i,s)}});function Is(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(mr(e)&&mr(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=Is(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=Is(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 Ud(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ut(e))return e;let n=Is(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 Pf=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!mr(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(...it(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...it(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=>Ge(l,n,Me())),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(...it(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...it(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var zf=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=gs(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>vs.has(typeof n)).map(n=>typeof n=="string"?Tt(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}}),Of=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Tt(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 Af=y("$ZodTransform",(e,t)=>{G.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 ht;return r.value=o,r}}),If=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",W(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${en(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)}),Cf=y("$ZodNullable",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.innerType._zod.optin),W(e._zod,"optout",()=>t.innerType._zod.optout),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${en(r.source)}|null)$`):void 0}),W(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)}),Nf=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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=>Fd(i,t)):Fd(o,t)}});function Fd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Df=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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))}),jf=y("$ZodNonOptional",(e,t)=>{G.init(e,t),W(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=>Vd(i,e)):Vd(o,e)}});function Vd(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 Lf=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(e._zod,"optout",()=>t.innerType._zod.optout),W(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=>Ge(s,n,Me()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ge(i,n,Me()))},input:r.value}),r.issues=[]),r)}});var Mf=y("$ZodPipe",(e,t)=>{G.init(e,t),W(e._zod,"values",()=>t.in._zod.values),W(e._zod,"optin",()=>t.in._zod.optin),W(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=>Kd(i,t,n)):Kd(o,t,n)}});function Kd(e,t,r){return Ut(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var qf=y("$ZodReadonly",(e,t)=>{G.init(e,t),W(e._zod,"propValues",()=>t.innerType._zod.propValues),W(e._zod,"values",()=>t.innerType._zod.values),W(e._zod,"optin",()=>t.innerType._zod.optin),W(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(Hd):Hd(o)}});function Hd(e){return e.value=Object.freeze(e.value),e}var Bf=y("$ZodCustom",(e,t)=>{ye.init(e,t),G.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=>Wd(i,r,n,e));Wd(o,r,n,e)}});function Wd(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($s(o))}}var sv=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},av=()=>{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 ${sv(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${wo(n.values[0])}`:`Invalid option: expected one of ${yo(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":""}: ${yo(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 Zf(){return{localeError:av()}}var yN=Symbol("ZodOutput"),_N=Symbol("ZodInput"),Ds=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 cv(){return new Ds}var on=cv();function Uf(e,t){return new e({type:"string",...P(t)})}function Ff(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function js(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function Vf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function Kf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function Hf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function Wf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Gf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Jf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Yf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Qf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Xf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function ep(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function tp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function rp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function np(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function op(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function ip(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function sp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function ap(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function cp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function up(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function lp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function dp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function fp(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function pp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function mp(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function hp(e,t){return new e({type:"number",checks:[],...P(t)})}function gp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function yp(e,t){return new e({type:"boolean",...P(t)})}function _p(e,t){return new e({type:"null",...P(t)})}function wp(e){return new e({type:"unknown"})}function bp(e,t){return new e({type:"never",...P(t)})}function So(e,t){return new Os({check:"less_than",...P(t),value:e,inclusive:!1})}function sn(e,t){return new Os({check:"less_than",...P(t),value:e,inclusive:!0})}function Eo(e,t){return new As({check:"greater_than",...P(t),value:e,inclusive:!1})}function an(e,t){return new As({check:"greater_than",...P(t),value:e,inclusive:!0})}function To(e,t){return new Ed({check:"multiple_of",...P(t),value:e})}function Ro(e,t){return new Rd({check:"max_length",...P(t),maximum:e})}function hr(e,t){return new Pd({check:"min_length",...P(t),minimum:e})}function Po(e,t){return new zd({check:"length_equals",...P(t),length:e})}function Ls(e,t){return new Od({check:"string_format",format:"regex",...P(t),pattern:e})}function Ms(e){return new Ad({check:"string_format",format:"lowercase",...P(e)})}function qs(e){return new Id({check:"string_format",format:"uppercase",...P(e)})}function Bs(e,t){return new Cd({check:"string_format",format:"includes",...P(t),includes:e})}function Zs(e,t){return new Nd({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Us(e,t){return new Dd({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Ft(e){return new jd({check:"overwrite",tx:e})}function Fs(e){return Ft(t=>t.normalize(e))}function Vs(){return Ft(e=>e.trim())}function Ks(){return Ft(e=>e.toLowerCase())}function Hs(){return Ft(e=>e.toUpperCase())}function vp(e,t,r){return new e({type:"array",element:t,...P(r)})}function xp(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function kp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function gr(e){return!!e._zod}function Je(e,t){return gr(e)?rn(e,t):e.safeParse(t)}function zo(e){if(!e)return;let t;if(gr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $p(e){if(gr(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 un={};Ml(un,{ZodISODate:()=>Ep,ZodISODateTime:()=>Sp,ZodISODuration:()=>Rp,ZodISOTime:()=>Tp,date:()=>Gs,datetime:()=>Ws,duration:()=>Ys,time:()=>Js});var Sp=y("ZodISODateTime",(e,t)=>{af.init(e,t),re.init(e,t)});function Ws(e){return dp(Sp,e)}var Ep=y("ZodISODate",(e,t)=>{cf.init(e,t),re.init(e,t)});function Gs(e){return fp(Ep,e)}var Tp=y("ZodISOTime",(e,t)=>{uf.init(e,t),re.init(e,t)});function Js(e){return pp(Tp,e)}var Rp=y("ZodISODuration",(e,t)=>{lf.init(e,t),re.init(e,t)});function Ys(e){return mp(Rp,e)}var Pp=(e,t)=>{bo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Hl(e,r)},flatten:{value:r=>Kl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},QN=y("ZodError",Pp),ln=y("ZodError",Pp,{Parent:Error});var zp=Wl(ln),Op=Gl(ln),Ap=Es(ln),Ip=Ts(ln);var ie=y("ZodType",(e,t)=>(G.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)=>ot(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>zp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ap(e,r,n),e.parseAsync=async(r,n)=>Op(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ip(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(ix(r,n)),e.superRefine=r=>e.check(sx(r)),e.overwrite=r=>e.check(Ft(r)),e.optional=()=>oe(e),e.nullable=()=>Dp(e),e.nullish=()=>oe(Dp(e)),e.nonoptional=r=>Qv(e,r),e.array=()=>L(e),e.or=r=>X([e,r]),e.and=r=>Ao(e,r),e.transform=r=>Xs(e,Zp(r)),e.default=r=>Gv(e,r),e.prefault=r=>Yv(e,r),e.catch=r=>ex(e,r),e.pipe=r=>Xs(e,r),e.readonly=()=>nx(e),e.describe=r=>{let n=e.clone();return on.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return on.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return on.get(e);let n=e.clone();return on.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),jp=y("_ZodString",(e,t)=>{$o.init(e,t),ie.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(Ls(...n)),e.includes=(...n)=>e.check(Bs(...n)),e.startsWith=(...n)=>e.check(Zs(...n)),e.endsWith=(...n)=>e.check(Us(...n)),e.min=(...n)=>e.check(hr(...n)),e.max=(...n)=>e.check(Ro(...n)),e.length=(...n)=>e.check(Po(...n)),e.nonempty=(...n)=>e.check(hr(1,...n)),e.lowercase=n=>e.check(Ms(n)),e.uppercase=n=>e.check(qs(n)),e.trim=()=>e.check(Vs()),e.normalize=(...n)=>e.check(Fs(...n)),e.toLowerCase=()=>e.check(Ks()),e.toUpperCase=()=>e.check(Hs())}),yv=y("ZodString",(e,t)=>{$o.init(e,t),jp.init(e,t),e.email=r=>e.check(Ff(_v,r)),e.url=r=>e.check(Gf(wv,r)),e.jwt=r=>e.check(lp(Cv,r)),e.emoji=r=>e.check(Jf(bv,r)),e.guid=r=>e.check(js(Cp,r)),e.uuid=r=>e.check(Vf(Oo,r)),e.uuidv4=r=>e.check(Kf(Oo,r)),e.uuidv6=r=>e.check(Hf(Oo,r)),e.uuidv7=r=>e.check(Wf(Oo,r)),e.nanoid=r=>e.check(Yf(vv,r)),e.guid=r=>e.check(js(Cp,r)),e.cuid=r=>e.check(Qf(xv,r)),e.cuid2=r=>e.check(Xf(kv,r)),e.ulid=r=>e.check(ep($v,r)),e.base64=r=>e.check(ap(Ov,r)),e.base64url=r=>e.check(cp(Av,r)),e.xid=r=>e.check(tp(Sv,r)),e.ksuid=r=>e.check(rp(Ev,r)),e.ipv4=r=>e.check(np(Tv,r)),e.ipv6=r=>e.check(op(Rv,r)),e.cidrv4=r=>e.check(ip(Pv,r)),e.cidrv6=r=>e.check(sp(zv,r)),e.e164=r=>e.check(up(Iv,r)),e.datetime=r=>e.check(Ws(r)),e.date=r=>e.check(Gs(r)),e.time=r=>e.check(Js(r)),e.duration=r=>e.check(Ys(r))});function g(e){return Uf(yv,e)}var re=y("ZodStringFormat",(e,t)=>{Q.init(e,t),jp.init(e,t)}),_v=y("ZodEmail",(e,t)=>{Yd.init(e,t),re.init(e,t)});var Cp=y("ZodGUID",(e,t)=>{Gd.init(e,t),re.init(e,t)});var Oo=y("ZodUUID",(e,t)=>{Jd.init(e,t),re.init(e,t)});var wv=y("ZodURL",(e,t)=>{Qd.init(e,t),re.init(e,t)});var bv=y("ZodEmoji",(e,t)=>{Xd.init(e,t),re.init(e,t)});var vv=y("ZodNanoID",(e,t)=>{ef.init(e,t),re.init(e,t)});var xv=y("ZodCUID",(e,t)=>{tf.init(e,t),re.init(e,t)});var kv=y("ZodCUID2",(e,t)=>{rf.init(e,t),re.init(e,t)});var $v=y("ZodULID",(e,t)=>{nf.init(e,t),re.init(e,t)});var Sv=y("ZodXID",(e,t)=>{of.init(e,t),re.init(e,t)});var Ev=y("ZodKSUID",(e,t)=>{sf.init(e,t),re.init(e,t)});var Tv=y("ZodIPv4",(e,t)=>{df.init(e,t),re.init(e,t)});var Rv=y("ZodIPv6",(e,t)=>{ff.init(e,t),re.init(e,t)});var Pv=y("ZodCIDRv4",(e,t)=>{pf.init(e,t),re.init(e,t)});var zv=y("ZodCIDRv6",(e,t)=>{mf.init(e,t),re.init(e,t)});var Ov=y("ZodBase64",(e,t)=>{gf.init(e,t),re.init(e,t)});var Av=y("ZodBase64URL",(e,t)=>{yf.init(e,t),re.init(e,t)});var Iv=y("ZodE164",(e,t)=>{_f.init(e,t),re.init(e,t)});var Cv=y("ZodJWT",(e,t)=>{wf.init(e,t),re.init(e,t)});var Lp=y("ZodNumber",(e,t)=>{Cs.init(e,t),ie.init(e,t),e.gt=(n,o)=>e.check(Eo(n,o)),e.gte=(n,o)=>e.check(an(n,o)),e.min=(n,o)=>e.check(an(n,o)),e.lt=(n,o)=>e.check(So(n,o)),e.lte=(n,o)=>e.check(sn(n,o)),e.max=(n,o)=>e.check(sn(n,o)),e.int=n=>e.check(Np(n)),e.safe=n=>e.check(Np(n)),e.positive=n=>e.check(Eo(0,n)),e.nonnegative=n=>e.check(an(0,n)),e.negative=n=>e.check(So(0,n)),e.nonpositive=n=>e.check(sn(0,n)),e.multipleOf=(n,o)=>e.check(To(n,o)),e.step=(n,o)=>e.check(To(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 hp(Lp,e)}var Nv=y("ZodNumberFormat",(e,t)=>{bf.init(e,t),Lp.init(e,t)});function Np(e){return gp(Nv,e)}var Dv=y("ZodBoolean",(e,t)=>{vf.init(e,t),ie.init(e,t)});function le(e){return yp(Dv,e)}var jv=y("ZodNull",(e,t)=>{xf.init(e,t),ie.init(e,t)});function Mp(e){return _p(jv,e)}var Lv=y("ZodUnknown",(e,t)=>{kf.init(e,t),ie.init(e,t)});function ne(){return wp(Lv)}var Mv=y("ZodNever",(e,t)=>{$f.init(e,t),ie.init(e,t)});function qv(e){return bp(Mv,e)}var Bv=y("ZodArray",(e,t)=>{Sf.init(e,t),ie.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(hr(r,n)),e.nonempty=r=>e.check(hr(1,r)),e.max=(r,n)=>e.check(Ro(r,n)),e.length=(r,n)=>e.check(Po(r,n)),e.unwrap=()=>e.element});function L(e,t){return vp(Bv,e,t)}var qp=y("ZodObject",(e,t)=>{Ef.init(e,t),ie.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ze(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ne()}),e.loose=()=>e.clone({...e._zod.def,catchall:ne()}),e.strict=()=>e.clone({...e._zod.def,catchall:qv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>U.extend(e,r),e.merge=r=>U.merge(e,r),e.pick=r=>U.pick(e,r),e.omit=r=>U.omit(e,r),e.partial=(...r)=>U.partial(Up,e,r[0]),e.required=(...r)=>U.required(Fp,e,r[0])});function $(e,t){let r={type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},...U.normalizeParams(t)};return new qp(r)}function Se(e,t){return new qp({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:ne(),...U.normalizeParams(t)})}var Bp=y("ZodUnion",(e,t)=>{Ns.init(e,t),ie.init(e,t),e.options=t.options});function X(e,t){return new Bp({type:"union",options:e,...U.normalizeParams(t)})}var Zv=y("ZodDiscriminatedUnion",(e,t)=>{Bp.init(e,t),Tf.init(e,t)});function ea(e,t,r){return new Zv({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Uv=y("ZodIntersection",(e,t)=>{Rf.init(e,t),ie.init(e,t)});function Ao(e,t){return new Uv({type:"intersection",left:e,right:t})}var Fv=y("ZodRecord",(e,t)=>{Pf.init(e,t),ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new Fv({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var Qs=y("ZodEnum",(e,t)=>{zf.init(e,t),ie.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 Qs({...t,checks:[],...U.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 Qs({...t,checks:[],...U.normalizeParams(o),entries:i})}});function ze(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Qs({type:"enum",entries:r,...U.normalizeParams(t)})}var Vv=y("ZodLiteral",(e,t)=>{Of.init(e,t),ie.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 S(e,t){return new Vv({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var Kv=y("ZodTransform",(e,t)=>{Af.init(e,t),ie.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(U.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(U.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 Zp(e){return new Kv({type:"transform",transform:e})}var Up=y("ZodOptional",(e,t)=>{If.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function oe(e){return new Up({type:"optional",innerType:e})}var Hv=y("ZodNullable",(e,t)=>{Cf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Dp(e){return new Hv({type:"nullable",innerType:e})}var Wv=y("ZodDefault",(e,t)=>{Nf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Gv(e,t){return new Wv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Jv=y("ZodPrefault",(e,t)=>{Df.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yv(e,t){return new Jv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Fp=y("ZodNonOptional",(e,t)=>{jf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Qv(e,t){return new Fp({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var Xv=y("ZodCatch",(e,t)=>{Lf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ex(e,t){return new Xv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var tx=y("ZodPipe",(e,t)=>{Mf.init(e,t),ie.init(e,t),e.in=t.in,e.out=t.out});function Xs(e,t){return new tx({type:"pipe",in:e,out:t})}var rx=y("ZodReadonly",(e,t)=>{qf.init(e,t),ie.init(e,t)});function nx(e){return new rx({type:"readonly",innerType:e})}var Vp=y("ZodCustom",(e,t)=>{Bf.init(e,t),ie.init(e,t)});function ox(e){let t=new ye({check:"custom"});return t._zod.check=e,t}function Kp(e,t){return xp(Vp,e??(()=>!0),t)}function ix(e,t={}){return kp(Vp,e,t)}function sx(e){let t=ox(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(U.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(U.issue(o))}},e(r.value,r)));return t}function ta(e,t){return Xs(Zp(e),t)}Me(Zf());var na="2025-11-25";var Hp=[na,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rt="io.modelcontextprotocol/related-task",Co="2.0",ce=Kp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Wp=X([g(),V().int()]),Gp=g(),V1=Se({ttl:V().optional(),pollInterval:V().optional()}),ax=$({ttl:V().optional()}),cx=$({taskId:g()}),oa=Se({progressToken:Wp.optional(),[Rt]:cx.optional()}),Ne=$({_meta:oa.optional()}),dn=Ne.extend({task:ax.optional()}),Jp=e=>dn.safeParse(e).success,de=$({method:g(),params:Ne.loose().optional()}),qe=$({_meta:oa.optional()}),Be=$({method:g(),params:qe.loose().optional()}),fe=Se({_meta:oa.optional()}),No=X([g(),V().int()]),Yp=$({jsonrpc:S(Co),id:No,...de.shape}).strict(),ia=e=>Yp.safeParse(e).success,Qp=$({jsonrpc:S(Co),...Be.shape}).strict(),Xp=e=>Qp.safeParse(e).success,sa=$({jsonrpc:S(Co),id:No,result:fe}).strict(),fn=e=>sa.safeParse(e).success;var A;(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"})(A||(A={}));var aa=$({jsonrpc:S(Co),id:No.optional(),error:$({code:V().int(),message:g(),data:ne().optional()})}).strict();var em=e=>aa.safeParse(e).success;var tm=X([Yp,Qp,sa,aa]),K1=X([sa,aa]),Vt=fe.strict(),ux=qe.extend({requestId:No.optional(),reason:g().optional()}),Do=Be.extend({method:S("notifications/cancelled"),params:ux}),lx=$({src:g(),mimeType:g().optional(),sizes:L(g()).optional(),theme:ze(["light","dark"]).optional()}),pn=$({icons:L(lx).optional()}),yr=$({name:g(),title:g().optional()}),rm=yr.extend({...yr.shape,...pn.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),dx=Ao($({applyDefaults:le().optional()}),J(g(),ne())),fx=ta(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ao($({form:dx.optional(),url:ce.optional()}),J(g(),ne()).optional())),px=Se({list:ce.optional(),cancel:ce.optional(),requests:Se({sampling:Se({createMessage:ce.optional()}).optional(),elicitation:Se({create:ce.optional()}).optional()}).optional()}),mx=Se({list:ce.optional(),cancel:ce.optional(),requests:Se({tools:Se({call:ce.optional()}).optional()}).optional()}),hx=$({experimental:J(g(),ce).optional(),sampling:$({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:fx.optional(),roots:$({listChanged:le().optional()}).optional(),tasks:px.optional(),extensions:J(g(),ce).optional()}),gx=Ne.extend({protocolVersion:g(),capabilities:hx,clientInfo:rm}),yx=de.extend({method:S("initialize"),params:gx});var _x=$({experimental:J(g(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:$({listChanged:le().optional()}).optional(),resources:$({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:$({listChanged:le().optional()}).optional(),tasks:mx.optional(),extensions:J(g(),ce).optional()}),ca=fe.extend({protocolVersion:g(),capabilities:_x,serverInfo:rm,instructions:g().optional()}),wx=Be.extend({method:S("notifications/initialized"),params:qe.optional()});var jo=de.extend({method:S("ping"),params:Ne.optional()}),bx=$({progress:V(),total:oe(V()),message:oe(g())}),vx=$({...qe.shape,...bx.shape,progressToken:Wp}),Lo=Be.extend({method:S("notifications/progress"),params:vx}),xx=Ne.extend({cursor:Gp.optional()}),mn=de.extend({params:xx.optional()}),hn=fe.extend({nextCursor:Gp.optional()}),kx=ze(["working","input_required","completed","failed","cancelled"]),gn=$({taskId:g(),status:kx,ttl:X([V(),Mp()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:oe(V()),statusMessage:oe(g())}),Kt=fe.extend({task:gn}),$x=qe.merge(gn),yn=Be.extend({method:S("notifications/tasks/status"),params:$x}),Mo=de.extend({method:S("tasks/get"),params:Ne.extend({taskId:g()})}),qo=fe.merge(gn),Bo=de.extend({method:S("tasks/result"),params:Ne.extend({taskId:g()})}),H1=fe.loose(),Zo=mn.extend({method:S("tasks/list")}),Uo=hn.extend({tasks:L(gn)}),Fo=de.extend({method:S("tasks/cancel"),params:Ne.extend({taskId:g()})}),nm=fe.merge(gn),om=$({uri:g(),mimeType:oe(g()),_meta:J(g(),ne()).optional()}),im=om.extend({text:g()}),ua=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),sm=om.extend({blob:ua}),_n=ze(["user","assistant"]),_r=$({audience:L(_n).optional(),priority:V().min(0).max(1).optional(),lastModified:un.datetime({offset:!0}).optional()}),am=$({...yr.shape,...pn.shape,uri:g(),description:oe(g()),mimeType:oe(g()),size:oe(V()),annotations:_r.optional(),_meta:oe(Se({}))}),Sx=$({...yr.shape,...pn.shape,uriTemplate:g(),description:oe(g()),mimeType:oe(g()),annotations:_r.optional(),_meta:oe(Se({}))}),Ex=mn.extend({method:S("resources/list")}),la=hn.extend({resources:L(am)}),Tx=mn.extend({method:S("resources/templates/list")}),da=hn.extend({resourceTemplates:L(Sx)}),fa=Ne.extend({uri:g()}),Rx=fa,Px=de.extend({method:S("resources/read"),params:Rx}),pa=fe.extend({contents:L(X([im,sm]))}),ma=Be.extend({method:S("notifications/resources/list_changed"),params:qe.optional()}),zx=fa,Ox=de.extend({method:S("resources/subscribe"),params:zx}),Ax=fa,Ix=de.extend({method:S("resources/unsubscribe"),params:Ax}),Cx=qe.extend({uri:g()}),Nx=Be.extend({method:S("notifications/resources/updated"),params:Cx}),Dx=$({name:g(),description:oe(g()),required:oe(le())}),jx=$({...yr.shape,...pn.shape,description:oe(g()),arguments:oe(L(Dx)),_meta:oe(Se({}))}),Lx=mn.extend({method:S("prompts/list")}),ha=hn.extend({prompts:L(jx)}),Mx=Ne.extend({name:g(),arguments:J(g(),g()).optional()}),qx=de.extend({method:S("prompts/get"),params:Mx}),ga=$({type:S("text"),text:g(),annotations:_r.optional(),_meta:J(g(),ne()).optional()}),ya=$({type:S("image"),data:ua,mimeType:g(),annotations:_r.optional(),_meta:J(g(),ne()).optional()}),_a=$({type:S("audio"),data:ua,mimeType:g(),annotations:_r.optional(),_meta:J(g(),ne()).optional()}),Bx=$({type:S("tool_use"),name:g(),id:g(),input:J(g(),ne()),_meta:J(g(),ne()).optional()}),Zx=$({type:S("resource"),resource:X([im,sm]),annotations:_r.optional(),_meta:J(g(),ne()).optional()}),Ux=am.extend({type:S("resource_link")}),wa=X([ga,ya,_a,Ux,Zx]),Fx=$({role:_n,content:wa}),ba=fe.extend({description:g().optional(),messages:L(Fx)}),va=Be.extend({method:S("notifications/prompts/list_changed"),params:qe.optional()}),Vx=$({title:g().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),Kx=$({taskSupport:ze(["required","optional","forbidden"]).optional()}),cm=$({...yr.shape,...pn.shape,description:g().optional(),inputSchema:$({type:S("object"),properties:J(g(),ce).optional(),required:L(g()).optional()}).catchall(ne()),outputSchema:$({type:S("object"),properties:J(g(),ce).optional(),required:L(g()).optional()}).catchall(ne()).optional(),annotations:Vx.optional(),execution:Kx.optional(),_meta:J(g(),ne()).optional()}),Hx=mn.extend({method:S("tools/list")}),xa=hn.extend({tools:L(cm)}),Pt=fe.extend({content:L(wa).default([]),structuredContent:J(g(),ne()).optional(),isError:le().optional()}),W1=Pt.or(fe.extend({toolResult:ne()})),Wx=dn.extend({name:g(),arguments:J(g(),ne()).optional()}),Gx=de.extend({method:S("tools/call"),params:Wx}),ka=Be.extend({method:S("notifications/tools/list_changed"),params:qe.optional()}),um=$({autoRefresh:le().default(!0),debounceMs:V().int().nonnegative().default(300)}),lm=ze(["debug","info","notice","warning","error","critical","alert","emergency"]),Jx=Ne.extend({level:lm}),Yx=de.extend({method:S("logging/setLevel"),params:Jx}),Qx=qe.extend({level:lm,logger:g().optional(),data:ne()}),Xx=Be.extend({method:S("notifications/message"),params:Qx}),e0=$({name:g().optional()}),t0=$({hints:L(e0).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),r0=$({mode:ze(["auto","required","none"]).optional()}),n0=$({type:S("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:L(wa).default([]),structuredContent:$({}).loose().optional(),isError:le().optional(),_meta:J(g(),ne()).optional()}),o0=ea("type",[ga,ya,_a]),Io=ea("type",[ga,ya,_a,Bx,n0]),i0=$({role:_n,content:X([Io,L(Io)]),_meta:J(g(),ne()).optional()}),s0=dn.extend({messages:L(i0),modelPreferences:t0.optional(),systemPrompt:g().optional(),includeContext:ze(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:L(g()).optional(),metadata:ce.optional(),tools:L(cm).optional(),toolChoice:r0.optional()}),$a=de.extend({method:S("sampling/createMessage"),params:s0}),Sa=fe.extend({model:g(),stopReason:oe(ze(["endTurn","stopSequence","maxTokens"]).or(g())),role:_n,content:o0}),Ea=fe.extend({model:g(),stopReason:oe(ze(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:_n,content:X([Io,L(Io)])}),a0=$({type:S("boolean"),title:g().optional(),description:g().optional(),default:le().optional()}),c0=$({type:S("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:ze(["email","uri","date","date-time"]).optional(),default:g().optional()}),u0=$({type:ze(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),l0=$({type:S("string"),title:g().optional(),description:g().optional(),enum:L(g()),default:g().optional()}),d0=$({type:S("string"),title:g().optional(),description:g().optional(),oneOf:L($({const:g(),title:g()})),default:g().optional()}),f0=$({type:S("string"),title:g().optional(),description:g().optional(),enum:L(g()),enumNames:L(g()).optional(),default:g().optional()}),p0=X([l0,d0]),m0=$({type:S("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:S("string"),enum:L(g())}),default:L(g()).optional()}),h0=$({type:S("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:L($({const:g(),title:g()}))}),default:L(g()).optional()}),g0=X([m0,h0]),y0=X([f0,p0,g0]),_0=X([y0,a0,c0,u0]),w0=dn.extend({mode:S("form").optional(),message:g(),requestedSchema:$({type:S("object"),properties:J(g(),_0),required:L(g()).optional()})}),b0=dn.extend({mode:S("url"),message:g(),elicitationId:g(),url:g().url()}),v0=X([w0,b0]),Ta=de.extend({method:S("elicitation/create"),params:v0}),x0=qe.extend({elicitationId:g()}),k0=Be.extend({method:S("notifications/elicitation/complete"),params:x0}),Ra=fe.extend({action:ze(["accept","decline","cancel"]),content:ta(e=>e===null?void 0:e,J(g(),X([g(),V(),le(),L(g())])).optional())}),$0=$({type:S("ref/resource"),uri:g()});var S0=$({type:S("ref/prompt"),name:g()}),E0=Ne.extend({ref:X([S0,$0]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),T0=de.extend({method:S("completion/complete"),params:E0});var Pa=fe.extend({completion:Se({values:L(g()).max(100),total:oe(V().int()),hasMore:oe(le())})}),R0=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),ne()).optional()}),P0=de.extend({method:S("roots/list"),params:Ne.optional()}),z0=fe.extend({roots:L(R0)}),O0=Be.extend({method:S("notifications/roots/list_changed"),params:qe.optional()}),G1=X([jo,yx,T0,Yx,qx,Lx,Ex,Tx,Px,Ox,Ix,Gx,Hx,Mo,Bo,Zo,Fo]),J1=X([Do,Lo,wx,O0,yn]),Y1=X([Vt,Sa,Ea,Ra,z0,qo,Uo,Kt]),Q1=X([jo,$a,Ta,P0,Mo,Bo,Zo,Fo]),X1=X([Do,Lo,Xx,Nx,ma,ka,va,yn,k0]),eD=X([Vt,ca,Pa,ba,ha,la,da,pa,Pt,xa,qo,Uo,Kt]),T=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===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ra(o.elicitations,r)}return new e(t,r,n)}},ra=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function zt(e){return e==="completed"||e==="failed"||e==="cancelled"}var A0=Symbol("Let zodToJsonSchema decide on which parser to use");var ID=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function za(e){let r=zo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$p(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Oa(e,t){let r=Je(e,t);if(!r.success)throw r.error;return r.data}var L0=6e4,Vo=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(Do,r=>{this._oncancel(r)}),this.setNotificationHandler(Lo,r=>{this._onprogress(r)}),this.setRequestHandler(jo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Mo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Bo,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 T(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 T(A.InvalidParams,`Task not found: ${i}`);if(!zt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(zt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Rt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Zo,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 T(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Fo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(zt(o.status))throw new T(A.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 T(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(A.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),T.fromError(A.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),fn(i)||em(i)?this._onresponse(i):ia(i)?this._onrequest(i,s):Xp(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=T.fromError(A.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?.[Rt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:A.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=Jp(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 T(A.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:A.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),fn(t))n(t);else{let s=new T(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(fn(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),fn(t))o(t);else{let s=T.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 T?s:new T(A.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Kt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},zt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(A.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(A.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 T?s:new T(A.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=x=>{u(x)};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(x){d(x);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||{},[Rt]:c}});let m=x=>{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(x)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let k=x instanceof T?x:new T(A.RequestTimeout,String(x));u(k)};this._responseHandlers.set(f,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return u(x);try{let k=Je(r,x.result);k.success?l(k.data):u(k.error)}catch(k){u(k)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??L0,_=()=>m(T.fromError(A.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let x=k=>{let R=this._responseHandlers.get(f);R?R(k):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,x),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(f),u(k)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(x=>{this._cleanupTimeout(f),u(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},qo,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},Uo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},nm,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||{},[Rt]: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||{},[Rt]: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||{},[Rt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=za(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Oa(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=za(t);this._notificationHandlers.set(n,o=>{let i=Oa(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"&&ia(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(A.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 T(A.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(A.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 T(A.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=yn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),zt(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 T(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(zt(a.status))throw new T(A.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=yn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),zt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function dm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fm(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];dm(s)&&dm(i)?r[o]={...s,...i}:r[o]=i}return r}var ny=ps(yu(),1),oy=ps(ry(),1);function BR(){let e=new ny.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,oy.default)(e),e}var Ei=class{constructor(t){this._ajv=t??BR()}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 Ti=class{constructor(t){this._client=t}async*callToolStream(t,r=Pt,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 T(A.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 T(A.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof T){yield{type:"error",error:u};return}yield{type:"error",error:new T(A.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 iy(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 sy(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 Ri(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&&Ri(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ri(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ri(r,t)}}function ZR(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 Pi=class extends Vo{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 Ei,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ka,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",va,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ma,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ti(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fm(this._capabilities,t)}setRequestHandler(t,r){let o=zo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(gr(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=Je(Ta,c);if(!u.success){let x=u.error instanceof Error?u.error.message:String(u.error);throw new T(A.InvalidParams,`Invalid elicitation request: ${x}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=ZR(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(A.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(A.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let x=Je(Kt,m);if(!x.success){let k=x.error instanceof Error?x.error.message:String(x.error);throw new T(A.InvalidParams,`Invalid task creation result: ${k}`)}return x.data}let h=Je(Ra,m);if(!h.success){let x=h.error instanceof Error?h.error.message:String(h.error);throw new T(A.InvalidParams,`Invalid elicitation result: ${x}`)}let _=h.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ri(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Je($a,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(A.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Je(Kt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(A.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?Ea:Sa,h=Je(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(A.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:na,capabilities:this._capabilities,clientInfo:this._clientInfo}},ca,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Hp.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){iy(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&sy(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Vt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Pa,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Vt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},ba,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},ha,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},la,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},da,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},pa,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Vt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Vt,r)}async callTool(t,r=Pt,n){if(this.isToolTaskRequired(t.name))throw new T(A.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 T(A.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 T(A.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(A.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},xa,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=um.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 Jy=ps(Wy(),1);import Cu from"node:process";import{PassThrough as gP}from"node:stream";var Oi=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),hP(r)}clear(){this._buffer=void 0}};function hP(e){return tm.parse(JSON.parse(e))}function Gy(e){return JSON.stringify(e)+`
|
|
37
|
+
`}var yP=Cu.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function _P(){let e={};for(let t of yP){let r=Cu.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Ai=class{constructor(t){this._readBuffer=new Oi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new gP)}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,Jy.default)(this._serverParams.command,this._serverParams.args??[],{env:{..._P(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Cu.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=Gy(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var wP=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var or=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new Ai({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??bP(),stderr:t.stderr??"pipe"}),n=new Pi({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:xP(r).map(kP),nextCursor:Yy(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!Ii(n,["error"])&&EP(n,["ok","success"],!0),target:t,messageId:rt(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:$P(r).map(SP).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=wP.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:vP(r)},Pt);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 bP(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function vP(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function xP(e){if(Array.isArray(e))return e;if(!Mr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&Mr(r)?[r]:[]}function kP(e){return Mr(e)?{id:rt(e,["id","message_id","messageId"]),cursor:Yy(e,["cursor"]),type:rt(e,["type","event_type","eventType"]),platform:rt(e,["platform"]),target:rt(e,["target"]),sessionKey:rt(e,["session_key","sessionKey"]),timestamp:rt(e,["timestamp","created_at","createdAt"]),message:rt(e,["message","text","content"]),raw:e}:{raw:e}}function $P(e){if(Array.isArray(e))return e;if(!Mr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function SP(e){if(!Mr(e))return null;let t=rt(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:rt(e,["platform"]),name:rt(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function rt(e,t){let r=Ii(e,t);return typeof r=="string"?r:void 0}function EP(e,t,r){let n=Ii(e,t);return typeof n=="boolean"?n:r}function Yy(e,t){let r=Ii(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function Ii(e,t){if(Mr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function Mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as jI,writeFile as LI}from"node:fs/promises";import{join as Jw}from"node:path";var Gn=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function b(e,t){return new Gn(e,t)}var Qy=["type","kind","event"],ir="|",Xy=new Set(["order","discriminator","rows","common"]);var De=",";function Nu(e){let t=e.split(`
|
|
39
|
+
`);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(r=>r.endsWith("\r")?r.slice(0,-1):r)}function dt(e){return b(e,"invalid quoted string")}function ft(e,t){if(e==="")return"";if(e.startsWith('"'))return r_(e,t);if(e.includes('"'))throw dt(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:TP(e)?Number(e):e}function vt(e,t){let r=e.trim();if(r.startsWith('"'))return[r_(r,t),!0];if(r.includes('"')||/\s/.test(r))throw b(t,"expected non-empty field name");return[r,!1]}var e_=/["\\\u0000-\u0008\u000a-\u001f]/g;function r_(e,t){if(e.charCodeAt(0)!==34)throw dt(t);let r="",n=1;for(;n<e.length;){e_.lastIndex=n;let o=e_.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return r+e.slice(n,o.index);throw dt(t)}if(o[0]!=="\\")throw dt(t);r+=e.slice(n,o.index);let i=e[o.index+1];switch(n=o.index+2,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 dt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw dt(t);r+=String.fromCharCode(a),n+=4;break}default:throw dt(t)}}throw dt(t)}function n_(e,t,r){for(;;){let n=e.indexOf('"',t),o=e.indexOf("\\",t);if(o!==-1&&(n===-1||o<n)){if(o===e.length-1)throw dt(r);t=o+2;continue}if(n===-1)throw dt(r);return n+1}}function xt(e,t,r){if(e==="")return[];let n=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(t,i);if(a!==-1&&(s===-1||a<s))n.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=n_(e,s+1,r);else break}return n.push(e.slice(o).trim()),n}function Re(e,t,r){let n=0;for(;n<e.length;){let o=e.indexOf('"',n),i=e.indexOf(t,n);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;n=n_(e,o+1,r)}return-1}function TP(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function RP(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function PP(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw b(0,"number is not representable in TOON");return String(e)}function kt(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function je(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return PP(e);if(typeof e=="string")return OP(e,t);throw b(0,"not a primitive")}function zP(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function ve(e){return zP(e)?e:Ci(e)}function OP(e,t){return Du(e,t)?Ci(e):e}function Du(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||RP(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}var t_=/["\\\u0000-\u001f]/g;function Ci(e){let t='"',r=0;t_.lastIndex=0;let n;for(;(n=t_.exec(e))!==null;){let o=e.charCodeAt(n.index),i;o===34?i='\\"':o===92?i="\\\\":o===10?i="\\n":o===13?i="\\r":o===9?i="\\t":i=`\\u${o.toString(16).padStart(4,"0")}`,t+=e.slice(r,n.index)+i,r=n.index+1}return`${t}${e.slice(r)}"`}function pt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function o_(e={}){let t=e.maxDepth??1e3,r=t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:r}}function i_(e,t){let r=[],n=!1;return Nu(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 b(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw b(s,"invalid indentation");let c=Math.floor(a/t.indent);mt(c,s,t),r.push({number:s,depth:c,content:o.slice(a),blankBefore:n}),n=!1}),r}function mt(e,t,r){if(r.maxDepth!==0&&e>r.maxDepth)throw b(t,`maximum nesting depth exceeded (maxDepth ${r.maxDepth})`)}function Qn(e,t,r){if(r.maxDepth===0)return;let n=0,o=!1,i=!1;for(let s of e){if(i){i=!1;continue}if(o&&s==="\\"){i=!0;continue}if(s==='"'){o=!o;continue}o||(s==="{"?(n+=1,mt(n,t,r)):s==="}"&&(n=Math.max(0,n-1)))}}function c_(e){if(!ue(e)||Object.keys(e).length===0)return e;let t={};for(let[r,n]of Object.entries(e)){let o=AP(n,1);if(o===void 0)return e;pt(t,r,o)}return t}function AP(e,t){if(!ue(e)||!IP(e))return;let{order:r,discriminator:n,rows:o}=e;if(typeof r!="string"||typeof n!="string"||!Number.isSafeInteger(o)||o<0)throw xe(t);let i=CP(r,o,t),s=e.common,a=s===void 0?Array.from({length:o},()=>({})):s;if(!Array.isArray(a)||a.length!==o||!a.every(ue))throw u_(t);let c=new Map;for(let[d,f]of Object.entries(e))if(!Xy.has(d)){if(!Array.isArray(f)||!f.every(ue))throw xe(t);c.set(d,f)}if(c.size===0)throw xe(t);let l=new Map,u=i.map((d,f)=>{let p=c.get(d);if(p===void 0)throw ju(t);let m=l.get(d)??0,h=p[m];if(h===void 0)throw ju(t);return l.set(d,m+1),NP(n,d,a[f],h,t)});for(let[d,f]of c)if((l.get(d)??0)!==f.length)throw ju(t);return u}function IP(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function CP(e,t,r){if(!e.startsWith("cycle("))throw xe(r);let n=e.slice(6),o=n.indexOf(")*");if(o===-1)throw xe(r);let i=n.slice(0,o),s=n.slice(o+2);if(i===""||s.includes("+tail("))throw xe(r);let a=i.split(",").map(u=>MP(u,r));if(a.some(u=>u===""))throw xe(r);let c=LP(s,r),l=a.length*c;if(!Number.isSafeInteger(l))throw xe(r);if(l!==t)throw u_(r);return Array.from({length:l},(u,d)=>a[d%a.length])}function NP(e,t,r,n,o){let i={};pt(i,e,t);for(let[s,a]of Object.entries(r??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw xe(o);pt(i,s,a)}for(let[s,a]of Object.entries(DP(n,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw xe(o);pt(i,s,a)}return i}function DP(e,t){let r={};for(let[n,o]of Object.entries(e))jP(r,n.split("."),o,t);return Ni(r,t)}function jP(e,t,r,n){if(t.some(i=>i===""))throw xe(n);let o=e;for(let i=0;i<t.length;i+=1){let s=t[i];if(i===t.length-1){o[s]=r;return}if(o[s]??={},o=o[s],!ue(o))throw xe(n)}}function Ni(e,t){return Array.isArray(e)?e.map(r=>Ni(r,t)):ue(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(r,n)=>{if(!Object.prototype.hasOwnProperty.call(e,String(n)))throw xe(t);return Ni(e[String(n)],t)}):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ni(n,t)])):e}function LP(e,t){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw xe(t);let r=Number(e);if(!Number.isSafeInteger(r))throw xe(t);return r}function MP(e,t){try{return decodeURIComponent(e)}catch{throw xe(t)}}function s_(e){return encodeURIComponent(e)}function xe(e){return b(e,"invalid cyclic array wire")}function u_(e){return b(e,"cyclic array length mismatch")}function ju(e){return b(e,"cyclic array group length mismatch")}function l_(e){if(!ue(e))return;let t=Object.entries(e);if(t.length===0)return;let r=[];for(let[o,i]of t){let s=qP(i);if(s===void 0)return;r.push([o,s])}let n=[];for(let[o,i]of r)FP(n,o,i);return n.join("")}function qP(e){if(!Array.isArray(e)||e.length===0||!e.every(ue))return;let t=BP(e);if(t===void 0)return;let r=e.map(a=>a[t]),n=ZP(r);if(n===void 0)return;let o=UP(e,t),i=new Map;for(let a of e){let c=a[t];i.has(c)||i.set(c,[]);let l={};for(let[u,d]of Object.entries(a))if(u!==t&&!o.includes(u)&&!Lu(d,u,l))return;i.get(c).push(l)}let s=[];for(let a of n.cycle){let c=i.get(a),l=KP(c);if(l===void 0||l.length===0)return;s.push({fields:l,label:a,rows:c})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(c=>[c,a[c]]))),discriminator:t,groups:s,order:n,rows:e}}function BP(e){return Qy.find(t=>e.every(r=>typeof r[t]=="string"))}function ZP(e){if(!(e.length<12))for(let t=2;t<=Math.min(8,Math.floor(e.length/3));t+=1){if(e.length%t!==0)continue;let r=e.slice(0,t);if(new Set(r).size<2||!e.every((s,a)=>s===r[a%t]))continue;let n=e.length/t;if(n<3)continue;let o=e.map(s_).join(","),i=`cycle(${r.map(s_).join(",")})*${n}`;if(i.length<=o.length*.4)return{cycle:r,encoded:i,repeats:n}}}function UP(e,t){let r=[],n=Object.keys(e[0]),o=n.indexOf(t)+1;for(let i of n.slice(o).filter(s=>s!==t)){if(!VP(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>kt(s[i])))break;r.push(i)}return r}function FP(e,t,r){e.push(ve(t),`:
|
|
41
41
|
`),e.push(" order: ",je(r.order.encoded,ir),`
|
|
42
42
|
`),e.push(" discriminator: ",je(r.discriminator,ir),`
|
|
43
43
|
`),e.push(" rows: ",String(r.rows.length),`
|
|
44
44
|
`),r.common.length>0&&a_(e,"common",r.common,r.commonRows);for(let n of r.groups)a_(e,n.label,n.fields,n.rows)}function a_(e,t,r,n){e.push(" ",ve(t),"[",String(n.length),ir,"]{",r.map(ve).join(ir),`}:
|
|
45
45
|
`);for(let o of n)e.push(" ",r.map(i=>je(o[i],ir)).join(ir),`
|
|
46
|
-
`)}function LP(e){return e!==""&&Mu(e)}function Lu(e,t,r,n=new Set){if(!Mu(t))return!1;if(kt(e))return r[t]=e,!0;if(Array.isArray(e)){if(n.has(e))return!1;n.add(e),r[`${t}.length`]=e.length;let o=e.every((i,s)=>Lu(i,`${t}.${s}`,r,n));return n.delete(e),o}if(ue(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&Lu(s,`${t}.${i}`,r,n));return n.delete(e),o}return!1}function MP(e){let t=Object.keys(e[0]??{});if(e.every(r=>qP(Object.keys(r),t)))return t.every(Mu)?t:void 0}function qP(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Mu(e){return e.split(".").every(t=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(t))}function Mr(e,t){let r=e[t]??e[e.length-1];return b(r===void 0?1:r.number,"array length mismatch")}function ji(e,t){if(t===-1)throw b(0,"array header missing colon");let r=e.slice(0,t),n=Re(r,"[",0);if(n===-1)throw b(0,"invalid array header");let o,i;try{[o,i]=vt(r.slice(0,n),0)}catch{throw b(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw b(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 b(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 b(0,"invalid array header")}let f=s.slice(a+1),p,m;if(f==="")p=void 0,m=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{m=ZP(f.slice(1,-1),d),p=Bu(m)}catch(h){throw b(0,h.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p,fieldTree:m}}function d_(e){let t=Re(e,"{",0);if(t===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let r,n;try{[r,n]=vt(e.slice(0,t),0)}catch{throw b(0,"invalid keyed map header")}if(r===""&&!n)throw b(0,"expected non-empty field name");let o=e.slice(t+1,-1),i=De;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=BP(o,i,i)}catch(a){throw b(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:i,fields:s}}function BP(e,t,r){let n=[],o=0;function i(c,l){let u=0;for(;o<e.length&&!(l&&e[o]==="}");){if(e[o]===t||e[o]==="}")throw b(0,"invalid array header");let d=o;for(;o<e.length;){let m=e[o];if(m==='"'){s();continue}if(m===t||m==="{"||m==="}"||m==="[")break;o+=1}let[f,p]=vt(e.slice(d,o),0);if(f===""&&!p)throw b(0,"invalid array header");if(u+=1,e[o]==="["){o+=1;let m=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let h=e.slice(m,o);if(!f_(h,r))throw b(0,"invalid array header");o+=1,n.push({path:[...c,f],listDelimiter:h})}else if(e[o]==="{"){o+=1;let m=n.length;if(i([...c,f],!0),e[o]!=="}"||n.length===m)throw b(0,"invalid array header");o+=1}else n.push({path:[...c,f],listDelimiter:void 0});if(e[o]===t){if(o+=1,o>=e.length||e[o]==="}")throw b(0,"invalid array header");continue}if(l?e[o]==="}":o===e.length)break;throw b(0,"invalid array header")}if(u===0)throw b(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let c=e[o];if(o+=1,c==="\\")o+=1;else if(c==='"')return}}if(i([],!1),o!==e.length)throw b(0,"invalid array header");let a=new Set;for(let c=0;c<n.length;c+=1)for(let l=c+1;l<n.length;l+=1)if(p_(n[c].path,n[l].path)||Xn(n[c].path,n[l].path)||Xn(n[l].path,n[c].path))throw b(0,"duplicate key");for(let c of n){let u=c.path.join("\0");if(a.has(u))throw b(0,"duplicate key");a.add(u)}return n}function ZP(e,t){if(t!==De&&e.includes(De)&&(e.includes("[")||e.includes("{")))return qu(e,De,t);try{return qu(e,t,t)}catch(r){if(t!==De&&r.reason!=="duplicate key")return qu(e,De,t);throw r}}function qu(e,t,r){let n=0;function o(c){let l=[];for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw b(0,"invalid array header");let u=n;for(;n<e.length;){let m=e[n];if(m==='"'){i();continue}if(m===t||m==="{"||m==="}"||m==="[")break;n+=1}let[d,f]=vt(e.slice(u,n),0);if(d===""&&!f)throw b(0,"invalid array header");let p={key:d};if(e[n]==="["){n+=1;let m=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw b(0,"invalid array header");let h=e.slice(m,n);n+=1;let _=UP(h);if(_!==void 0){if(_.delimiter!==r)throw b(0,"invalid array header");p.fixedLength=_.len,p.fixedDelimiter=_.delimiter}else if(f_(h,r))p.listDelimiter=h;else throw b(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,p.children=o(!0),e[n]!=="}"||p.children.length===0)throw b(0,"invalid array header");n+=1}if(l.push(p),e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw b(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw b(0,"invalid array header")}if(l.length===0)throw b(0,"invalid array header");return l}function i(){for(n+=1;n<e.length;){let c=e[n];if(n+=1,c==="\\")n+=1;else if(c==='"')return}}let s=o(!1);if(n!==e.length)throw b(0,"invalid array header");let a=Bu(s);for(let c=0;c<a.length;c+=1)for(let l=c+1;l<a.length;l+=1)if(p_(a[c].path,a[l].path)||Xn(a[c].path,a[l].path)||Xn(a[l].path,a[c].path))throw b(0,"duplicate key");return s}function UP(e){let t=/^[0-9]+/.exec(e)?.[0];if(t===void 0||t.length>1&&t.startsWith("0"))return;let r=e.slice(t.length),n;switch(r){case"":n=De;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(t,10),delimiter:n}}function Bu(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children!==void 0?Bu(r.children,n):[{path:n,listDelimiter:r.listDelimiter}]})}function Li(e,t,r){return e.listDelimiter===void 0?ft(t,r):xt(t,e.listDelimiter,r).map(n=>ft(n,r))}function f_(e,t){return e.length===1&&e!==t&&!/[ \t\r\n"[\]{}:]/.test(e)}function p_(e,t){return e.length===t.length&&Xn(e,t)}function Xn(e,t){return t.every((r,n)=>e[n]===r)}function Mi(e,t){return b(t,e.reason??String(e.message))}function Ke(e,t){let r=o_(t),n=i_(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Qn(o.content,o.number,r);let l;try{l=ji(o.content,Re(o.content,":",o.number))}catch(u){if(r.strict)throw Mi(u,o.number);l=void 0}if(l!==void 0)return KP(l,n,r)}if(i&&Re(o.content,":",o.number)===-1)return ft(o.content.trim(),o.number);let s={index:0},a=Uu(n,s,0,r),c=n[s.index];if(c!==void 0)throw b(c.number,"expected end of document");return r.cyclicDiscriminatedArrays?c_(a):a}function Uu(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 b(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=FP(e,t,r,n);b_(o,s,a,c,n,i.number)}return o}function FP(e,t,r,n){let o=e[t.index],i=o.content,s=Re(i,":",o.number);if(s===-1)throw b(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=Re(a,"[",o.number),u=Re(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){Qn(a,o.number,n);let m;try{m=d_(a)}catch(_){if(n.strict)throw Mi(_,o.number);t.index+=1;let w=Zu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw b(o.number,"expected keyed map rows");let h=VP(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){Qn(a,o.number,n);let m;try{m=ji(a,s)}catch(_){if(n.strict)throw Mi(_,o.number);t.index+=1;let w=Zu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw b(o.number,"expected non-empty field name");let h=Fu(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=vt(a,o.number);if(d===""&&!f)throw b(o.number,"expected non-empty field name");t.index+=1;let p=Zu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function Zu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return ft(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?Uu(e,t,r+1,i):{}}function VP(e,t,r,n,o){let i={};for(r.index+=1;r.index<t.length;){let s=t[r.index];if(s.depth<n)break;if(s.depth>n)throw b(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw b(s.number,"blank line inside keyed map");let a=Re(s.content,":",s.number);if(a===-1)throw b(s.number,"expected `key: value`");let[c,l]=vt(s.content.slice(0,a),s.number);if(c===""&&!l)throw b(s.number,"expected non-empty field name");let u=xt(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw b(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{Br(d,f.path,Li(f,u[p],s.number),o,s.number)}),b_(i,c,l,d,o,s.number),r.index+=1}return i}function KP(e,t,r){let n=t[0],o=Re(n.content,":",n.number);if(o===-1)throw b(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=Fu(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw b(c.number,"expected end of document");return a}function Fu(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 b(s,"expected tabular rows");return HP(e,e.fields,r,n,o+1,i)}if(a!==""){let c=xt(a,e.delimiter,s).map(l=>ft(l,s));if(c.length!==e.len)throw b(s,"array length mismatch");return c}return ez(e,r,n,o+1,i)}function HP(e,t,r,n,o,i){if(e.fieldTree!==void 0&&QP(e.fieldTree))return WP(e,r,n,o,i);let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw Mr(r,n.index);if(c.depth<o)break;if(c.depth>o)throw b(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw b(c.number,"blank line inside array");if(!qr(c.content,e.delimiter,c.number))break;let l=xt(c.content,e.delimiter,c.number);if(l.length!==t.length)throw b(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{Br(u,d.path,Li(d,l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw Mr(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&qr(a.content,e.delimiter,a.number))throw b(a.number,"array length mismatch");return s}function WP(e,t,r,n,o){return m_(e.len,e.fieldTree,e.delimiter,t,r,n,o,!0)}function m_(e,t,r,n,o,i,s,a){let c=[],l=g_(e,t,r,n,o.index,i,s);for(;c.length<e;){let d=n[o.index];if(d===void 0)throw Mr(n,o.index);if(d.depth<i)break;if(d.depth>i)throw b(d.number,"invalid indentation");if(d.blankBefore&&s.strict)throw b(d.number,"blank line inside array");if(!qr(d.content,r,d.number))break;let f=xt(d.content,r,d.number),p={cellIndex:0,nextIndex:o.index+1,flatWidth:qi(t),childTableFields:l},m=h_(t,f,d.number,n,p,i+1,r,s);if(p.cellIndex!==f.length)throw b(d.number,"array row length mismatch");c.push(YP(t,m,a)),o.index=p.nextIndex}if(c.length!==e)throw Mr(n,o.index);let u=n[o.index];if(u!==void 0&&u.depth>=i&&qr(u.content,r,u.number))throw b(u.number,"array length mismatch");return c}function h_(e,t,r,n,o,i,s,a){let c={};return e.forEach((l,u)=>{let d=e.slice(u+1),f=GP(l,d,t,r,n,o,i,s,a);Br(c,[l.key],f,a,r)}),c}function GP(e,t,r,n,o,i,s,a,c){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>r.length)throw b(n,"array row length mismatch");let u=r.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(d=>ft(d,n));return i.cellIndex+=e.fixedLength,u}if(e.children!==void 0){let u=qi(e.children),d=r[i.cellIndex],f=__(d),p=r.length-i.cellIndex-1,m=o[i.nextIndex],h=m!==void 0&&m.depth===s,_=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(_===void 0?f!==void 0&&(h||r.length!==i.flatWidth&&p<u+XP(t)):_){if(f===void 0)throw b(n,"array row length mismatch");return i.cellIndex+=1,m_(f,e.children,a,o,{get index(){return i.nextIndex},set index(x){i.nextIndex=x}},s,c,!1)}return h_(e.children,r,n,o,i,s,a,c)}let l=r[i.cellIndex];if(l===void 0)throw b(n,"array row length mismatch");return i.cellIndex+=1,Li(e,l,n)}function g_(e,t,r,n,o,i,s){let a=t.filter(u=>u.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let c,l=1<<a.length;for(let u=0;u<l;u+=1){let d=new Set;a.forEach((p,m)=>{u&1<<m&&d.add(p)});let f=y_(e,t,d,r,n,o,i,s);f!==void 0&&(c===void 0||f.consumedChildRows>c.consumedChildRows||f.consumedChildRows===c.consumedChildRows&&d.size<c.childTableFields.size)&&(c={childTableFields:d,consumedChildRows:f.consumedChildRows})}return c?.childTableFields}function y_(e,t,r,n,o,i,s,a){let c=i,l=0;try{for(let d=0;d<e;d+=1){let f=o[c];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!qr(f.content,n,f.number))return;let p=xt(f.content,n,f.number),m=JP(t,r,p,n,o,c+1,s+1,a);if(m===void 0||o[m.nextIndex]?.depth>s)return;l+=m.consumedChildRows,c=m.nextIndex}let u=o[c];if(u!==void 0&&u.depth>=s&&qr(u.content,n,u.number))return}catch{return}return{nextIndex:c,consumedChildRows:l}}function JP(e,t,r,n,o,i,s,a){let c=0,l=i,u=0;for(let d of e){if(d.fixedLength!==void 0)c+=d.fixedLength;else if(d.children!==void 0)if(t.has(d)){let f=__(r[c]);if(f===void 0)return;c+=1;let p=g_(f,d.children,n,o,l,s,a);if(p===void 0)return;let m=y_(f,d.children,p,n,o,l,s,a);if(m===void 0)return;l=m.nextIndex,u+=f+m.consumedChildRows}else c+=qi(d.children);else c+=1;if(c>r.length)return}if(c===r.length)return{nextIndex:l,consumedChildRows:u}}function YP(e,t,r){return r&&e.length===1&&e[0].fixedLength!==void 0?t[e[0].key]:t}function __(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function QP(e){return e.some(t=>t.fixedLength!==void 0||t.children!==void 0)}function qi(e){return e.reduce((t,r)=>t+w_(r),0)}function w_(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?qi(e.children):1}function XP(e){return e.reduce((t,r)=>r.children!==void 0?t+1:t+w_(r),0)}function qr(e,t,r){let n=Re(e,":",r);if(n===-1)return!0;let o=Re(e,t,r);return o===-1?!1:o<n}function ez(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 Mr(t,r.index);if(a.depth>n)throw b(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw b(a.number,"blank line inside array");i.push(tz(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw b(s.number,"array length mismatch");return i}function tz(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=Re(i,":",o.number);Qn(i,o.number,n);let a;try{a=ji(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return Fu(a,c,e,t,r,n)}}if(Re(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 Uu(s,{index:0},r+1,n)}return t.index+=1,ft(i,o.number)}function b_(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(rz)){Br(e,s,n,o,i);return}}Br(e,[t],n,o,i)}function Br(e,t,r,n,o){mt(t.length-1,o,n);let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw b(o,"duplicate key");pt(e,i,r);return}if(s&&!ue(e[i])){if(n.strict)throw b(o,"path expansion conflict");pt(e,i,{})}else s||pt(e,i,{});Br(e[i],t.slice(1),r,n,o)}function rz(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function He(e,t={}){let r=t.maxDepth??1e3,n=t.delimiter??De;if(![De,"|"," "].includes(n))throw b(0,"invalid array header");let o={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0,primitiveArrayColumns:t.primitiveArrayColumns===!0,objectArrayColumns:t.objectArrayColumns===!0,cyclicDiscriminatedArrays:t.cyclicDiscriminatedArrays===!0,delimiter:n,maxDepth:r===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(r))};if(o.cyclicDiscriminatedArrays){let s=l_(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?Wu(i,void 0,e,0,!1,o):ue(e)?v_(i,e,0,o):i.push(je(e,n)),i.join("")}function Zr(e,t){e.push(" ".repeat(t*2))}function v_(e,t,r,n){mt(r,0,n);for(let[o,i]of Object.entries(t))Zr(e,r),Ku(e,o,i,r,n)}function Ku(e,t,r,n,o){if(mt(n,0,o),Array.isArray(r)){Wu(e,t,r,n,!1,o);return}if(ue(r)){let i=o.keyedMapCollapse?oz(r,o,n+1):void 0;if(i!==void 0){e.push(ve(t),"{",Gu(o.delimiter),i.fields.map(s=>Qu(s,o.delimiter)).join(o.delimiter),`}:
|
|
47
|
-
`);for(let[s,a]of Object.entries(r)){
|
|
46
|
+
`)}function VP(e){return e!==""&&Mu(e)}function Lu(e,t,r,n=new Set){if(!Mu(t))return!1;if(kt(e))return r[t]=e,!0;if(Array.isArray(e)){if(n.has(e))return!1;n.add(e),r[`${t}.length`]=e.length;let o=e.every((i,s)=>Lu(i,`${t}.${s}`,r,n));return n.delete(e),o}if(ue(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&Lu(s,`${t}.${i}`,r,n));return n.delete(e),o}return!1}function KP(e){let t=Object.keys(e[0]??{});if(e.every(r=>HP(Object.keys(r),t)))return t.every(Mu)?t:void 0}function HP(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Mu(e){return e.split(".").every(t=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(t))}function qr(e,t){let r=e[t]??e[e.length-1];return b(r===void 0?1:r.number,"array length mismatch")}function Di(e,t){if(t===-1)throw b(0,"array header missing colon");let r=e.slice(0,t),n=Re(r,"[",0);if(n===-1)throw b(0,"invalid array header");let o,i;try{[o,i]=vt(r.slice(0,n),0)}catch{throw b(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw b(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 b(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 b(0,"invalid array header")}let f=s.slice(a+1),p,m;if(f==="")p=void 0,m=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{m=GP(f.slice(1,-1),d),p=Bu(m)}catch(h){throw b(0,h.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p,fieldTree:m}}function d_(e){let t=Re(e,"{",0);if(t===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let r,n;try{[r,n]=vt(e.slice(0,t),0)}catch{throw b(0,"invalid keyed map header")}if(r===""&&!n)throw b(0,"expected non-empty field name");let o=e.slice(t+1,-1),i=De;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=WP(o,i,i)}catch(a){throw b(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:i,fields:s}}function WP(e,t,r){let n=[],o=0;function i(c,l){let u=0;for(;o<e.length&&!(l&&e[o]==="}");){if(e[o]===t||e[o]==="}")throw b(0,"invalid array header");let d=o;for(;o<e.length;){let m=e[o];if(m==='"'){s();continue}if(m===t||m==="{"||m==="}"||m==="[")break;o+=1}let[f,p]=vt(e.slice(d,o),0);if(f===""&&!p)throw b(0,"invalid array header");if(u+=1,e[o]==="["){o+=1;let m=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let h=e.slice(m,o);if(!f_(h,r))throw b(0,"invalid array header");o+=1,n.push({path:[...c,f],listDelimiter:h})}else if(e[o]==="{"){o+=1;let m=n.length;if(i([...c,f],!0),e[o]!=="}"||n.length===m)throw b(0,"invalid array header");o+=1}else n.push({path:[...c,f],listDelimiter:void 0});if(e[o]===t){if(o+=1,o>=e.length||e[o]==="}")throw b(0,"invalid array header");continue}if(l?e[o]==="}":o===e.length)break;throw b(0,"invalid array header")}if(u===0)throw b(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let c=e[o];if(o+=1,c==="\\")o+=1;else if(c==='"')return}}if(i([],!1),o!==e.length)throw b(0,"invalid array header");let a=new Set;for(let c=0;c<n.length;c+=1)for(let l=c+1;l<n.length;l+=1)if(p_(n[c].path,n[l].path)||Xn(n[c].path,n[l].path)||Xn(n[l].path,n[c].path))throw b(0,"duplicate key");for(let c of n){let u=c.path.join("\0");if(a.has(u))throw b(0,"duplicate key");a.add(u)}return n}function GP(e,t){if(t!==De&&e.includes(De)&&(e.includes("[")||e.includes("{")))return qu(e,De,t);try{return qu(e,t,t)}catch(r){if(t!==De&&r.reason!=="duplicate key")return qu(e,De,t);throw r}}function qu(e,t,r){let n=0;function o(c){let l=[];for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw b(0,"invalid array header");let u=n;for(;n<e.length;){let m=e[n];if(m==='"'){i();continue}if(m===t||m==="{"||m==="}"||m==="[")break;n+=1}let[d,f]=vt(e.slice(u,n),0);if(d===""&&!f)throw b(0,"invalid array header");let p={key:d};if(e[n]==="["){n+=1;let m=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw b(0,"invalid array header");let h=e.slice(m,n);n+=1;let _=JP(h);if(_!==void 0){if(_.delimiter!==r)throw b(0,"invalid array header");p.fixedLength=_.len,p.fixedDelimiter=_.delimiter}else if(f_(h,r))p.listDelimiter=h;else throw b(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,p.children=o(!0),e[n]!=="}"||p.children.length===0)throw b(0,"invalid array header");n+=1}if(l.push(p),e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw b(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw b(0,"invalid array header")}if(l.length===0)throw b(0,"invalid array header");return l}function i(){for(n+=1;n<e.length;){let c=e[n];if(n+=1,c==="\\")n+=1;else if(c==='"')return}}let s=o(!1);if(n!==e.length)throw b(0,"invalid array header");let a=Bu(s);for(let c=0;c<a.length;c+=1)for(let l=c+1;l<a.length;l+=1)if(p_(a[c].path,a[l].path)||Xn(a[c].path,a[l].path)||Xn(a[l].path,a[c].path))throw b(0,"duplicate key");return s}function JP(e){let t=/^[0-9]+/.exec(e)?.[0];if(t===void 0||t.length>1&&t.startsWith("0"))return;let r=e.slice(t.length),n;switch(r){case"":n=De;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(t,10),delimiter:n}}function Bu(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children!==void 0?Bu(r.children,n):[{path:n,listDelimiter:r.listDelimiter}]})}function ji(e,t,r){return e.listDelimiter===void 0?ft(t,r):xt(t,e.listDelimiter,r).map(n=>ft(n,r))}function f_(e,t){return e.length===1&&e!==t&&!/[ \t\r\n"[\]{}:]/.test(e)}function p_(e,t){return e.length===t.length&&Xn(e,t)}function Xn(e,t){return t.every((r,n)=>e[n]===r)}function Li(e,t){return b(t,e.reason??String(e.message))}function Ke(e,t){let r=o_(t),n=i_(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Qn(o.content,o.number,r);let l;try{l=Di(o.content,Re(o.content,":",o.number))}catch(u){if(r.strict)throw Li(u,o.number);l=void 0}if(l!==void 0)return XP(l,n,r)}if(i&&Re(o.content,":",o.number)===-1)return ft(o.content.trim(),o.number);let s={index:0},a=Uu(n,s,0,r),c=n[s.index];if(c!==void 0)throw b(c.number,"expected end of document");return r.cyclicDiscriminatedArrays?c_(a):a}function Uu(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 b(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=YP(e,t,r,n);b_(o,s,a,c,n,i.number)}return o}function YP(e,t,r,n){let o=e[t.index],i=o.content,s=Re(i,":",o.number);if(s===-1)throw b(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=Re(a,"[",o.number),u=Re(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){Qn(a,o.number,n);let m;try{m=d_(a)}catch(_){if(n.strict)throw Li(_,o.number);t.index+=1;let w=Zu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw b(o.number,"expected keyed map rows");let h=QP(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){Qn(a,o.number,n);let m;try{m=Di(a,s)}catch(_){if(n.strict)throw Li(_,o.number);t.index+=1;let w=Zu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw b(o.number,"expected non-empty field name");let h=Fu(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=vt(a,o.number);if(d===""&&!f)throw b(o.number,"expected non-empty field name");t.index+=1;let p=Zu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function Zu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return ft(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?Uu(e,t,r+1,i):{}}function QP(e,t,r,n,o){let i={};for(r.index+=1;r.index<t.length;){let s=t[r.index];if(s.depth<n)break;if(s.depth>n)throw b(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw b(s.number,"blank line inside keyed map");let a=Re(s.content,":",s.number);if(a===-1)throw b(s.number,"expected `key: value`");let[c,l]=vt(s.content.slice(0,a),s.number);if(c===""&&!l)throw b(s.number,"expected non-empty field name");let u=xt(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw b(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{Zr(d,f.path,ji(f,u[p],s.number),o,s.number)}),b_(i,c,l,d,o,s.number),r.index+=1}return i}function XP(e,t,r){let n=t[0],o=Re(n.content,":",n.number);if(o===-1)throw b(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=Fu(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw b(c.number,"expected end of document");return a}function Fu(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 b(s,"expected tabular rows");return ez(e,e.fields,r,n,o+1,i)}if(a!==""){let c=xt(a,e.delimiter,s).map(l=>ft(l,s));if(c.length!==e.len)throw b(s,"array length mismatch");return c}return az(e,r,n,o+1,i)}function ez(e,t,r,n,o,i){if(e.fieldTree!==void 0&&iz(e.fieldTree))return tz(e,r,n,o,i);let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw qr(r,n.index);if(c.depth<o)break;if(c.depth>o)throw b(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw b(c.number,"blank line inside array");if(!Br(c.content,e.delimiter,c.number))break;let l=xt(c.content,e.delimiter,c.number);if(l.length!==t.length)throw b(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{Zr(u,d.path,ji(d,l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw qr(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Br(a.content,e.delimiter,a.number))throw b(a.number,"array length mismatch");return s}function tz(e,t,r,n,o){return m_(e.len,e.fieldTree,e.delimiter,t,r,n,o,!0)}function m_(e,t,r,n,o,i,s,a){let c=[],l=g_(e,t,r,n,o.index,i,s);for(;c.length<e;){let d=n[o.index];if(d===void 0)throw qr(n,o.index);if(d.depth<i)break;if(d.depth>i)throw b(d.number,"invalid indentation");if(d.blankBefore&&s.strict)throw b(d.number,"blank line inside array");if(!Br(d.content,r,d.number))break;let f=xt(d.content,r,d.number),p={cellIndex:0,nextIndex:o.index+1,flatWidth:Mi(t),childTableFields:l},m=h_(t,f,d.number,n,p,i+1,r,s);if(p.cellIndex!==f.length)throw b(d.number,"array row length mismatch");c.push(oz(t,m,a)),o.index=p.nextIndex}if(c.length!==e)throw qr(n,o.index);let u=n[o.index];if(u!==void 0&&u.depth>=i&&Br(u.content,r,u.number))throw b(u.number,"array length mismatch");return c}function h_(e,t,r,n,o,i,s,a){let c={};return e.forEach((l,u)=>{let d=e.slice(u+1),f=rz(l,d,t,r,n,o,i,s,a);Zr(c,[l.key],f,a,r)}),c}function rz(e,t,r,n,o,i,s,a,c){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>r.length)throw b(n,"array row length mismatch");let u=r.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(d=>ft(d,n));return i.cellIndex+=e.fixedLength,u}if(e.children!==void 0){let u=Mi(e.children),d=r[i.cellIndex],f=__(d),p=r.length-i.cellIndex-1,m=o[i.nextIndex],h=m!==void 0&&m.depth===s,_=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(_===void 0?f!==void 0&&(h||r.length!==i.flatWidth&&p<u+sz(t)):_){if(f===void 0)throw b(n,"array row length mismatch");return i.cellIndex+=1,m_(f,e.children,a,o,{get index(){return i.nextIndex},set index(x){i.nextIndex=x}},s,c,!1)}return h_(e.children,r,n,o,i,s,a,c)}let l=r[i.cellIndex];if(l===void 0)throw b(n,"array row length mismatch");return i.cellIndex+=1,ji(e,l,n)}function g_(e,t,r,n,o,i,s){let a=t.filter(u=>u.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let c,l=1<<a.length;for(let u=0;u<l;u+=1){let d=new Set;a.forEach((p,m)=>{u&1<<m&&d.add(p)});let f=y_(e,t,d,r,n,o,i,s);f!==void 0&&(c===void 0||f.consumedChildRows>c.consumedChildRows||f.consumedChildRows===c.consumedChildRows&&d.size<c.childTableFields.size)&&(c={childTableFields:d,consumedChildRows:f.consumedChildRows})}return c?.childTableFields}function y_(e,t,r,n,o,i,s,a){let c=i,l=0;try{for(let d=0;d<e;d+=1){let f=o[c];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Br(f.content,n,f.number))return;let p=xt(f.content,n,f.number),m=nz(t,r,p,n,o,c+1,s+1,a);if(m===void 0||o[m.nextIndex]?.depth>s)return;l+=m.consumedChildRows,c=m.nextIndex}let u=o[c];if(u!==void 0&&u.depth>=s&&Br(u.content,n,u.number))return}catch{return}return{nextIndex:c,consumedChildRows:l}}function nz(e,t,r,n,o,i,s,a){let c=0,l=i,u=0;for(let d of e){if(d.fixedLength!==void 0)c+=d.fixedLength;else if(d.children!==void 0)if(t.has(d)){let f=__(r[c]);if(f===void 0)return;c+=1;let p=g_(f,d.children,n,o,l,s,a);if(p===void 0)return;let m=y_(f,d.children,p,n,o,l,s,a);if(m===void 0)return;l=m.nextIndex,u+=f+m.consumedChildRows}else c+=Mi(d.children);else c+=1;if(c>r.length)return}if(c===r.length)return{nextIndex:l,consumedChildRows:u}}function oz(e,t,r){return r&&e.length===1&&e[0].fixedLength!==void 0?t[e[0].key]:t}function __(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function iz(e){return e.some(t=>t.fixedLength!==void 0||t.children!==void 0)}function Mi(e){return e.reduce((t,r)=>t+w_(r),0)}function w_(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Mi(e.children):1}function sz(e){return e.reduce((t,r)=>r.children!==void 0?t+1:t+w_(r),0)}function Br(e,t,r){let n=Re(e,":",r);if(n===-1)return!0;let o=Re(e,t,r);return o===-1?!1:o<n}function az(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 qr(t,r.index);if(a.depth>n)throw b(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw b(a.number,"blank line inside array");i.push(cz(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw b(s.number,"array length mismatch");return i}function cz(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=Re(i,":",o.number);Qn(i,o.number,n);let a;try{a=Di(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return Fu(a,c,e,t,r,n)}}if(Re(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 Uu(s,{index:0},r+1,n)}return t.index+=1,ft(i,o.number)}function b_(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(uz)){Zr(e,s,n,o,i);return}}Zr(e,[t],n,o,i)}function Zr(e,t,r,n,o){mt(t.length-1,o,n);let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw b(o,"duplicate key");pt(e,i,r);return}if(s&&!ue(e[i])){if(n.strict)throw b(o,"path expansion conflict");pt(e,i,{})}else s||pt(e,i,{});Zr(e[i],t.slice(1),r,n,o)}function uz(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function He(e,t={}){let r=t.maxDepth??1e3,n=t.delimiter??De;if(![De,"|"," "].includes(n))throw b(0,"invalid array header");let o={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0,primitiveArrayColumns:t.primitiveArrayColumns===!0,objectArrayColumns:t.objectArrayColumns===!0,cyclicDiscriminatedArrays:t.cyclicDiscriminatedArrays===!0,delimiter:n,maxDepth:r===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(r))};if(o.cyclicDiscriminatedArrays){let s=l_(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?Wu(i,void 0,e,0,!1,o):ue(e)?v_(i,e,0,o):i.push(je(e,n)),i.join("")}function Ur(e,t){e.push(" ".repeat(t*2))}function v_(e,t,r,n){mt(r,0,n);for(let[o,i]of Object.entries(t))Ur(e,r),Ku(e,o,i,r,n)}function Ku(e,t,r,n,o){if(mt(n,0,o),Array.isArray(r)){Wu(e,t,r,n,!1,o);return}if(ue(r)){let i=o.keyedMapCollapse?dz(r,o,n+1):void 0;if(i!==void 0){e.push(ve(t),"{",Gu(o.delimiter),i.fields.map(s=>Qu(s,o.delimiter)).join(o.delimiter),`}:
|
|
47
|
+
`);for(let[s,a]of Object.entries(r)){Ur(e,n+1);let c=[];e.push(ve(s),": ",i.paths.map(l=>Xu(Yu(a,l.path),l,o.delimiter,o,c,n+2)).join(o.delimiter),`
|
|
48
48
|
`),e.push(...c)}return}e.push(ve(t),`:
|
|
49
49
|
`),v_(e,r,n+1,o);return}e.push(ve(t),": ",je(r,o.delimiter),`
|
|
50
50
|
`)}function Wu(e,t,r,n,o,i){if(mt(n,0,i),r.length===0){t!==void 0?e.push(ve(t),`: []
|
|
@@ -52,41 +52,44 @@ var $b=Object.create;var fs=Object.defineProperty;var Sb=Object.getOwnPropertyDe
|
|
|
52
52
|
`):e.push(`[]
|
|
53
53
|
`);return}if(r.every(kt)){Vu(e,t,r.length,void 0,i.delimiter),e.push(" "),e.push(r.map(a=>je(a,i.delimiter)).join(i.delimiter)),e.push(`
|
|
54
54
|
`);return}let s=o?void 0:x_(r,i,n+1);if(s!==void 0){Vu(e,t,r.length,s.fields,i.delimiter),e.push(`
|
|
55
|
-
`);for(let a of r){
|
|
55
|
+
`);for(let a of r){Ur(e,n+1);let c=[];e.push(s.paths.map(l=>Xu(Yu(a,l.path),l,i.delimiter,i,c,n+2)).join(i.delimiter)),e.push(`
|
|
56
56
|
`),e.push(...c)}return}Vu(e,t,r.length,void 0,i.delimiter),e.push(`
|
|
57
|
-
`);for(let a of r)
|
|
58
|
-
`);return}e.push("- "),Ku(e,o[0][0],o[0][1],r+1,n);for(let[i,s]of o.slice(1))
|
|
59
|
-
`)}function Vu(e,t,r,n,o){t!==void 0&&e.push(ve(t)),e.push("[",String(r),Gu(o),"]"),n!==void 0&&e.push("{",n.map(i=>Qu(i,o)).join(o),"}"),e.push(":")}function Gu(e){return e===De?"":e}function x_(e,t,r){let n=
|
|
60
|
-
`),e.push(...s)}}function
|
|
57
|
+
`);for(let a of r)Ur(e,n+1),lz(e,a,n+1,i)}function lz(e,t,r,n){if(mt(r,0,n),Array.isArray(t)){e.push("- "),Wu(e,void 0,t,r,!0,n);return}if(ue(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
|
|
58
|
+
`);return}e.push("- "),Ku(e,o[0][0],o[0][1],r+1,n);for(let[i,s]of o.slice(1))Ur(e,r+1),Ku(e,i,s,r+1,n);return}e.push("- ",je(t,n.delimiter),`
|
|
59
|
+
`)}function Vu(e,t,r,n,o){t!==void 0&&e.push(ve(t)),e.push("[",String(r),Gu(o),"]"),n!==void 0&&e.push("{",n.map(i=>Qu(i,o)).join(o),"}"),e.push(":")}function Gu(e){return e===De?"":e}function x_(e,t,r){let n=fz(e,t);if(n!==void 0)return n;let o=Hu(e.map(i=>({value:i})),t,r);return o===void 0?void 0:{fields:o,paths:Ju(o)}}function dz(e,t,r){let n=Object.values(e);if(!(n.length<2))return x_(n,t,r)}function Hu(e,t,r){mt(r,0,t);let n=e[0]?.value;if(!ue(n))return;let o=Object.keys(n).map(i=>({key:i}));if(o.length!==0){for(let{value:i}of e)if(!ue(i)||Object.keys(i).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(i,a.key)))return;for(let i of o){let s=e.map(({value:c})=>({value:c[i.key]}));if(s.every(({value:c})=>kt(c)))continue;if(t.primitiveArrayColumns&&s.every(({value:c})=>Array.isArray(c)&&c.every(kt))){i.listDelimiter=";";continue}if(t.objectArrayColumns&&s.every(({value:c})=>Array.isArray(c))){let c=k_(s.map(({value:u})=>u));if(c!==void 0){i.fixedLength=c.fixedLength,i.fixedDelimiter=t.delimiter;continue}let l=Hu(s.flatMap(({value:u})=>u.map(d=>({value:d}))),t,r+1);if(l!==void 0){i.children=l,i.childTable=!0;continue}}if(!t.nestedTabularHeaders)return;let a=Hu(s,t,r+1);if(a===void 0)return;i.children=a}return o}}function fz(e,t){if(!t.objectArrayColumns)return;let r=k_(e);return r===void 0?void 0:{fields:[{key:"values",fixedLength:r.fixedLength,fixedDelimiter:t.delimiter}],paths:[{path:[],fixedLength:r.fixedLength}]}}function k_(e){let t=e[0]?.length;if(!(!Number.isInteger(t)||t===0)&&e.every(r=>Array.isArray(r)&&r.length===t&&r.every(kt)))return{fixedLength:t}}function Ju(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.childTable===!0?[{path:n,childFields:r.children}]:r.fixedLength!==void 0?[{path:n,fixedLength:r.fixedLength}]:r.children===void 0?[{path:n,listDelimiter:r.listDelimiter}]:Ju(r.children,n)})}function Yu(e,t){let r=e;for(let n of t)r=r[n];return r}function Qu(e,t){return e.listDelimiter!==void 0?`${ve(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${ve(e.key)}[${e.fixedLength}${Gu(t)}]`:e.children===void 0?ve(e.key):`${ve(e.key)}{${e.children.map(r=>Qu(r,t)).join(t)}}`}function Xu(e,t,r,n,o,i){return t.childFields!==void 0?(pz(o,e,t.childFields,n,i),String(e.length)):t.fixedLength!==void 0?e.map(s=>je(s,r)).join(r):t.listDelimiter===void 0?je(e,r):e.map(s=>mz(s,r,t.listDelimiter)).join(t.listDelimiter)}function pz(e,t,r,n,o){for(let i of t){Ur(e,o);let s=[];e.push(Ju(r).map(a=>Xu(Yu(i,a.path),a,n.delimiter,n,s,o+1)).join(n.delimiter)),e.push(`
|
|
60
|
+
`),e.push(...s)}}function mz(e,t,r){return typeof e!="string"?je(e,t):Du(e,t)||e.includes(r)?Ci(e):e}var SZ=new TextEncoder,EZ=new TextDecoder;import{basename as Gw}from"node:path";import{randomUUID as ll}from"node:crypto";import{spawn as Qz}from"node:child_process";import{readFileSync as Xz}from"node:fs";import{mkdir as eO,readFile as tO,rename as $U,rm as Fi,stat as SU,writeFile as EU}from"node:fs/promises";import{dirname as to,join as $t,resolve as dl}from"node:path";import{isAbsolute as rU,join as Fr,resolve as _z}from"node:path";var wz=".red";function bz(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function $_(e){return Fr(bz(e),wz)}function S_(e){return Fr($_(e),"state")}function vz(e){return Fr($_(e),"tmp")}function el(e){return Fr(S_(e),"rsp")}function tl(e){return Fr(S_(e),"red-skills.rdb")}var xz=".red/tmp/red-skills.rdb";function E_(e){return Fr(vz(e),"red-skills.rdb")}function T_(e,t){let r=tl(e);if(t(r))return r;let n=E_(e);if(t(n))throw rl();return r}function R_(e,t){return t===xz||_z(e,t)===E_(e)}function rl(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}import{createHash as Sz}from"node:crypto";import{constants as ol}from"node:fs";import{mkdir as q_,open as Ez,readFile as Tz,rm as B_,stat as Rz}from"node:fs/promises";import{createConnection as Pz}from"node:net";import{tmpdir as zz}from"node:os";import{dirname as Z_,join as eo}from"node:path";var kz="toon";function O_(e){return e.trimStart().startsWith("{")?"json":"toon"}function A_(e){let t=0;for(;e[t]===`
|
|
61
61
|
`||e[t]==="\r";)t+=1;let r=e.slice(t);if(r==="")return null;let n=O_(r);if(n==="json"){let i=r.indexOf(`
|
|
62
62
|
`);return i<0?null:{frame:r.slice(0,i),dialect:n,rest:r.slice(i+1)}}let o=r.indexOf(`
|
|
63
63
|
|
|
64
|
-
`);return o<0?null:{frame:r.slice(0,o+1),dialect:n,rest:r.slice(o+2)}}function I_(e){let t=O_(e)==="json"?nl:P_,r=t===nl?P_:nl;try{return t(e)}catch(n){try{return r(e)}catch{throw n}}}function nl(e){return JSON.parse(e)}function P_(e){return Ke(e)}function C_(e,t){if(t==="toon"){let r
|
|
64
|
+
`);return o<0?null:{frame:r.slice(0,o+1),dialect:n,rest:r.slice(o+2)}}function I_(e){let t=O_(e)==="json"?nl:P_,r=t===nl?P_:nl;try{return t(e)}catch(n){try{return r(e)}catch{throw n}}}function nl(e){return JSON.parse(e)}function P_(e){return Ke(e)}function C_(e,t){if(t==="toon"){let r=$z(e);if(r!==null)return r.endsWith(`
|
|
65
65
|
`)?`${r}
|
|
66
66
|
`:`${r}
|
|
67
67
|
|
|
68
68
|
`}return`${JSON.stringify(e)}
|
|
69
|
-
`}function
|
|
69
|
+
`}function $z(e){try{let t=JSON.stringify(e);if(t===void 0)return null;let r=He(JSON.parse(t));return r.trim()===""?null:r}catch{return null}}function N_(e,t){return!z_(e)||!z_(t)||t.ok!==!1?!1:typeof e.id=="string"&&typeof t.id=="string"&&t.id!==e.id}function z_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var D_=new Set;function j_(e){return D_.has(e)?"json":kz}function L_(e){D_.add(e)}var Oz=108;async function U_(e,t,r="resident server"){let n=e.wire,o=n??j_(e.socketPath),i=await M_(e,t,r,o);return n||o==="json"||!N_(t,i)?i:(L_(e.socketPath),await M_(e,t,r,"json"))}async function M_(e,t,r,n){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=Pz(e.socketPath),c=!1,l="",u=setTimeout(()=>{d(()=>s(new Error(`${r} timed out`))),a.destroy()},o);function d(f){c||(c=!0,clearTimeout(u),f())}a.on("connect",()=>{a.write(C_(t,n))}),a.on("data",f=>{l+=f.toString("utf8");let p=A_(l);p&&(l=p.rest,d(()=>{try{i(I_(p.frame))}catch(m){s(m)}}),a.end())}),a.on("error",f=>d(()=>s(f))),a.on("close",()=>{c||d(()=>s(new Error(`${r} closed without response`)))})})}async function F_(e){await q_(Z_(e),{recursive:!0,mode:448});try{return await Ez(e,ol.O_CREAT|ol.O_EXCL|ol.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}var Az=6e4,V_="resident-spawn-lock v1",Iz=3;async function K_(e,t={}){let r=t.maxAgeMs??Az,n=t.now??Date.now,o=t.pid??process.pid,i=t.isPidAlive??sr;await q_(Z_(e),{recursive:!0,mode:448});let s=[];for(let a=0;;a+=1){let c=await F_(e);if(c)return await c.writeFile(`${V_} pid=${o} taken=${new Date(n()).toISOString()}
|
|
70
|
+
`).catch(()=>{}),{acquired:!0,lockPath:e,handle:c,reaped:s};let l=await Nz(e),u=await jz(e,l,n());if(a>=Iz||u==null)return{acquired:!1,lockPath:e,holder:l,ageMs:u};let d=Cz(l,u,r,i);if(d==null)return{acquired:!1,lockPath:e,holder:l,ageMs:u};let f={lockPath:e,reason:d,holder:l,ageMs:u};await B_(e,{force:!0}),s.push(f),t.onReap?.(f)}}async function H_(e){await e.handle.close().catch(()=>{}),await B_(e.lockPath,{force:!0})}function Cz(e,t,r,n){return e==null?t>r?"unattributed":null:n(e.pid)?t>r?"aged-out":null:"holder-dead"}function W_(e){let t=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,r=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${r}, ${t}. If that process is gone, remove the file to clear it`}async function Nz(e){try{return Dz(await Tz(e,"utf8"))}catch{return null}}function Dz(e){let t=e.split(`
|
|
71
|
+
`,1)[0]?.trim()??"";if(!t.startsWith(V_))return null;let r=Number(/\bpid=(\d+)\b/.exec(t)?.[1]??""),n=/\btaken=(\S+)/.exec(t)?.[1]??"";return!Number.isInteger(r)||r<=0||!Number.isFinite(Date.parse(n))?null:{pid:r,takenAt:n}}async function jz(e,t,r){let n=t==null?Number.NaN:Date.parse(t.takenAt);if(Number.isFinite(n))return Math.max(0,r-n);try{return Math.max(0,r-(await Rz(e)).mtimeMs)}catch{return null}}function sr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function G_(e,t=1e3){if(!sr(e))return;try{process.kill(e,"SIGTERM")}catch{return}let r=Date.now()+t;for(;Date.now()<r;){if(!sr(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}var Lz="/tmp";function J_(e){let t=e.env??process.env,r=Sz("sha256").update(e.key).digest("hex").slice(0,20),n=c=>eo(c,e.socketFileName).length<Oz,o=t.XDG_RUNTIME_DIR;if(o){let c=eo(o,"red-skills",r);if(n(c))return c}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=eo(`red-skills-${i}`,r),a=eo(zz(),s);return n(a)||process.platform==="win32"?a:eo(Lz,s)}async function qi(e,t){return await U_(e,t,"resident rsp server")}import{existsSync as Mz,readdirSync as qz}from"node:fs";import{homedir as Bz}from"node:os";import{basename as sl,dirname as il,join as We,resolve as Bi}from"node:path";var Zi="rsp-resident-entry-unresolved";function Zz(e){return"command"in e}var Ui=class extends Error{code=Zi;searched;callerEntry;constructor(t){super(`${Zi}: no rsp entrypoint found for the resident auto-spawn${t.callerEntry?` (caller entry: ${t.callerEntry})`:""}
|
|
70
72
|
searched:
|
|
71
73
|
${t.searched.map(r=>` ${r}`).join(`
|
|
72
|
-
`)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},
|
|
74
|
+
`)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},ar="rsp.bundle.min.mjs",Uz=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,al=/^rsp-(.+)\.bundle\.min\.mjs$/,Fz=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function Q_(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let r=t.env??process.env,n=t.exists??Mz,o=t.execPath??process.execPath,i=t.execArgv??process.execArgv,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,a=(l,u)=>({command:o,args:[...i,l],source:u});if(r.RSP_BIN)return{command:r.RSP_BIN,args:[],source:"env-rsp-bin"};if(s&&Vz(s))return a(Bi(s),"caller-entry");let c=[];for(let[l,u]of Hz(s,t.rootDir,r,t.listDir??Yz))if(c.push(l),n(l))return a(l,u);return{diagnostic:Zi,searched:c,...s?{callerEntry:Bi(s)}:{}}}function X_(e={},t={}){let r=Q_(e,t);if(Zz(r))return r;throw new Ui(r)}function Vz(e){let t=sl(e);return t===ar||al.test(t)||t==="rsp"||t==="rsp.mjs"||t==="rsp.js"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:Kz(Bi(e))}function Kz(e){let t=il(e);for(let r=0;r<4;r++){if(sl(t)==="rsp")return!0;let n=il(t);if(n===t)return!1;t=n}return!1}function*Hz(e,t,r,n){if(e){let i=il(Bi(e));yield[We(i,ar),"caller-sibling-bundle"];let s=Uz.exec(sl(e));s&&(yield[We(i,`rsp-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[We(i,"..","dist",ar),"caller-sibling-bundle"]}for(let i of Fz){let s=r[i];s&&(yield[We(s,"dist",ar),"plugin-root-bundle"],yield[We(s,"..","..","dist",ar),"plugin-root-bundle"])}t&&(yield[We(t,"dist",ar),"repo-bundle"],yield[We(t,"apps","rsp","dist","cli.js"),"workspace-entry"],yield[We(t,"node_modules","@reddb-io","rsp","dist","cli.js"),"node-modules-entry"]);let o=Wz(r);yield[We(o,ar),"bundle-cache"];for(let i of Gz(o,n))yield[We(o,i),"bundle-cache"]}function Wz(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||We(e.HOME||Bz(),".cache");return We(t,"red-skills","bundles")}function Gz(e,t){return t(e).filter(r=>al.test(r)).sort((r,n)=>Jz(Y_(n),Y_(r)))}function Y_(e){return al.exec(e)?.[1]??""}function Jz(e,t){let r=i=>i.split(".").map(s=>Number.parseInt(s,10)),[n,o]=[r(e),r(t)];for(let i=0;i<Math.max(n.length,o.length);i++){let[s,a]=[n[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(t):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function Yz(e){try{return qz(e)}catch{return[]}}var rO=1,nO=5e3;function Ki(e){let t=hO(e)??dl(e),r=mO(t),n=el(t);return{rootDir:t,socketPath:$t(r,"rsp.sock"),pidPath:$t(r,"rsp.pid"),lockPath:$t(r,"rsp.lock"),wakeLockPath:$t(t,".red","tmp","rsp","wake.lock"),summaryPath:$t(n,"rsp-status-summary.json"),registryPath:$t(n,"rsp-resident.pid.json")}}var Vi=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await oO(this.paths,this.config);let r=await qi(this.paths,{...t,id:ll()});if(!r.ok)throw new Error(r.error);return r.value}};async function oO(e,t){if(await eO(to(e.socketPath),{recursive:!0,mode:448}),await rw(e.socketPath,t))return;await tw(e,t);let r=await K_(e.lockPath,{onReap:n=>process.stderr.write(`rsp: reaped the resident spawn lock ${JSON.stringify(n.lockPath)} (${n.reason}, ${Math.round(n.ageMs/1e3)}s old)
|
|
75
|
+
`)});if(r.acquired)try{if(await rw(e.socketPath,t))return;await tw(e,t),await aO(e.socketPath);let n=cO(e,t);await ew(e.socketPath,n);return}finally{await H_(r)}try{await ew(e.socketPath)}catch(n){throw new Error(`${n instanceof Error?n.message:String(n)}; ${W_(r)}`)}}async function ro(e,t=200){try{return await ow(e,t)!=null}catch{return!1}}async function ow(e,t=200){let r=await qi({socketPath:e,timeoutMs:t},{id:ll(),op:"ping"});return r.ok?sw(r.value)?{version:wO(r.value.version)}:{}:null}async function iO(e){try{let t=dO(await tO(e,"utf8"));return bO(t)?t:null}catch{return null}}async function ew(e,t){let r=Date.now()+sO(),n;for(;Date.now()<r;){if(await ro(e))return;if(t){let o=t.spawnError();if(o)throw new Error(cl("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(cl("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?cl("resident rsp server did not start",t):"resident rsp server did not start")}function sO(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:nO}async function aO(e){await Fi(e,{force:!0})}function cO(e,t){let[r,n]=pO(e,t),o=process.env.RSP_DEBUG==="1",i,s="",a=Qz(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=lO(`${s}${c}`,uO)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var uO=8*1024;function cl(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:
|
|
73
76
|
${o}`),n.join(`
|
|
74
|
-
`)}function
|
|
75
|
-
`)}function
|
|
76
|
-
`)){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
|
|
77
|
-
`,"utf8")),t}async function
|
|
77
|
+
`)}function lO(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function dO(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return Ke(t)}}async function tw(e,t){try{let r=await iO(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!sr(r.pid)){await Fi(e.registryPath,{force:!0});return}if(await ro(r.socket_path,100))return;if(iw(t.clientVersion,r.resident_version)&&(await fO(r.pid,1500),!sr(r.pid))){await Fi(e.registryPath,{force:!0});return}await G_(r.pid),await Fi(e.registryPath,{force:!0})}catch{}}async function fO(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!sr(e))return;await new Promise(n=>setTimeout(n,50))}}function pO(e,t){let r=X_(t,{rootDir:e.rootDir});return[r.command,r.args]}function mO(e){return J_({key:e,socketFileName:"rsp.sock"})}function hO(e){let t=dl(e);for(let r=0;r<32;r++){try{let o=ul($t(t,".git"));if(o!=null)return gO(t,o)??t;if(ul($t(t,".git","HEAD"))!=null||ul($t(t,".red","config.yaml"))!=null)return t}catch{}let n=to(t);if(n===t)return null;t=n}return null}function gO(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=dl(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?to(to(to(n))):null}function ul(e){try{return Xz(e,"utf8")}catch{return null}}async function rw(e,t){let r=await ow(e).catch(()=>null);return r?iw(t.clientVersion,r.version)?(await yO(e,t.clientVersion),await vO(e),!1):!0:!1}async function yO(e,t){try{await qi({socketPath:e,timeoutMs:200},{id:ll(),op:"handover",clientVersion:t})}catch{}}function iw(e,t){return!e||!t?!1:_O(e,t)>0}function _O(e,t){let r=nw(e),n=nw(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function nw(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 sw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wO(e){return typeof e=="string"&&e.length>0?e:void 0}function bO(e){return sw(e)&&e.version===rO&&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 vO(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await ro(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as xO}from"node:child_process";var pl=["supports","contradicts","related_to"];function ml(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 hl(e){return typeof e=="string"&&pl.includes(e)}function Vr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function aw(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
|
|
78
|
+
`)}function kO(e){return{deriveConnections(t){return SO(e,t)}}}function cw(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return kO({command:t,args:EO(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:TO(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function $O(e){let t=JSON.parse(RO(e));return(Array.isArray(t)?t:fl(t)&&Array.isArray(t.connections)?t.connections:[]).filter(PO).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:fl(n.metadata)?n.metadata:void 0}))}async function SO(e,t){let r=xO(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 $O(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function EO(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 TO(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function RO(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function PO(e){return fl(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&hl(e.kind)}function fl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as Hi}from"node:fs";import{mkdir as zO,readFile as gl,writeFile as OO}from"node:fs/promises";import{dirname as yl,isAbsolute as AO,join as Kr,resolve as Mt}from"node:path";var Wi="file://./.red/brain/brain.rdb",IO="RED_BRAIN_ROOT",CO="brain.root";async function NO(e=process.cwd(),t={}){let n=(t.env??process.env)[IO];if(n)return Mt(e,n);let o=await DO(e);if(o)return o;let i=Mt(e),s=null;for(;;){let a=Kr(i,".red");if(Hi(a)&&(s??=i,Hi(Kr(a,"brain"))||Hi(Kr(a,CO))))return i;let c=yl(i);if(c===i)return s??Mt(e);i=c}}async function DO(e){let t=Mt(e);for(;;){let r=Kr(t,".red","config.yaml");try{let o=await gl(r,"utf8"),i=jO(o);if(i)return Mt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=yl(t);if(n===t)return null;t=n}}function jO(e){let t=LO(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 LO(e){let t={},r=[],n=[];for(let o of e.split(`
|
|
79
|
+
`)){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 uw(e){return Kr(Mt(e),".red","brain","config.yaml")}function MO(e){return Kr(Mt(e),".env")}async function qO(e){let t=uw(e);return Hi(t)||(await zO(yl(t),{recursive:!0}),await OO(t,`connection_string: ${Wi}
|
|
80
|
+
`,"utf8")),t}async function BO(e){let t=uw(e);try{let r=await gl(t,"utf8");return ZO(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function ZO(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:Wi};let r=t.slice(18).trim();return{connection_string:lw(r)||Wi}}function lw(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function dw(e=process.cwd()){let t=await NO(e),r=await qO(t),n=await BO(t)??{connection_string:Wi},o=await UO(t),i=n.connection_string,s=FO(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:VO(t,s)}}async function UO(e){let t={...process.env};try{let r=await gl(MO(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=lw(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function FO(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 VO(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return AO(r)?t:`file://${Mt(e,r)}`}import{existsSync as KO}from"node:fs";import{resolve as HO}from"node:path";var WO=7,GO=64*1024*1024;function pw(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(R_(e.rootDir,t))throw rl();return t===tl(e.rootDir)}async function mw(e){let t=Ki(e.rootDir),r=new Vi(t,YO(e.rootDir));return await r.request({op:"ping"}),new _l(r)}function JO(e){return`file://${T_(HO(e),KO)}`}function YO(e){return{storeUri:JO(e),ttlDays:WO,byteBudget:GO}}var _l=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return QO(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:fw(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:fw(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 fw(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function QO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var XO=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",eA=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function hw(e,t){return XO?rA(e,t):eA?oA(e,t):tA(e,t)}async function tA(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 rA(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:nA(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*nA(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 oA(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:iA(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*iA(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 cA}from"node:url";import{dirname as uA,resolve as lA,join as XU}from"node:path";import{existsSync as sA}from"node:fs";import{join as aA}from"node:path";function gw(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=aA(r,"bin",t);if(sA(i))return i;throw new Error(`reddb: binary "${t}" not found.
|
|
78
81
|
expected at: ${i}
|
|
79
82
|
override: set ${n}=/path/to/${t}
|
|
80
83
|
fix: re-run \`pnpm install\` (the postinstall script downloads it),
|
|
81
|
-
or check the postinstall log for a download error.`)}var
|
|
82
|
-
`)).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(
|
|
84
|
+
or check the postinstall log for a download error.`)}var dA=uA(cA(import.meta.url)),fA=lA(dA,"..");function pA(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function yw(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:gw({name:pA(),packageRoot:fA,envVar:"REDDB_BIN"})}var mA=new TextEncoder,hA=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Gi=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(mA.encode(o+`
|
|
85
|
+
`)).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(hA.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 bl(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:/"?gA(e):yA(e)}function gA(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=_A(o),a=r.port?Number(r.port):wl(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 yA(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):wl(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):wl(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 _A(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 wl(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 wA=new Set(["embedded"]),no=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&wA.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:vA(n.value)}async put(t,r,n,o={}){this._guard("put");let i=bA(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 bA(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return _w(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return _w(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function _w(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 vA(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 Hr=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(ww).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${vl(o,t)} = ${kA(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 ${vl(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 ${vl(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 ${xl(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(ww).join(", ")}] FROM ${xl(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(`
|
|
83
86
|
|
|
84
87
|
`)){let u=l.split(`
|
|
85
|
-
`).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function vl(e,t){return`${xl(e)}.${lA(t)}`}function xl(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 lA(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function dA(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 fw(e){return`'${String(e).replace(/'/g,"''")}'`}var io=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${St(t)}`})}push(t,r,n={}){let o=mA(n);return this.client.call("query",{sql:`QUEUE PUSH ${St(t)} ${hA(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${St(t)}${$l(r)}`});return kl(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${St(t)}${$l(r)}`});return kl(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${St(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${St(t)}`})}async readWait(t,r,n={}){let o=fA(t,r,n),i=await this.client.call("query",{sql:o});return kl(i)}};function fA(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=St(e),a=St(t),c=o!=null?` GROUP ${St(o)}`:"",l=i!=null?$l(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function St(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 $l(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 pA(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function mA(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 ${pA(e.priority)}`),e.key!=null&&(t+=` KEY ${Sl(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Sl(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function hA(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Sl(e):JSON.stringify(e)}function Sl(e){return`'${String(e).replace(/'/g,"''")}'`}function kl(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var so=class{constructor(t){this.db=t}async insert(t,r){pw(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ji(t)} DOCUMENT VALUES (${_A(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=gA(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 ${Ji(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){pw(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])=>`${mw(c)} = ${wA(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ji(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 ${Ji(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function pw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function gA(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 Ji(e){return String(e).split(".").map(mw).join(".")}function mw(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 yA(e){return hw(JSON.stringify(e))}function _A(e){return JSON.stringify(e)}function wA(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?yA(e):hw(e)}function hw(e){return`'${String(e).replace(/'/g,"''")}'`}var ao=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){vA(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(gw).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${qt(o)} ${qt(t)} = ${bA(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${qt(n)} ${qt(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${qt(n)} ${qt(t)}`})}};function bA(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${qt(r)}.${qt(n)})`}return xA(e)}function vA(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 qt(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 xA(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):gw(e)}function gw(e){return`'${String(e).replace(/'/g,"''")}'`}var co=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){kA(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(yw).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Wr(o)}.${Wr(t)} = ${$A(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Wr(n)}.${Wr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Wr(n)}.${Wr(t)}`})}};function kA(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 Wr(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 $A(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):yw(e)}function yw(e){return`'${String(e).replace(/'/g,"''")}'`}async function ww(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(SA)}async function bw(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${TA(t)}`)).rows??[]).some(n=>n.name===String(t))}var uo=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(_w).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${_w(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 SA(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function _w(e){return String(e).split(".").map(EA).join(".")}function EA(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 TA(e){return`'${String(e).replace(/'/g,"''")}'`}var RA="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",PA="1.0",kw="1.0.9",vw="NESTED_TX_NOT_SUPPORTED";async function $w(e,t={}){let r=bl(e);if(jA(r),r.kind==="embedded"){let n=DA(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=NA(r),i=t.binary??lw(),s=await cw(i,o),a=new Gi(s);return await a.call("version",{}),new Tl(a,{transport:"embedded"})}}function xw(e){return zA(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:AA(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&CA(e)?{$uuid:e}:e}function zA(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 OA(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(xw):e.map(xw)}function AA(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 IA(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 CA(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Yi(e){if(Array.isArray(e))return e.map(Yi);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return IA(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]=Yi(o);return r}return e}function NA(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function DA(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 jA(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",RA)}var Qi=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 Rl()}},El=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Rl();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 Qi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){Sw(r,n)}throw r}}},Tl=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=PA,this.cache=new oo(t,this.transport),this.queue=new io(t),this.queues=this.queue,this.documents=new so(this);let n=new Hr(t);this.kv=Object.assign((o="kv_default")=>new Hr(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 ao(t,o),this.vault=(o="red.vault")=>new co(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=OA(r);return n==null?this.client.call("query",{sql:t}).then(Yi):this.client.call("query",{sql:t,params:n}).then(Yi)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return LA(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 MA(n,r.length)}tx(){return new El(this)}async transaction(t){if(this.inTransaction)throw Rl();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 Qi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){Sw(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return bw(this,t)}list(){return ww(this)}from(t){return new uo(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 Rl(){return new z(vw,`${vw}: nested transactions are not supported on one connection`)}function Sw(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function LA(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${kw} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function MA(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 >= ${kw} 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 lo(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"&&qA(t.chosenOption)&&BA(t.outcome)&&ZA(t.cost)}function qA(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function BA(e){return e==="success"||e==="failure"||e==="escalated"}function ZA(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 UA}from"node:crypto";function Pl(e){return UA("sha256").update(e).digest("hex")}function Ew(e){return Pl(JSON.stringify(e))}function Tw(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var zl="unknown",Xi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Il(t.from),i=Il(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>FA(p,n)).filter(p=>p!=null).filter(p=>KA(p,t)).filter(p=>HA(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=JA(c,l,r),f=[Rw(null,s,u,r)];if(t.groupBy){let m=[...WA(s,t.groupBy).entries()].map(([h,_])=>Rw(h,_,u,r)).sort((h,_)=>_.total-h.total||QA(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function FA(e,t){let r=e.properties.metadata??{},n=VA(e,r,t);return n==null?null:{ts:n,platform:Ol(r,"platform")??zl,eventType:Ol(r,"event_type")??zl,target:Ol(r,"target")??zl}}function VA(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Il(t.timestamp)??n}function Ol(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function KA(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 HA(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function WA(e,t){let r=new Map;for(let n of e){let o=GA(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function GA(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Rw(e,t,r,n){let o=new Map;for(let s of t){let a=Al(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 JA(e,t,r){if(e==null||t==null)return[];let n=[],o=Al(e,r),i=Al(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=YA(o,r),s++;return n}function Al(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 YA(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 Il(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 QA(e,t){return String(e??"").localeCompare(String(t??""))}var XA=["validate","simple","complex","think"];var eI={validate:1,simple:.85,complex:.65,think:.45};function tI(){return{schemaVersion:1,buckets:{}}}function zw(e,t={}){let r=aI(t.initial??tI());for(let n of e)rI(r,n,t);return r}function rI(e,t,r={}){let n=(r.tierForEvent??nI)(t);if(!n)return e;let i=iI(e,t.taskClass).arms[n],s=oI(t,n);return i.posterior.alpha=Pw(i.posterior.alpha+s),i.posterior.beta=Pw(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 nI(e){let t=e.chosenOption.kind;if(cI(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 oI(e,t){return e.outcome!=="success"?0:eI[t]}function iI(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=sI(),e.buckets[r]}function sI(){return{arms:{validate:es(),simple:es(),complex:es(),think:es()}}}function es(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function aI(e){return JSON.parse(JSON.stringify(e))}function cI(e){return XA.includes(e)}function Pw(e){return Math.round(e*1e3)/1e3}var ts=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Ow={contact:"person"},rs=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],nt={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var os=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 $w(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 ${nt.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${nt.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${nt.outcomeEvents}`)}kv(){return this.db.kv(nt.kv)}async capture(t){let r=Lw(t.kind??"note"),n=Date.now(),o=fI(t.tags??[]),i=Ew([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=`${Tw(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 ${nt.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(Iw(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 ${nt.artifacts}`);this.artifactCache=t.rows.map(uI).filter(ns)}return this.artifactCache}async search(t,r=10,n={}){let o=pI(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=qw(u,o),f=Bw({...d,connections:mI(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:gI(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=Mw(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 ${nt.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(Cw(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 ${nt.connections}`);this.connectionCache=t.rows.map(lI).filter(ns)}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:kI(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new Xi(r).events(t)}async appendOutcomeEvent(t){if(!lo(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${nt.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 ${nt.outcomeEvents}`);this.outcomeEventCache=t.rows.map(dI).filter(ns).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(Nw());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return Dw(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!Dw(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(Nw(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=zw(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=>!Vr(i.artifact)).slice(0,r);return yI(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(Iw(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Cw(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||Vr(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=ew(t),i=new Set([t.rid]);for(let d of r)Vr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Vr(d.artifact)).map(d=>({artifact:ml(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:ml(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:pl},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!hl(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 Lw(e){let r=Ow[e]??e;if(ts.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Mw(e){if(rs.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function uI(e){let t=Number(e.red_entity_id??e.rid),r=Cl(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:Lw(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 lI(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:Mw(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:Cl(e.properties??e.PROPERTIES)}}function dI(e){let t=Number(e.red_entity_id??e.rid),r=Cl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!lo(r)?null:{rid:t,event:r}}function Cl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function ns(e){return e!=null}function fI(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function pI(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Aw(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function qw(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+Aw(r,a)*3+Aw(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 mI(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||Vr(a))continue;let c=Bw({...qw(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*hI(i.kind))}return ar(o*.35)}function hI(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 Bw(e){return{...e,lexical:ar(e.lexical),tags:ar(e.tags),kind:ar(e.kind),connections:ar(e.connections),vector:ar(e.vector),total:ar(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function ar(e){return Math.round(e*1e3)/1e3}function gI(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 yI(e,t){let r=t.map(_I),n=wI(t),o=bI(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:vI(e,r,n,o)}}function _I(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 wI(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 bI(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 vI(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
|
|
86
|
-
`);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}]`:""}; ${
|
|
87
|
-
`)}function
|
|
88
|
-
`)||JSON.stringify(e.raw)}function
|
|
89
|
-
`)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function
|
|
88
|
+
`).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function vl(e,t){return`${xl(e)}.${xA(t)}`}function xl(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 xA(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function kA(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 ww(e){return`'${String(e).replace(/'/g,"''")}'`}var oo=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${St(t)}`})}push(t,r,n={}){let o=EA(n);return this.client.call("query",{sql:`QUEUE PUSH ${St(t)} ${TA(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${St(t)}${$l(r)}`});return kl(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${St(t)}${$l(r)}`});return kl(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${St(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${St(t)}`})}async readWait(t,r,n={}){let o=$A(t,r,n),i=await this.client.call("query",{sql:o});return kl(i)}};function $A(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=St(e),a=St(t),c=o!=null?` GROUP ${St(o)}`:"",l=i!=null?$l(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function St(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 $l(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 SA(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function EA(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 ${SA(e.priority)}`),e.key!=null&&(t+=` KEY ${Sl(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Sl(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function TA(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Sl(e):JSON.stringify(e)}function Sl(e){return`'${String(e).replace(/'/g,"''")}'`}function kl(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var io=class{constructor(t){this.db=t}async insert(t,r){bw(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ji(t)} DOCUMENT VALUES (${zA(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=RA(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 ${Ji(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){bw(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])=>`${vw(c)} = ${OA(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ji(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 ${Ji(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function bw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function RA(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 Ji(e){return String(e).split(".").map(vw).join(".")}function vw(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 PA(e){return xw(JSON.stringify(e))}function zA(e){return JSON.stringify(e)}function OA(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?PA(e):xw(e)}function xw(e){return`'${String(e).replace(/'/g,"''")}'`}var so=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){IA(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(kw).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${qt(o)} ${qt(t)} = ${AA(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${qt(n)} ${qt(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${qt(n)} ${qt(t)}`})}};function AA(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${qt(r)}.${qt(n)})`}return CA(e)}function IA(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 qt(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 CA(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):kw(e)}function kw(e){return`'${String(e).replace(/'/g,"''")}'`}var ao=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){NA(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map($w).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Wr(o)}.${Wr(t)} = ${DA(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Wr(n)}.${Wr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Wr(n)}.${Wr(t)}`})}};function NA(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 Wr(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 DA(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):$w(e)}function $w(e){return`'${String(e).replace(/'/g,"''")}'`}async function Ew(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(jA)}async function Tw(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${MA(t)}`)).rows??[]).some(n=>n.name===String(t))}var co=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(Sw).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${Sw(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 jA(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function Sw(e){return String(e).split(".").map(LA).join(".")}function LA(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 MA(e){return`'${String(e).replace(/'/g,"''")}'`}var qA="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",BA="1.0",zw="1.0.9",Rw="NESTED_TX_NOT_SUPPORTED";async function Ow(e,t={}){let r=bl(e);if(GA(r),r.kind==="embedded"){let n=WA(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=HA(r),i=t.binary??yw(),s=await hw(i,o),a=new Gi(s);return await a.call("version",{}),new Tl(a,{transport:"embedded"})}}function Pw(e){return ZA(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:FA(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&KA(e)?{$uuid:e}:e}function ZA(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 UA(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Pw):e.map(Pw)}function FA(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 VA(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 KA(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Yi(e){if(Array.isArray(e))return e.map(Yi);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return VA(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]=Yi(o);return r}return e}function HA(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function WA(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 GA(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",qA)}var Qi=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 Rl()}},El=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Rl();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 Qi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){Aw(r,n)}throw r}}},Tl=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=BA,this.cache=new no(t,this.transport),this.queue=new oo(t),this.queues=this.queue,this.documents=new io(this);let n=new Hr(t);this.kv=Object.assign((o="kv_default")=>new Hr(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 so(t,o),this.vault=(o="red.vault")=>new ao(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=UA(r);return n==null?this.client.call("query",{sql:t}).then(Yi):this.client.call("query",{sql:t,params:n}).then(Yi)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return JA(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 YA(n,r.length)}tx(){return new El(this)}async transaction(t){if(this.inTransaction)throw Rl();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 Qi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){Aw(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return Tw(this,t)}list(){return Ew(this)}from(t){return new co(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 Rl(){return new z(Rw,`${Rw}: nested transactions are not supported on one connection`)}function Aw(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function JA(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${zw} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function YA(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 >= ${zw} 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 uo(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"&&QA(t.chosenOption)&&XA(t.outcome)&&eI(t.cost)}function QA(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function XA(e){return e==="success"||e==="failure"||e==="escalated"}function eI(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 tI}from"node:crypto";function Pl(e){return tI("sha256").update(e).digest("hex")}function Iw(e){return Pl(JSON.stringify(e))}function Cw(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var zl="unknown",Xi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Il(t.from),i=Il(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>rI(p,n)).filter(p=>p!=null).filter(p=>oI(p,t)).filter(p=>iI(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=cI(c,l,r),f=[Nw(null,s,u,r)];if(t.groupBy){let m=[...sI(s,t.groupBy).entries()].map(([h,_])=>Nw(h,_,u,r)).sort((h,_)=>_.total-h.total||lI(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function rI(e,t){let r=e.properties.metadata??{},n=nI(e,r,t);return n==null?null:{ts:n,platform:Ol(r,"platform")??zl,eventType:Ol(r,"event_type")??zl,target:Ol(r,"target")??zl}}function nI(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Il(t.timestamp)??n}function Ol(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function oI(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 iI(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function sI(e,t){let r=new Map;for(let n of e){let o=aI(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function aI(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Nw(e,t,r,n){let o=new Map;for(let s of t){let a=Al(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 cI(e,t,r){if(e==null||t==null)return[];let n=[],o=Al(e,r),i=Al(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=uI(o,r),s++;return n}function Al(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 uI(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 Il(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 lI(e,t){return String(e??"").localeCompare(String(t??""))}var dI=["validate","simple","complex","think"];var fI={validate:1,simple:.85,complex:.65,think:.45};function pI(){return{schemaVersion:1,buckets:{}}}function jw(e,t={}){let r=wI(t.initial??pI());for(let n of e)mI(r,n,t);return r}function mI(e,t,r={}){let n=(r.tierForEvent??hI)(t);if(!n)return e;let i=yI(e,t.taskClass).arms[n],s=gI(t,n);return i.posterior.alpha=Dw(i.posterior.alpha+s),i.posterior.beta=Dw(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 hI(e){let t=e.chosenOption.kind;if(bI(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 gI(e,t){return e.outcome!=="success"?0:fI[t]}function yI(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=_I(),e.buckets[r]}function _I(){return{arms:{validate:es(),simple:es(),complex:es(),think:es()}}}function es(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function wI(e){return JSON.parse(JSON.stringify(e))}function bI(e){return dI.includes(e)}function Dw(e){return Math.round(e*1e3)/1e3}var ts=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Lw={contact:"person"},rs=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],nt={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var os=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 Ow(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 ${nt.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${nt.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${nt.outcomeEvents}`)}kv(){return this.db.kv(nt.kv)}async capture(t){let r=Vw(t.kind??"note"),n=Date.now(),o=$I(t.tags??[]),i=Iw([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=`${Cw(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 ${nt.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(qw(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 ${nt.artifacts}`);this.artifactCache=t.rows.map(vI).filter(ns)}return this.artifactCache}async search(t,r=10,n={}){let o=SI(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=Hw(u,o),f=Ww({...d,connections:EI(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:RI(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=Kw(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 ${nt.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(Bw(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 ${nt.connections}`);this.connectionCache=t.rows.map(xI).filter(ns)}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:NI(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new Xi(r).events(t)}async appendOutcomeEvent(t){if(!uo(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${nt.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 ${nt.outcomeEvents}`);this.outcomeEventCache=t.rows.map(kI).filter(ns).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(Zw());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return Uw(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!Uw(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(Zw(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=jw(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=>!Vr(i.artifact)).slice(0,r);return PI(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(qw(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Bw(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||Vr(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=aw(t),i=new Set([t.rid]);for(let d of r)Vr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Vr(d.artifact)).map(d=>({artifact:ml(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:ml(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:pl},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!hl(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 Vw(e){let r=Lw[e]??e;if(ts.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Kw(e){if(rs.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function vI(e){let t=Number(e.red_entity_id??e.rid),r=Cl(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:Vw(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 xI(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:Kw(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:Cl(e.properties??e.PROPERTIES)}}function kI(e){let t=Number(e.red_entity_id??e.rid),r=Cl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!uo(r)?null:{rid:t,event:r}}function Cl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function ns(e){return e!=null}function $I(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function SI(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Mw(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function Hw(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+Mw(r,a)*3+Mw(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 EI(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||Vr(a))continue;let c=Ww({...Hw(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*TI(i.kind))}return cr(o*.35)}function TI(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 Ww(e){return{...e,lexical:cr(e.lexical),tags:cr(e.tags),kind:cr(e.kind),connections:cr(e.connections),vector:cr(e.vector),total:cr(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function cr(e){return Math.round(e*1e3)/1e3}function RI(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 PI(e,t){let r=t.map(zI),n=OI(t),o=AI(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:II(e,r,n,o)}}function zI(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 OI(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 AI(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 II(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
|
|
89
|
+
`);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}]`:""}; ${CI(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(`
|
|
90
|
+
`)}function CI(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(ns);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function qw(e){return`artifact.hash.${e}`}function Bw(e,t,r){return`connection.${e}.${r}.${t}`}function Zw(){return`model-tier-bandit.v${1}`}function Uw(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function NI(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function DI(e=process.cwd()){let t=await dw(e);if(pw(t))try{return{config:t,store:await mw(t),project:Gw(t.rootDir)}}catch(n){let o=Ki(t.rootDir);if(await ro(o.socketPath,50))throw n}let r=await os.open({uri:t.connectionString,autoLinker:cw()});return{config:t,store:r,project:Gw(t.rootDir)}}async function ke(e,t=process.cwd()){let r=await DI(t);try{return await e(r)}finally{await r.store.close()}}function MI(e){return He(e)}async function Yw(e,t){if(e!=="SessionStart")return{};let r=await ke(async({config:o,store:i})=>(await i.status(),o)),n=Jw(r.rootDir,".red","brain","sessions");return await jI(n,{recursive:!0}),await LI(Jw(n,"last-session.json"),MI({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()}),"utf8"),{}}var is=class{map({event:t,sourceAgent:r}){return{title:qI(t),content:BI(t),kind:"event",tags:ZI(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Qw(t),metadata:UI(t)}}};function Qw(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Pl(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function qI(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 BI(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(`
|
|
91
|
+
`)||JSON.stringify(e.raw)}function ZI(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function UI(e){let t={event_key:Qw(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 ss(e){let t=new is,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 ur=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function eb(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new ur("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new ur("brain_act requires a non-empty message");let o=t.connect??(a=>or.connect(a)),i=t.process??FI(t.env??process.env),s;try{s=await o(i)}catch(a){throw new ur(`brain_act could not reach the channel bridge: ${Xw(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new ur(`brain_act could not send to "${r}": ${Xw(c)}`,{cause:c})}if(!a.ok)throw new ur(`brain_act could not send to "${r}": ${VI(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function FI(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 VI(e){return KI(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function KI(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 Xw(e){return e instanceof Error?e.message:String(e)}import{createServer as HI}from"node:http";async function nb(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:Nl(n,"supports"),contradicts:Nl(n,"contradicts"),depends_on:Nl(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=>WI(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=>GI(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 ob(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:JI(e)}}async function ib(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=HI((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
|
|
92
|
+
`)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function WI(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:XI(e.properties.content)}}function GI(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 JI(e){return`<!doctype html>
|
|
90
93
|
<html lang="en">
|
|
91
94
|
<head>
|
|
92
95
|
<meta charset="utf-8">
|
|
@@ -278,44 +281,44 @@ ${o}`),n.join(`
|
|
|
278
281
|
<section>
|
|
279
282
|
<h2>Event KPIs</h2>
|
|
280
283
|
<div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
|
|
281
|
-
${
|
|
282
|
-
${
|
|
284
|
+
${tb(e.kpis.events_by_platform,"Platform")}
|
|
285
|
+
${tb(e.kpis.events_by_type,"Event type")}
|
|
283
286
|
</section>
|
|
284
287
|
<section>
|
|
285
288
|
<h2>Recent Decisions</h2>
|
|
286
289
|
<div class="feed">
|
|
287
|
-
${e.recent_decisions.length===0?
|
|
290
|
+
${e.recent_decisions.length===0?rb("No decision artifacts captured yet."):e.recent_decisions.map(YI).join("")}
|
|
288
291
|
</div>
|
|
289
292
|
</section>
|
|
290
293
|
</div>
|
|
291
294
|
<section>
|
|
292
295
|
<h2>Recent Connections</h2>
|
|
293
296
|
<div class="feed">
|
|
294
|
-
${e.recent_connections.length===0?
|
|
297
|
+
${e.recent_connections.length===0?rb("No graph connections captured yet."):e.recent_connections.map(QI).join("")}
|
|
295
298
|
</div>
|
|
296
299
|
</section>
|
|
297
300
|
</main>
|
|
298
301
|
<footer class="meta">${ae(e.attribution.red_hermes)}</footer>
|
|
299
|
-
<script id="brain-dashboard-data" type="application/json">${
|
|
302
|
+
<script id="brain-dashboard-data" type="application/json">${eC(e)}</script>
|
|
300
303
|
</body>
|
|
301
|
-
</html>`}function Gr(e,t,r){return`<div class="metric"><span>${ae(e)}</span><strong>${t}</strong><div class="meta">${ae(r)}</div></div>`}function
|
|
304
|
+
</html>`}function Gr(e,t,r){return`<div class="metric"><span>${ae(e)}</span><strong>${t}</strong><div class="meta">${ae(r)}</div></div>`}function tb(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${ae(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${ae(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${ae(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function YI(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${ae(n)}</span>`).join("")}</div>`;return`<article class="item">
|
|
302
305
|
<h3>${ae(e.title)}</h3>
|
|
303
306
|
<div class="meta">#${e.rid} - ${ae(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
|
|
304
307
|
<p class="meta">${ae(e.excerpt)}</p>
|
|
305
308
|
${r}
|
|
306
|
-
</article>`}function
|
|
309
|
+
</article>`}function QI(e){return`<article class="item">
|
|
307
310
|
<h3><span class="edge ${ae(e.kind)}">${ae(e.kind)}</span> ${ae(e.from.title)} -> ${ae(e.to.title)}</h3>
|
|
308
311
|
<div class="meta">#${e.rid} - ${ae(e.created_at)}${e.reason?` - ${ae(e.reason)}`:""}</div>
|
|
309
|
-
</article>`}function
|
|
310
|
-
`,"utf8")}var
|
|
312
|
+
</article>`}function rb(e){return`<div class="empty">${ae(e)}</div>`}function Nl(e,t){return e.filter(r=>r.kind===t).length}function XI(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function ae(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case"'":return"'";default:return t}})}function eC(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as nC,readFile as oC,writeFile as iC}from"node:fs/promises";import{dirname as sC}from"node:path";function sb(e){return He(e,{keyedMapCollapse:!0})}var tC=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],rC=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],b2=[...tC,...rC];async function ab(e){let t=await ss({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 cb(e){try{let r=(await oC(e,"utf8")).trim();if(!r)return{};try{return JSON.parse(r)}catch{return Ke(r)}}catch(t){if(t.code==="ENOENT")return{};throw t}}async function ub(e,t){await nC(sC(e),{recursive:!0}),await iC(e,`${sb(t)}
|
|
313
|
+
`,"utf8")}var lb={"=":"data",":=":{to:"data",typed:!0},":":"meta"},aC=/^[a-z][a-z0-9+.-]*:\/\//i;function cC(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function uC(e=lb){return Object.entries(e).map(([t,r])=>cC(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function lC(e){return/^-\d+(\.\d+)?$/.test(e)}function lo(e){return!(!e||e.startsWith("-")&&!lC(e))}function as(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function db(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>db(r.trim())):e}function lr(e,t){switch(t){case"boolean":return dC(e);case"number":return fC(e);case"array":return e.split(",").map(r=>as(r.trim()));case"string":default:return e}}function dC(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function fC(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function Bt(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function pC(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function Y(e,t){return{type:e,value:t}}function mC(e){let t=[],r=gC(e);if(t.push(Y("section-header","Usage:"),Y("text"," "),Y("usage-text",r),Y("newline",`
|
|
311
314
|
`),Y("newline",`
|
|
312
315
|
`)),e.positional&&e.positional.length>0){t.push(Y("section-header","Arguments:"),Y("newline",`
|
|
313
316
|
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push(Y("indent"," "),Y("positional-name",`<${o}>`)),n.required||t.push(Y("positional-optional"," (optional)")),t.push(Y("newline",`
|
|
314
317
|
`),Y("indent"," "),Y("option-description",n.description),Y("newline",`
|
|
315
318
|
`))}t.push(Y("newline",`
|
|
316
319
|
`))}if(e.options&&Object.keys(e.options).length>0){t.push(Y("section-header","Options:"),Y("newline",`
|
|
317
|
-
`));let n=
|
|
318
|
-
`))}return r}function
|
|
320
|
+
`));let n=yC(e.options);t.push(...n)}return t}function hC(e,t){let r=mC(e);return pC(r,t)}function gC(e){let t=["[options]"];if(e.positional)for(let r of e.positional)r.variadic?t.push(r.required?`<${r.name}...>`:`[${r.name}...]`):t.push(r.required?`<${r.name}>`:`[${r.name}]`);return t.join(" ")}function yC(e,t=!1){let r=[],n=[],o=t?"global-option-flag":"option-flag",i=t?"global-option-type":"option-type",s=t?"global-option-default":"option-default",a=t?"global-option-description":"option-description";for(let[l,u]of Object.entries(e)){if(u.hidden)continue;let d=[],f=h=>{d.includes(h)||d.push(h)};u.short&&f(`-${u.short}`),f(`--${l}`);for(let h of u.aliases??[])h.length===1?f(`-${h}`):f(`--${h}`);let p=d.join(", "),m=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;n.push({flags:p,type:m,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let c=Math.max(...n.map(l=>l.flags.length+(l.type?l.type.length+1:0)),20);for(let l of n){let u=l.flags.length+(l.type?l.type.length+1:0),d=" ".repeat(c-u+2);r.push(Y("indent"," ")),r.push(Y(o,l.flags)),l.type&&(r.push(Y("text"," ")),r.push(Y(i,l.type))),r.push(Y("text",d)),r.push(Y(a,l.desc)),l.default!==void 0&&(r.push(Y("text"," ")),r.push(Y(s,`(default: ${l.default})`))),r.push(Y("newline",`
|
|
321
|
+
`))}return r}function fb(e){let t=$C(e.options??{},e.autoShort??!1),r=uC(e.separators??lb);return{schema:e,parse(n){return _C(n,e,t,r)},help(){return hC(e,e.formatter)}}}function _C(e,t,r,n){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(n.map(u=>u.to));for(let u of i)o[u]={};let s=0,a=t.positional??[],c=0,l=!1;for(;c<e.length;){let u=e[c];if(t.stopEarly&&s>0){o.rest=e.slice(c);break}if(u==="--"&&!l){l=!0,c++;continue}if(l){if(s<a.length){let f=a[s];if(f.variadic){let p=[];for(;c<e.length;){let m=e[c];p.push(f.type?lr(m,f.type):m),c++}o.positional[f.name]=p,s++}else{let p=f.type?lr(u,f.type):u;o.positional[f.name]=p,s++,c++}}else t.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),c++;continue}if(u.startsWith("--")){c=xC(u,c,e,o,r,t);continue}if(u.startsWith("-")&&u.length>1&&!PC(u)){c=kC(u,c,e,o,r,t);continue}let d=wC(u,n);if(d){let{key:f,value:p,config:m}=d,h=o,_=h[m.to]??(h[m.to]={});_[f]=m.typed?db(p):Bt(p),c++;continue}if(s<a.length){let f=a[s];if(f.variadic){let m=[];for(;c<e.length&&!e[c].startsWith("-");){let h=e[c];m.push(f.type?lr(h,f.type):h),c++}o.positional[f.name]=m,s++;continue}let p=f.type?lr(u,f.type):u;o.positional[f.name]=p,s++}else t.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);c++}return EC(o,t,r),TC(o,t,a),RC(o,t,r),o}function wC(e,t){if(aC.test(e))return null;for(let r of t){if(r.prefix&&e.startsWith(r.separator)){let o=e.slice(r.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(bC(s))return{key:s,value:a,config:r}}continue}let n=e.indexOf(r.separator);if(n>0){let o=e.slice(0,n),i=e.slice(n+r.separator.length);if(vC(o,i,r))return{key:o,value:i,config:r}}}return null}function bC(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function vC(e,t,r){return e?r.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(t)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((r.separator==="="||r.separator===":=")&&e.includes("/")):!1}function xC(e,t,r,n,o,i){let s=e.slice(2);if(s.startsWith("no-")){let c=s.slice(3),l=o.get(c);if(l?.negatable!==!1&&l?.type==="boolean")return n.options[l.name]=!1,t+1}if(s.includes("=")){let c=s.indexOf("="),l=s.slice(0,c),u=s.slice(c+1);return cs(l,u,t+1,n,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let c=r[t+1];return lo(c)?cs(a.name,c,t+2,n,o,i):(n.errors.push(`Option --${s} requires a value`),t+1)}return n.options[a.name]=!0,t+1}return i.strict?n.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(n.options[s]=!0),t+1}function kC(e,t,r,n,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),c=s.slice(0,a),l=s.slice(a+1),u=Dl(c,o);return u?cs(u.name,l,t+1,n,o,i):(i.strict?n.errors.push(`Unknown option: -${c}`):i.allowUnknown!==!1&&(n.options[c]=as(Bt(l))),t+1)}if(s.length===1){let a=Dl(s,o);if(a){if(a.type!=="boolean"){let c=r[t+1];return lo(c)?cs(a.name,c,t+2,n,o,i):(n.errors.push(`Option -${s} requires a value`),t+1)}return n.options[a.name]=!0,t+1}if(i.strict)n.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let c=r[t+1];if(lo(c))return n.options[s]=as(Bt(c)),t+2;n.options[s]=!0}return t+1}for(let a of s){let c=Dl(a,o);c?c.type==="boolean"?n.options[c.name]=!0:n.errors.push(`Option -${a} requires a value`):i.strict?n.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(n.options[a]=!0)}return t+1}function cs(e,t,r,n,o,i){let s=o.get(e);if(s){if(s.choices){let c=s.type?lr(Bt(t),s.type):Bt(t);if(!s.choices.includes(c))return n.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${s.choices.join(", ")}`),r}let a=s.type?lr(Bt(t),s.type):Bt(t);if(s.type==="array"){let c=n.options[e];Array.isArray(c)?c.push(...a):n.options[e]=a}else n.options[e]=a}else i.strict?n.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(n.options[e]=as(Bt(t)));return r}function $C(e,t=!1){let r=new Map,n=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of n)i.short&&o.add(i.short);for(let[i,s]of n){let a=s.short??"";t&&!a&&(a=SC(i,o),a&&o.add(a));let c={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};r.set(i,c);for(let l of c.aliases)r.set(l,c)}return r}function SC(e,t){for(let r of e){if(!/[a-zA-Z]/.test(r))continue;let n=r.toLowerCase();if(!t.has(n))return n;let o=r.toUpperCase();if(!t.has(o))return o}return""}function Dl(e,t){for(let r of t.values())if(r.short===e||r.aliases.includes(e))return r}function EC(e,t,r){for(let n of r.values())if(e.options[n.name]===void 0)if(n.env&&process.env[n.env]!==void 0){let o=process.env[n.env];e.options[n.name]=n.type?lr(o,n.type):o}else n.default!==void 0&&(e.options[n.name]=n.default);for(let n of t.positional??[])e.positional[n.name]===void 0&&n.default!==void 0&&(e.positional[n.name]=n.default)}function TC(e,t,r){if(t.options)for(let[n,o]of Object.entries(t.options))o.required&&e.options[n]===void 0&&e.errors.push(`Missing required option: --${n}`);for(let n of r)n.required&&e.positional[n.name]===void 0&&e.errors.push(`Missing required argument: <${n.name}>`)}function RC(e,t,r){for(let n of r.values()){let o=e.options[n.name];if(n.validate&&o!==void 0){let i=n.validate(o);i!==!0&&e.errors.push(i)}}for(let n of t.positional??[]){let o=e.positional[n.name];if(n.validate&&o!==void 0){let i=n.validate(o);i!==!0&&e.errors.push(i)}}}function PC(e){return/^-\d+(\.\d+)?$/.test(e)}var fo=class extends Error{flag;known;constructor(t,r){super(`unknown flag '${t}'; expected one of: ${r.join(", ")}`),this.name="UnknownFlagError",this.flag=t,this.known=r}};function zC(e){let t={};for(let[r,n]of Object.entries(e))t[r]={type:n.kind==="boolean"?"boolean":"string",...r.length===1?{short:r}:{},...n.aliases===void 0?{}:{aliases:n.aliases}};return t}function OC(e,t){let r=new Map;for(let[o,i]of Object.entries(t))if(!(i.kind!=="value"||i.type!=="array")){r.set(o,o);for(let s of i.aliases??[])r.set(s,o)}let n=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=r.get(s[1]);if(a===void 0)continue;let c=s[2];if(c===void 0&&lo(e[o+1])&&(c=e[o+1],o+=1),c===void 0)continue;let l=n.get(a)??[];l.push(c),n.set(a,l)}return n}function pb(e,t,r={}){let o=fb({options:zC(t),separators:{},allowUnknown:!0}).parse([...e]),i={},s=OC(e,t),a=o.errors.find(c=>/^Option --?\S+ requires a value$/.test(c));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(r.unknownFlags==="error"){let c=new Set(Object.keys(t));for(let l of Object.keys(o.options))if(!c.has(l))throw new fo(l.length===1?`-${l}`:`--${l}`,Object.keys(t).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[c,l]of Object.entries(t)){let u=o.options[c];u!==void 0&&(l.kind==="boolean"?i[c]=u:l.type==="array"?i[c]=(s.get(c)??[]).map(d=>l.coerce(d)):i[c]=l.coerce(String(u)))}return{values:i,positionals:o.rest}}var po=class extends Error{token;known;constructor(t,r){super(`unknown command '${t}'; expected one of: ${r.join(", ")}`),this.name="UnknownCommandError",this.token=t,this.known=r}};function mb(e,t){let[r,...n]=e;if(r!==void 0){for(let[i,s]of Object.entries(t.commands))if(r===i||(s.aliases??[]).includes(r))return{command:i,args:n};if(t.errorOnUnknownCommand&&!r.startsWith("-"))throw new po(r,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:n}}var F=e=>e;function mo(e){return t=>{let r=Number(t);if(!Number.isFinite(r))throw new Error(`--${e} must be a number`);return r}}var hb={version:{kind:"boolean",aliases:["v"]},help:{kind:"boolean",aliases:["h"]},json:{kind:"boolean"}},ho={},gb={title:{kind:"value",coerce:F},content:{kind:"value",coerce:F},file:{kind:"value",coerce:F},kind:{kind:"value",coerce:F},tag:{kind:"value",type:"array",coerce:F},agent:{kind:"value",coerce:F},runner:{kind:"value",coerce:F},session:{kind:"value",coerce:F}},yb={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:mo("limit")}},_b={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:mo("limit")},json:{kind:"boolean"}},wb={from:{kind:"value",coerce:F},to:{kind:"value",coerce:F},kind:{kind:"value",coerce:F},reason:{kind:"value",coerce:F}},bb={target:{kind:"value",coerce:F},message:{kind:"value",coerce:F}},vb={runner:{kind:"value",coerce:F}},xb={"after-cursor":{kind:"value",aliases:["cursor"],coerce:F},"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:mo("limit")}},kb={"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:mo("limit")},state:{kind:"value",coerce:F}},$b={interval:{kind:"value",coerce:F},"group-by":{kind:"value",coerce:F},"time-field":{kind:"value",coerce:F},from:{kind:"value",coerce:F},to:{kind:"value",coerce:F},platform:{kind:"value",coerce:F},"event-type":{kind:"value",coerce:F},target:{kind:"value",coerce:F}},Sb={out:{kind:"value",coerce:F},host:{kind:"value",coerce:F},port:{kind:"value",coerce:mo("port")},json:{kind:"boolean"},serve:{kind:"boolean"}},Eb={root:{kind:"value",coerce:F}},AC={help:{},version:{},init:{},status:{},capture:{},search:{},think:{aliases:["query"]},get:{},link:{},backlinks:{},act:{},hook:{},"ingest-events":{},"schedule-ingest":{},kpi:{aliases:["kpis"]},dashboard:{},"outcome-event":{}},IC={commands:AC,default:"help",keepArgvOnDefault:!0,errorOnUnknownCommand:!0};function Tb(e){try{return mb(e,IC)}catch(t){throw t instanceof po?new Error(`unknown brain command: ${t.token} \u2014 run \`brain help\` for the command list`):t}}function ge(e,t){try{return pb(e,t,{unknownFlags:"error"})}catch(r){throw r instanceof fo?new Error(`unknown brain flag: ${r.flag} \u2014 run \`brain help\` for usage`):r}}var Rb=`brain commands:
|
|
319
322
|
init
|
|
320
323
|
status
|
|
321
324
|
capture [text] --title <title> --kind <${ts.join("|")}> --tag <tag>
|
|
@@ -335,6 +338,6 @@ brain flags (answered before any command, and before config or the store):
|
|
|
335
338
|
-v, --version print the build version
|
|
336
339
|
--json with --version: print the structured build info
|
|
337
340
|
-h, --help show this help
|
|
338
|
-
`;async function
|
|
341
|
+
`;async function LC(){let{command:e,args:t}=Tb(process.argv.slice(2));switch(e){case"help":case"version":{let{values:r}=ge(t,hb);if(e==="version"||r.version===!0){MC(r.json===!0);return}console.log(Rb);return}case"init":ge(t,ho),await ke(async({config:r,store:n})=>{let o=await n.status();Pe({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":ge(t,ho),await ke(async({config:r,store:n})=>{Pe({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await BC(t);return;case"search":await ZC(t);return;case"think":await UC(t);return;case"get":await FC(t);return;case"link":await VC(t);return;case"backlinks":await KC(t);return;case"act":await YC(t);return;case"hook":await QC(t);return;case"ingest-events":await WC(t);return;case"schedule-ingest":await HC(t);return;case"kpi":await GC(t);return;case"dashboard":await JC(t);return;case"outcome-event":await qC(t);return}}function MC(e){let t=ql("brain");process.stdout.write(e?`${JSON.stringify(t)}
|
|
339
342
|
`:`${Bl(t)}
|
|
340
|
-
`)}async function
|
|
343
|
+
`)}async function qC(e){let{values:t,positionals:r}=ge(e,Eb);if(r[0]!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=await XC(),o=JSON.parse(n);if(!uo(o))throw new Error("invalid brain outcome event");await ke(async({store:i})=>{Pe(await i.appendOutcomeEvent(o))},t.root??process.cwd())}async function BC(e){let{values:t,positionals:r}=ge(e,gb),n=(t.title??r.join(" ").slice(0,80))||"Untitled artifact",o=t.content??(t.file?await CC(t.file,"utf8"):r.join(" "));if(!o.trim())throw new Error("brain capture requires content, --content, or --file");await ke(async({store:i})=>{let s=await i.capture({title:n,content:o,kind:t.kind??"note",tags:t.tag??[],sourceAgent:t.agent,sourceRunner:t.runner,sourceSession:t.session,sourcePath:process.cwd()});Pe(s)})}async function ZC(e){let{values:t,positionals:r}=ge(e,yb),n=t.query??r.join(" ");if(!n)throw new Error("brain search requires a query");let o=t.limit??10;await ke(async({store:i})=>Pe(await i.search(n,o)))}async function UC(e){let{values:t,positionals:r}=ge(e,_b),n=t.query??r.join(" ");if(!n)throw new Error("brain think requires a query");let o=t.limit??8;await ke(async({store:i})=>{let s=await i.think(n,o);t.json===!0?Pe(s):console.log(s.answer)})}async function FC(e){let{positionals:t}=ge(e,ho),r=t[0];if(!r)throw new Error("brain get requires a rid or artifact id");await ke(async({store:n})=>{let o=await n.getArtifact(us(r));if(!o)throw new Error(`Brain artifact not found: ${r}`);Pe(o)})}async function VC(e){let{values:t}=ge(e,wb),r=t.from,n=t.to;if(!r||!n)throw new Error("brain link requires --from and --to");await ke(async({store:o})=>{Pe(await o.link({from:us(r),to:us(n),kind:t.kind??"related_to",reason:t.reason}))})}async function KC(e){let{positionals:t}=ge(e,ho),r=t[0];if(!r)throw new Error("brain backlinks requires a rid or artifact id");await ke(async({store:n})=>Pe(await n.backlinks(us(r))))}async function HC(e){let{values:t}=ge(e,kb),r=await or.connect();try{await ke(async({config:n,store:o})=>{let i=t.state??Pb(n.rootDir,".red","brain","ingestion-state.json"),s=await cb(i),a=await ab({bridge:r,store:o,state:s,sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.schedule-ingest"});await ub(i,a.state),Pe(a)})}finally{await r.close().catch(()=>{})}}async function WC(e){let{values:t}=ge(e,xb),r=await or.connect();try{await ke(async({store:n})=>{let o=await ss({bridge:r,store:n,afterCursor:t["after-cursor"],sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.ingest-events"});Pe(o)})}finally{await r.close().catch(()=>{})}}async function GC(e){let{values:t}=ge(e,$b);await ke(async({store:r})=>{Pe(await r.eventKpis({interval:t.interval,groupBy:t["group-by"],timeField:t["time-field"],from:t.from,to:t.to,platform:t.platform,eventType:t["event-type"],target:t.target}))})}async function JC(e){let{values:t}=ge(e,Sb),r=await ke(async({config:o,store:i,project:s})=>{let a=await nb(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:ob(a),defaultOut:Pb(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){Pe(r.dashboard);return}if(t.serve===!0){let o=t.host??"127.0.0.1",i=t.port??4738,s=await ib(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=t.out??r.defaultOut;await NC(jC(n),{recursive:!0}),await DC(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function YC(e){let{values:t,positionals:r}=ge(e,bb),n=t.target??r[0],o=t.message??r.slice(1).join(" ");if(!n)throw new Error("brain act requires --target <channel>");if(!o)throw new Error("brain act requires --message <text>");Pe(await eb({target:n,message:o}))}async function QC(e){let{values:t,positionals:r}=ge(e,vb),n=r[0]??"SessionStart",o=t.runner??"unknown";Pe(await Yw(n,o))}function us(e){return/^\d+$/.test(e)?Number(e):e}function Pe(e){console.log(JSON.stringify(e,null,2))}async function XC(){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")}LC().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|