@reddb-io/red-skills 3.0.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Pw=Object.create;var Ji=Object.defineProperty;var zw=Object.getOwnPropertyDescriptor;var Ow=Object.getOwnPropertyNames;var Iw=Object.getPrototypeOf,Aw=Object.prototype.hasOwnProperty;var yt=(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),yl=(e,t)=>{for(var r in t)Ji(e,r,{get:t[r],enumerable:!0})},Nw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ow(t))!Aw.call(e,o)&&o!==r&&Ji(e,o,{get:()=>t[o],enumerable:!(n=zw(t,o))||n.enumerable});return e};var Yi=(e,t,r)=>(r=e!=null?Pw(Iw(e)):{},Nw(t||!e||!e.__esModule?Ji(r,"default",{value:e,enumerable:!0}):r,e));var fn=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 ln=class{};Z._CodeOrName=ln;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qt=class extends ln{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=qt;var Me=class extends ln{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 qt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Me;Z.nil=new Me("");function Vp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)ya(r,t[n]),r.push(e[++n]);return new Me(r)}Z._=Vp;var ga=new Me("+");function Kp(e,...t){let r=[dn(e[0])],n=0;for(;n<t.length;)r.push(ga),ya(r,t[n]),r.push(ga,dn(e[++n]));return jx(r),new Me(r)}Z.str=Kp;function ya(e,t){t instanceof Me?e.push(...t._items):t instanceof qt?e.push(t):e.push(qx(t))}Z.addCodeArg=ya;function jx(e){let t=1;for(;t<e.length-1;){if(e[t]===ga){let r=Mx(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Mx(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof qt||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 qt))return`"${e}${t.slice(1)}`}function Lx(e,t){return t.emptyStr()?e:e.emptyStr()?t:Kp`${e}${t}`}Z.strConcat=Lx;function qx(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:dn(Array.isArray(e)?e.join(","):e)}function Bx(e){return new Me(dn(e))}Z.stringify=Bx;function dn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=dn;function Zx(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Me(`.${e}`):Vp`[${e}]`}Z.getProperty=Zx;function Ux(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Me(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=Ux;function Fx(e){return new Me(e.toString())}Z.regexpCode=Fx});var va=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var Re=fn(),_a=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Co;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Co||(Pe.UsedValueState=Co={}));Pe.varKinds={const:new Re.Name("const"),let:new Re.Name("let"),var:new Re.Name("var")};var Do=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Re.Name?t:this.name(t)}name(t){return new Re.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}}};Pe.Scope=Do;var jo=class extends Re.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Re._)`.${new Re.Name(r)}[${n}]`}};Pe.ValueScopeName=jo;var Vx=(0,Re._)`\n`,wa=class extends Do{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Vx:Re.nil}}get(){return this._scope}name(t){return new jo(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,Re._)`${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=Re.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,Co.Started);let u=r(l);if(u){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;i=(0,Re._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Re._)`${i}${u}${this.opts._n}`;else throw new _a(l);c.set(l,Co.Completed)})}return i}};Pe.ValueScope=wa});var C=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 L=fn(),Ve=va(),xt=fn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return xt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return xt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return xt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return xt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return xt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return xt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return xt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return xt.Name}});var Bo=va();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Bo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Bo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Bo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Bo.varKinds}});D.operators={GT:new L._Code(">"),GTE:new L._Code(">="),LT:new L._Code("<"),LTE:new L._Code("<="),EQ:new L._Code("==="),NEQ:new L._Code("!=="),NOT:new L._Code("!"),OR:new L._Code("||"),AND:new L._Code("&&"),ADD:new L._Code("+")};var ut=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ba=class extends ut{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ve.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=fr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},Mo=class extends ut{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=fr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return qo(t,this.rhs)}},xa=class extends Mo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},$a=class extends ut{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ka=class extends ut{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Sa=class extends ut{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ea=class extends ut{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=fr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},pn=class extends ut{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)||(Kx(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Ut(t,r.names),{})}},lt=class extends pn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ta=class extends pn{},dr=class extends lt{};dr.kind="else";var Bt=class e extends lt{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 dr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Hp(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=fr(this.condition,t,r),this}get names(){let t=super.names;return qo(t,this.condition),this.else&&Ut(t,this.else.names),t}};Bt.kind="if";var Zt=class extends lt{};Zt.kind="for";var Ra=class extends Zt{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=fr(this.iteration,t,r),this}get names(){return Ut(super.names,this.iteration.names)}},Pa=class extends Zt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ve.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)}},Lo=class extends Zt{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=fr(this.iterable,t,r),this}get names(){return Ut(super.names,this.iterable.names)}},mn=class extends lt{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)}};mn.kind="func";var hn=class extends pn{render(t){return"return "+super.render(t)}};hn.kind="return";var za=class extends lt{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&&Ut(t,this.catch.names),this.finally&&Ut(t,this.finally.names),t}},gn=class extends lt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};gn.kind="catch";var yn=class extends lt{render(t){return"finally"+super.render(t)}};yn.kind="finally";var Oa=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new Ve.Scope({parent:t}),this._nodes=[new Ta]}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 ba(t,i,n)),i}const(t,r,n){return this._def(Ve.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ve.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ve.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Mo(t,r,n))}add(t,r){return this._leafNode(new xa(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new Ea(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,L.addCodeArg)(r,o));return r.push("}"),new L._Code(r)}if(t,r,n){if(this._blockNode(new Bt(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 Bt(t))}else(){return this._elseNode(new dr)}endIf(){return this._endBlockNode(Bt,dr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ra(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ve.varKinds.var:Ve.varKinds.let){let s=this._scope.toName(t);return this._for(new Pa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ve.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof L.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,L._)`${s}.length`,a=>{this.var(i,(0,L._)`${s}[${a}]`),n(i)})}return this._for(new Lo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,L._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Lo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Zt)}label(t){return this._leafNode(new $a(t))}break(t){return this._leafNode(new ka(t))}return(t){let r=new hn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(hn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new za;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new gn(i),r(i)}return n&&(this._currNode=o.finally=new yn,this.code(n)),this._endBlockNode(gn,yn)}throw(t){return this._leafNode(new Sa(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=L.nil,n,o){return this._blockNode(new mn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(mn)}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 Bt))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=Oa;function Ut(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function qo(e,t){return t instanceof L._CodeOrName?Ut(e,t.names):e}function fr(e,t,r){if(e instanceof L.Name)return n(e);if(!o(e))return e;return new L._Code(e._items.reduce((i,s)=>(s instanceof L.Name&&(s=n(s)),s instanceof L._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof L._Code&&i._items.some(s=>s instanceof L.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function Kx(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Hp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${Ia(e)}`}D.not=Hp;var Hx=Wp(D.operators.AND);function Wx(...e){return e.reduce(Hx)}D.and=Wx;var Gx=Wp(D.operators.OR);function Jx(...e){return e.reduce(Gx)}D.or=Jx;function Wp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${Ia(t)} ${e} ${Ia(r)}`}function Ia(e){return e instanceof L.Name?e:(0,L._)`(${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=C(),Yx=fn();function Qx(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=Qx;function Xx(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Yp(e,t),!Qp(t,e.self.RULES.all))}j.alwaysValidSchema=Xx;function Yp(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]||tm(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=Yp;function Qp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=Qp;function e$(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=e$;function t$({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=t$;function r$(e){return Xp(decodeURIComponent(e))}j.unescapeFragment=r$;function n$(e){return encodeURIComponent(Na(e))}j.escapeFragment=n$;function Na(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Na;function Xp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Xp;function o$(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=o$;function Gp({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:Gp({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} || {}`),Ca(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:em}),items:Gp({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 em(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Ca(e,r,t),r}j.evaluatedPropsToName=em;function Ca(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Ca;var Jp={};function i$(e,t){return e.scopeValue("func",{ref:t,code:Jp[t.code]||(Jp[t.code]=new Yx._Code(t.code))})}j.useFunc=i$;var Aa;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Aa||(j.Type=Aa={}));function s$(e,t,r){if(e instanceof H.Name){let n=t===Aa.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():"/"+Na(e)}j.getErrorPath=s$;function tm(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=tm});var dt=v(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var ye=C(),a$={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};Da.default=a$});var _n=v(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.extendErrors=_e.resetErrorsCount=_e.reportExtraError=_e.reportError=_e.keyword$DataError=_e.keywordError=void 0;var B=C(),Zo=q(),ke=dt();_e.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};_e.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 c$(e,t=_e.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=om(e,t,r);n??(s||a)?rm(i,c):nm(o,(0,B._)`[${c}]`)}_e.reportError=c$;function u$(e,t=_e.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=om(e,t,r);rm(o,a),i||s||nm(n,ke.default.vErrors)}_e.reportExtraError=u$;function l$(e,t){e.assign(ke.default.errors,t),e.if((0,B._)`${ke.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${ke.default.vErrors}.length`,t),()=>e.assign(ke.default.vErrors,null)))}_e.resetErrorsCount=l$;function d$({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,ke.default.errors,a=>{e.const(s,(0,B._)`${ke.default.vErrors}[${a}]`),e.if((0,B._)`${s}.instancePath === undefined`,()=>e.assign((0,B._)`${s}.instancePath`,(0,B.strConcat)(ke.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))})}_e.extendErrors=d$;function rm(e,t){let r=e.const("err",t);e.if((0,B._)`${ke.default.vErrors} === null`,()=>e.assign(ke.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${ke.default.vErrors}.push(${r})`),e.code((0,B._)`${ke.default.errors}++`)}function nm(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 Ft={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 om(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:f$(e,t,r)}function f$(e,t,r={}){let{gen:n,it:o}=e,i=[p$(o,r),m$(e,r)];return h$(e,t,i),n.object(...i)}function p$({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,Zo.getErrorPath)(t,Zo.Type.Str)}`:e;return[ke.default.instancePath,(0,B.strConcat)(ke.default.instancePath,r)]}function m$({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,Zo.getErrorPath)(r,Zo.Type.Str)}`),[Ft.schemaPath,o]}function h$(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([Ft.keyword,o],[Ft.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Ft.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ft.schema,s],[Ft.parentSchema,(0,B._)`${u}${d}`],[ke.default.data,i]),l&&n.push([Ft.propertyName,l])}});var sm=v(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.boolOrEmptySchema=pr.topBoolOrEmptySchema=void 0;var g$=_n(),y$=C(),_$=dt(),w$={message:"boolean schema is false"};function v$(e){let{gen:t,schema:r,validateName:n}=e;r===!1?im(e,!1):typeof r=="object"&&r.$async===!0?t.return(_$.default.data):(t.assign((0,y$._)`${n}.errors`,null),t.return(!0))}pr.topBoolOrEmptySchema=v$;function b$(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),im(e)):r.var(t,!0)}pr.boolOrEmptySchema=b$;function im(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,g$.reportError)(o,w$,void 0,t)}});var ja=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.getRules=mr.isJSONType=void 0;var x$=["string","number","integer","boolean","null","object","array"],$$=new Set(x$);function k$(e){return typeof e=="string"&&$$.has(e)}mr.isJSONType=k$;function S$(){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:{}}}mr.getRules=S$});var Ma=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function E$({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&am(e,n)}$t.schemaHasRulesForType=E$;function am(e,t){return t.rules.some(r=>cm(e,r))}$t.shouldUseGroup=am;function cm(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))}$t.shouldUseRule=cm});var wn=v(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.reportTypeError=we.checkDataTypes=we.checkDataType=we.coerceAndCheckDataType=we.getJSONTypes=we.getSchemaTypes=we.DataType=void 0;var T$=ja(),R$=Ma(),P$=_n(),N=C(),um=q(),hr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(hr||(we.DataType=hr={}));function z$(e){let t=lm(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}we.getSchemaTypes=z$;function lm(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(T$.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}we.getJSONTypes=lm;function O$(e,t){let{gen:r,data:n,opts:o}=e,i=I$(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,R$.schemaHasRulesForType)(e,t[0]));if(s){let a=qa(t,n,o.strictNumbers,hr.Wrong);r.if(a,()=>{i.length?A$(e,t,i):Ba(e)})}return s}we.coerceAndCheckDataType=O$;var dm=new Set(["string","number","integer","boolean","null"]);function I$(e,t){return t?e.filter(r=>dm.has(r)||t==="array"&&r==="array"):[]}function A$(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(qa(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(dm.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),Ba(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),N$(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
3
+ var Bw=Object.create;var Ji=Object.defineProperty;var Zw=Object.getOwnPropertyDescriptor;var Uw=Object.getOwnPropertyNames;var Fw=Object.getPrototypeOf,Vw=Object.prototype.hasOwnProperty;var yt=(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),_l=(e,t)=>{for(var r in t)Ji(e,r,{get:t[r],enumerable:!0})},Kw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Uw(t))!Vw.call(e,o)&&o!==r&&Ji(e,o,{get:()=>t[o],enumerable:!(n=Zw(t,o))||n.enumerable});return e};var Yi=(e,t,r)=>(r=e!=null?Bw(Fw(e)):{},Kw(t||!e||!e.__esModule?Ji(r,"default",{value:e,enumerable:!0}):r,e));var fn=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 ln=class{};Z._CodeOrName=ln;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qt=class extends ln{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=qt;var Me=class extends ln{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 qt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Me;Z.nil=new Me("");function Kp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)ya(r,t[n]),r.push(e[++n]);return new Me(r)}Z._=Kp;var ga=new Me("+");function Hp(e,...t){let r=[dn(e[0])],n=0;for(;n<t.length;)r.push(ga),ya(r,t[n]),r.push(ga,dn(e[++n]));return Gx(r),new Me(r)}Z.str=Hp;function ya(e,t){t instanceof Me?e.push(...t._items):t instanceof qt?e.push(t):e.push(Qx(t))}Z.addCodeArg=ya;function Gx(e){let t=1;for(;t<e.length-1;){if(e[t]===ga){let r=Jx(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Jx(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof qt||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 qt))return`"${e}${t.slice(1)}`}function Yx(e,t){return t.emptyStr()?e:e.emptyStr()?t:Hp`${e}${t}`}Z.strConcat=Yx;function Qx(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:dn(Array.isArray(e)?e.join(","):e)}function Xx(e){return new Me(dn(e))}Z.stringify=Xx;function dn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=dn;function e$(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Me(`.${e}`):Kp`[${e}]`}Z.getProperty=e$;function t$(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Me(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=t$;function r$(e){return new Me(e.toString())}Z.regexpCode=r$});var va=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var Re=fn(),_a=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Co;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Co||(Pe.UsedValueState=Co={}));Pe.varKinds={const:new Re.Name("const"),let:new Re.Name("let"),var:new Re.Name("var")};var Do=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Re.Name?t:this.name(t)}name(t){return new Re.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}}};Pe.Scope=Do;var jo=class extends Re.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Re._)`.${new Re.Name(r)}[${n}]`}};Pe.ValueScopeName=jo;var n$=(0,Re._)`\n`,wa=class extends Do{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?n$:Re.nil}}get(){return this._scope}name(t){return new jo(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,Re._)`${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=Re.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,Co.Started);let u=r(l);if(u){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;i=(0,Re._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Re._)`${i}${u}${this.opts._n}`;else throw new _a(l);c.set(l,Co.Completed)})}return i}};Pe.ValueScope=wa});var C=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 L=fn(),Ve=va(),xt=fn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return xt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return xt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return xt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return xt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return xt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return xt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return xt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return xt.Name}});var Bo=va();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Bo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Bo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Bo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Bo.varKinds}});D.operators={GT:new L._Code(">"),GTE:new L._Code(">="),LT:new L._Code("<"),LTE:new L._Code("<="),EQ:new L._Code("==="),NEQ:new L._Code("!=="),NOT:new L._Code("!"),OR:new L._Code("||"),AND:new L._Code("&&"),ADD:new L._Code("+")};var dt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ba=class extends dt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ve.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=fr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},Mo=class extends dt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=fr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return qo(t,this.rhs)}},xa=class extends Mo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},$a=class extends dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ka=class extends dt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Sa=class extends dt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ea=class extends dt{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=fr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},pn=class extends dt{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)||(o$(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Ut(t,r.names),{})}},ft=class extends pn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ta=class extends pn{},dr=class extends ft{};dr.kind="else";var Bt=class e extends ft{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 dr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Wp(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=fr(this.condition,t,r),this}get names(){let t=super.names;return qo(t,this.condition),this.else&&Ut(t,this.else.names),t}};Bt.kind="if";var Zt=class extends ft{};Zt.kind="for";var Ra=class extends Zt{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=fr(this.iteration,t,r),this}get names(){return Ut(super.names,this.iteration.names)}},Pa=class extends Zt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ve.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)}},Lo=class extends Zt{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=fr(this.iterable,t,r),this}get names(){return Ut(super.names,this.iterable.names)}},mn=class extends ft{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)}};mn.kind="func";var hn=class extends pn{render(t){return"return "+super.render(t)}};hn.kind="return";var za=class extends ft{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&&Ut(t,this.catch.names),this.finally&&Ut(t,this.finally.names),t}},gn=class extends ft{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};gn.kind="catch";var yn=class extends ft{render(t){return"finally"+super.render(t)}};yn.kind="finally";var Oa=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Ve.Scope({parent:t}),this._nodes=[new Ta]}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 ba(t,i,n)),i}const(t,r,n){return this._def(Ve.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ve.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ve.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Mo(t,r,n))}add(t,r){return this._leafNode(new xa(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new Ea(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,L.addCodeArg)(r,o));return r.push("}"),new L._Code(r)}if(t,r,n){if(this._blockNode(new Bt(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 Bt(t))}else(){return this._elseNode(new dr)}endIf(){return this._endBlockNode(Bt,dr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ra(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ve.varKinds.var:Ve.varKinds.let){let s=this._scope.toName(t);return this._for(new Pa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ve.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof L.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,L._)`${s}.length`,a=>{this.var(i,(0,L._)`${s}[${a}]`),n(i)})}return this._for(new Lo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,L._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Lo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Zt)}label(t){return this._leafNode(new $a(t))}break(t){return this._leafNode(new ka(t))}return(t){let r=new hn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(hn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new za;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new gn(i),r(i)}return n&&(this._currNode=o.finally=new yn,this.code(n)),this._endBlockNode(gn,yn)}throw(t){return this._leafNode(new Sa(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=L.nil,n,o){return this._blockNode(new mn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(mn)}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 Bt))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=Oa;function Ut(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function qo(e,t){return t instanceof L._CodeOrName?Ut(e,t.names):e}function fr(e,t,r){if(e instanceof L.Name)return n(e);if(!o(e))return e;return new L._Code(e._items.reduce((i,s)=>(s instanceof L.Name&&(s=n(s)),s instanceof L._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof L._Code&&i._items.some(s=>s instanceof L.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function o$(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Wp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${Ia(e)}`}D.not=Wp;var i$=Gp(D.operators.AND);function s$(...e){return e.reduce(i$)}D.and=s$;var a$=Gp(D.operators.OR);function c$(...e){return e.reduce(a$)}D.or=c$;function Gp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${Ia(t)} ${e} ${Ia(r)}`}function Ia(e){return e instanceof L.Name?e:(0,L._)`(${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=C(),u$=fn();function l$(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=l$;function d$(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Qp(e,t),!Xp(t,e.self.RULES.all))}j.alwaysValidSchema=d$;function Qp(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]||rm(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=Qp;function Xp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=Xp;function f$(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=f$;function p$({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=p$;function m$(e){return em(decodeURIComponent(e))}j.unescapeFragment=m$;function h$(e){return encodeURIComponent(Na(e))}j.escapeFragment=h$;function Na(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Na;function em(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=em;function g$(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=g$;function Jp({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:Jp({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} || {}`),Ca(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:tm}),items:Jp({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 tm(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Ca(e,r,t),r}j.evaluatedPropsToName=tm;function Ca(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Ca;var Yp={};function y$(e,t){return e.scopeValue("func",{ref:t,code:Yp[t.code]||(Yp[t.code]=new u$._Code(t.code))})}j.useFunc=y$;var Aa;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Aa||(j.Type=Aa={}));function _$(e,t,r){if(e instanceof H.Name){let n=t===Aa.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():"/"+Na(e)}j.getErrorPath=_$;function rm(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=rm});var pt=v(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var ye=C(),w$={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};Da.default=w$});var _n=v(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.extendErrors=_e.resetErrorsCount=_e.reportExtraError=_e.reportError=_e.keyword$DataError=_e.keywordError=void 0;var B=C(),Zo=q(),ke=pt();_e.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};_e.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 v$(e,t=_e.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=im(e,t,r);n??(s||a)?nm(i,c):om(o,(0,B._)`[${c}]`)}_e.reportError=v$;function b$(e,t=_e.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=im(e,t,r);nm(o,a),i||s||om(n,ke.default.vErrors)}_e.reportExtraError=b$;function x$(e,t){e.assign(ke.default.errors,t),e.if((0,B._)`${ke.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${ke.default.vErrors}.length`,t),()=>e.assign(ke.default.vErrors,null)))}_e.resetErrorsCount=x$;function $$({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,ke.default.errors,a=>{e.const(s,(0,B._)`${ke.default.vErrors}[${a}]`),e.if((0,B._)`${s}.instancePath === undefined`,()=>e.assign((0,B._)`${s}.instancePath`,(0,B.strConcat)(ke.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))})}_e.extendErrors=$$;function nm(e,t){let r=e.const("err",t);e.if((0,B._)`${ke.default.vErrors} === null`,()=>e.assign(ke.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${ke.default.vErrors}.push(${r})`),e.code((0,B._)`${ke.default.errors}++`)}function om(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 Ft={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 im(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:k$(e,t,r)}function k$(e,t,r={}){let{gen:n,it:o}=e,i=[S$(o,r),E$(e,r)];return T$(e,t,i),n.object(...i)}function S$({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,Zo.getErrorPath)(t,Zo.Type.Str)}`:e;return[ke.default.instancePath,(0,B.strConcat)(ke.default.instancePath,r)]}function E$({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,Zo.getErrorPath)(r,Zo.Type.Str)}`),[Ft.schemaPath,o]}function T$(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([Ft.keyword,o],[Ft.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Ft.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ft.schema,s],[Ft.parentSchema,(0,B._)`${u}${d}`],[ke.default.data,i]),l&&n.push([Ft.propertyName,l])}});var am=v(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.boolOrEmptySchema=pr.topBoolOrEmptySchema=void 0;var R$=_n(),P$=C(),z$=pt(),O$={message:"boolean schema is false"};function I$(e){let{gen:t,schema:r,validateName:n}=e;r===!1?sm(e,!1):typeof r=="object"&&r.$async===!0?t.return(z$.default.data):(t.assign((0,P$._)`${n}.errors`,null),t.return(!0))}pr.topBoolOrEmptySchema=I$;function A$(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),sm(e)):r.var(t,!0)}pr.boolOrEmptySchema=A$;function sm(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,R$.reportError)(o,O$,void 0,t)}});var ja=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.getRules=mr.isJSONType=void 0;var N$=["string","number","integer","boolean","null","object","array"],C$=new Set(N$);function D$(e){return typeof e=="string"&&C$.has(e)}mr.isJSONType=D$;function j$(){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:{}}}mr.getRules=j$});var Ma=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function M$({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&cm(e,n)}$t.schemaHasRulesForType=M$;function cm(e,t){return t.rules.some(r=>um(e,r))}$t.shouldUseGroup=cm;function um(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))}$t.shouldUseRule=um});var wn=v(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.reportTypeError=we.checkDataTypes=we.checkDataType=we.coerceAndCheckDataType=we.getJSONTypes=we.getSchemaTypes=we.DataType=void 0;var L$=ja(),q$=Ma(),B$=_n(),N=C(),lm=q(),hr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(hr||(we.DataType=hr={}));function Z$(e){let t=dm(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}we.getSchemaTypes=Z$;function dm(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(L$.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}we.getJSONTypes=dm;function U$(e,t){let{gen:r,data:n,opts:o}=e,i=F$(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,q$.schemaHasRulesForType)(e,t[0]));if(s){let a=qa(t,n,o.strictNumbers,hr.Wrong);r.if(a,()=>{i.length?V$(e,t,i):Ba(e)})}return s}we.coerceAndCheckDataType=U$;var fm=new Set(["string","number","integer","boolean","null"]);function F$(e,t){return t?e.filter(r=>fm.has(r)||t==="array"&&r==="array"):[]}function V$(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(qa(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(fm.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),Ba(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),K$(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
5
5
  || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":n.elseIf((0,N._)`${s} === "boolean" || ${o} === null
6
6
  || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":n.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,N._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function N$({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function La(e,t,r,n=hr.Correct){let o=n===hr.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===hr.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}we.checkDataType=La;function qa(e,t,r,n){if(e.length===1)return La(e[0],t,r,n);let o,i=(0,um.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,La(s,t,r,n));return o}we.checkDataTypes=qa;var C$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function Ba(e){let t=D$(e);(0,P$.reportError)(t,C$)}we.reportTypeError=Ba;function D$(e){let{gen:t,data:r,schema:n}=e,o=(0,um.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var pm=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.assignDefaults=void 0;var gr=C(),j$=q();function M$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)fm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>fm(e,i,o.default))}Uo.assignDefaults=M$;function fm(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,gr._)`${i}${(0,gr.getProperty)(t)}`;if(o){(0,j$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,gr._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,gr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,gr._)`${a} = ${(0,gr.stringify)(r)}`)}});var Le=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=C(),Za=q(),kt=dt(),L$=q();function q$(e,t){let{gen:r,data:n,it:o}=e;r.if(Fa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=q$;function B$({gen:e,data:t,it:{opts:r}},n,o){return(0,ee.or)(...n.map(i=>(0,ee.and)(Fa(e,t,i,r.ownProperties),(0,ee._)`${o} = ${i}`)))}K.checkMissingProp=B$;function Z$(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=Z$;function mm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=mm;function Ua(e,t,r){return(0,ee._)`${mm(e)}.call(${t}, ${r})`}K.isOwnProperty=Ua;function U$(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} !== undefined`;return n?(0,ee._)`${o} && ${Ua(e,t,r)}`:o}K.propertyInData=U$;function Fa(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} === undefined`;return n?(0,ee.or)(o,(0,ee.not)(Ua(e,t,r))):o}K.noPropertyInData=Fa;function hm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=hm;function F$(e,t){return hm(t).filter(r=>!(0,Za.alwaysValidSchema)(e,t[r]))}K.schemaProperties=F$;function V$({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=[[kt.default.instancePath,(0,ee.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.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=V$;var K$=(0,ee._)`new RegExp`;function H$({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"?K$:(0,L$.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=H$;function W$(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:Za.Type.Num},i),t.if((0,ee.not)(i),a)})}}K.validateArray=W$;function G$(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,Za.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=G$});var _m=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateKeywordUsage=et.validSchemaType=et.funcKeywordCode=et.macroKeywordCode=void 0;var Se=C(),Vt=dt(),J$=Le(),Y$=_n();function Q$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=ym(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Se.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}et.macroKeywordCode=Q$;function X$(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;t0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=ym(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&&gm(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&gm(e),_(()=>e0(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Se._)`await `),b=>n.assign(d,!1).if((0,Se._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Se._)`${b}.errors`),()=>n.throw(b))),w}function m(){let w=(0,Se._)`${u}.errors`;return n.assign(w,null),h(Se.nil),w}function h(w=t.async?(0,Se._)`await `:Se.nil){let b=c.opts.passContext?Vt.default.this:Vt.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Se._)`${w}${(0,J$.callValidateCode)(e,u,b,x)}`,t.modifying)}function _(w){var b;n.if((0,Se.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}et.funcKeywordCode=X$;function gm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Se._)`${n.parentData}[${n.parentDataProperty}]`))}function e0(e,t){let{gen:r}=e;r.if((0,Se._)`Array.isArray(${t})`,()=>{r.assign(Vt.default.vErrors,(0,Se._)`${Vt.default.vErrors} === null ? ${t} : ${Vt.default.vErrors}.concat(${t})`).assign(Vt.default.errors,(0,Se._)`${Vt.default.vErrors}.length`),(0,Y$.extendErrors)(e)},()=>e.error())}function t0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function ym(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,Se.stringify)(r)})}function r0(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")}et.validSchemaType=r0;function n0({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)}}et.validateKeywordUsage=n0});var vm=v(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.extendSubschemaMode=St.extendSubschemaData=St.getSubschema=void 0;var tt=C(),wm=q();function o0(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,tt._)`${e.schemaPath}${(0,tt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,tt._)`${e.schemaPath}${(0,tt.getProperty)(t)}${(0,tt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,wm.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')}St.getSubschema=o0;function i0(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,tt._)`${t.data}${(0,tt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,tt.str)`${l}${(0,wm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,tt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof tt.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]}}St.extendSubschemaData=i0;function s0(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}St.extendSubschemaMode=s0});var Va=v((lM,bm)=>{"use strict";bm.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 $m=v((dM,xm)=>{"use strict";var Et=xm.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(){};Fo(t,n,o,e,"",e)};Et.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Et.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Et.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Et.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 Fo(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 Et.arrayKeywords)for(var f=0;f<d.length;f++)Fo(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in Et.propsKeywords){if(d&&typeof d=="object")for(var p in d)Fo(e,t,r,d[p],o+"/"+u+"/"+a0(p),i,o,u,n,p)}else(u in Et.keywords||e.allKeys&&!(u in Et.skipKeywords))&&Fo(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function a0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var vn=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.getSchemaRefs=ze.resolveUrl=ze.normalizeId=ze._getFullPath=ze.getFullPath=ze.inlineRef=void 0;var c0=q(),u0=Va(),l0=$m(),d0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function f0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ka(e):t?km(e)<=t:!1}ze.inlineRef=f0;var p0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ka(e){for(let t in e){if(p0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ka)||typeof r=="object"&&Ka(r))return!0}return!1}function km(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!d0.has(r)&&(typeof e[r]=="object"&&(0,c0.eachItem)(e[r],n=>t+=km(n)),t===1/0))return 1/0}return t}function Sm(e,t="",r){r!==!1&&(t=yr(t));let n=e.parse(t);return Em(e,n)}ze.getFullPath=Sm;function Em(e,t){return e.serialize(t).split("#")[0]+"#"}ze._getFullPath=Em;var m0=/#\/?$/;function yr(e){return e?e.replace(m0,""):""}ze.normalizeId=yr;function h0(e,t,r){return r=yr(r),e.resolve(t,r)}ze.resolveUrl=h0;var g0=/^[a-z_][-a-z0-9._]*$/i;function y0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=yr(e[r]||t),i={"":o},s=Sm(n,o,!1),a={},c=new Set;return l0(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])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let R=this.opts.uriResolver.resolve;if(x=yr(_?R(_,x):x),c.has(x))throw u(x);c.add(x);let O=this.refs[x];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,x):x!==yr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!g0.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!u0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ze.getSchemaRefs=y0});var $n=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Om=sm(),Tm=wn(),Wa=Ma(),Vo=wn(),_0=pm(),xn=_m(),Ha=vm(),S=C(),A=dt(),w0=vn(),ft=q(),bn=_n();function v0(e){if(Nm(e)&&(Cm(e),Am(e))){$0(e);return}Im(e,()=>(0,Om.topBoolOrEmptySchema)(e))}Tt.validateFunctionCode=v0;function Im({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Rm(r,o)}`),x0(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${b0(o)}`,n.$async,()=>e.code(Rm(r,o)).code(i))}function b0(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function x0(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function $0(e){let{schema:t,opts:r,gen:n}=e;Im(e,()=>{r.$comment&&t.$comment&&jm(e),R0(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&k0(e),Dm(e),O0(e)})}function k0(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Rm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function S0(e,t){if(Nm(e)&&(Cm(e),Am(e))){E0(e,t);return}(0,Om.boolOrEmptySchema)(e,t)}function Am({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 Nm(e){return typeof e.schema!="boolean"}function E0(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&jm(e),P0(e),z0(e);let i=n.const("_errs",A.default.errors);Dm(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function Cm(e){(0,ft.checkUnknownRules)(e),T0(e)}function Dm(e,t){if(e.opts.jtd)return Pm(e,[],!1,t);let r=(0,Tm.getSchemaTypes)(e.schema),n=(0,Tm.coerceAndCheckDataType)(e,r);Pm(e,r,!n,t)}function T0(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ft.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function R0(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ft.checkStrictMode)(e,"default is ignored in the schema root")}function P0(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,w0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function z0(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function jm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function O0(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&I0(e),t.return((0,S._)`${A.default.errors} === 0`))}function I0({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function Pm(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,ft.schemaHasRulesButRef)(i,u))){o.block(()=>Lm(e,"$ref",u.all.$ref.definition));return}c.jtd||A0(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Wa.shouldUseGroup)(i,f)&&(f.type?(o.if((0,Vo.checkDataType)(f.type,s,c.strictNumbers)),zm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,Vo.reportTypeError)(e)),o.endIf()):zm(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function zm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,_0.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Wa.shouldUseRule)(n,i)&&Lm(e,i.keyword,i.definition,t.type)})}function A0(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(N0(e,t),e.opts.allowUnionTypes||C0(e,t),D0(e,e.dataTypes))}function N0(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Mm(e.dataTypes,r)||Ga(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),M0(e,t)}}function C0(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ga(e,"use allowUnionTypes to allow union type keyword")}function D0(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Wa.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>j0(t,s))&&Ga(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function j0(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Mm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function M0(e,t){let r=[];for(let n of e.dataTypes)Mm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ga(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ft.checkStrictMode)(e,t,e.opts.strictTypes)}var Ko=class{constructor(t,r,n){if((0,xn.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,ft.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",qm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,xn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",A.default.errors))}result(t,r,n){this.failResult((0,S.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,S.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,S._)`${r} !== undefined && (${(0,S.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?bn.reportExtraError:bn.reportError)(this,this.def.error,r)}$dataError(){(0,bn.reportError)(this,this.def.$dataError||bn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,bn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,Vo.checkDataTypes)(c,r,i.opts.strictNumbers,Vo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,Ha.getSubschema)(this.it,t);(0,Ha.extendSubschemaData)(n,this.it,t),(0,Ha.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return S0(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ft.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ft.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};Tt.KeywordCxt=Ko;function Lm(e,t,r,n){let o=new Ko(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,xn.funcKeywordCode)(o,r):"macro"in r?(0,xn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,xn.funcKeywordCode)(o,r)}var L0=/^\/(?:[^~]|~0|~1)*$/,q0=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function qm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!L0.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=q0.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ft.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Tt.getData=qm});var Ho=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Ja=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ya.default=Ja});var kn=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Qa=vn(),Xa=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qa.resolveUrl)(t,r,n),this.missingSchema=(0,Qa.normalizeId)((0,Qa.getFullPath)(t,this.missingRef))}};ec.default=Xa});var Go=v(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.resolveSchema=qe.getCompilingSchema=qe.resolveRef=qe.compileSchema=qe.SchemaEnv=void 0;var Ke=C(),B0=Ho(),Kt=dt(),He=vn(),Bm=q(),Z0=$n(),_r=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,He.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};qe.SchemaEnv=_r;function rc(e){let t=Zm.call(this,e);if(t)return t;let r=(0,He.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ke.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:B0.default,code:(0,Ke._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[Ke.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ke.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ke.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ke._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,Z0.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Kt.default.self}`,`${Kt.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 Ke.Name?void 0:m,items:h instanceof Ke.Name?void 0:h,dynamicProps:m instanceof Ke.Name,dynamicItems:h instanceof Ke.Name},p.source&&(p.source.evaluated=(0,Ke.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)}}qe.compileSchema=rc;function U0(e,t,r){var n;r=(0,He.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=K0.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 _r({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=F0.call(this,i)}qe.resolveRef=U0;function F0(e){return(0,He.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:rc.call(this,e)}function Zm(e){for(let t of this._compilations)if(V0(t,e))return t}qe.getCompilingSchema=Zm;function V0(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function K0(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Wo.call(this,e,t)}function Wo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,He._getFullPath)(this.opts.uriResolver,r),o=(0,He.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return tc.call(this,r,e);let i=(0,He.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Wo.call(this,e,s);return typeof a?.schema!="object"?void 0:tc.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||rc.call(this,s),i===(0,He.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,He.resolveUrl)(this.opts.uriResolver,o,l)),new _r({schema:a,schemaId:c,root:e,baseId:o})}return tc.call(this,r,s)}}qe.resolveSchema=Wo;var H0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tc(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,Bm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!H0.has(a)&&l&&(t=(0,He.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Bm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,He.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Wo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new _r({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var Um=v((yM,W0)=>{W0.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 ic=v((_M,Gm)=>{"use strict";var G0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Vm=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),nc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Km=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),J0=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function oc(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 Y0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fm(e){return e.length=0,!0}function Q0(e,t,r){if(e.length){let n=oc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function X0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=Q0;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=Fm}else{o.push(l);continue}}return o.length&&(a===Fm?r.zone=o.join(""):s?n.push(o.join("")):n.push(oc(o))),r.address=n.join(""),r}function Hm(e){if(ek(e,":")<2)return{host:e,isIPV6:!1};let t=X0(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 ek(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function tk(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 rk={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},nk=/[@/?#:]/g,ok=/[@/?#]/g;function Wm(e,t){let r=t?ok:nk;return r.lastIndex=0,e.replace(r,n=>rk[n])}function ik(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(nc(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Km(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function sk(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(nc(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Km(i)?t+=i:t+="%"+o,r+=2;continue}}J0(e[r])?t+=e[r]:t+=escape(e[r])}return t}function ak(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(nc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function ck(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Vm(r)){let n=Hm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Wm(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}Gm.exports={nonSimpleDomain:Y0,recomposeAuthority:ck,reescapeHostDelimiters:Wm,normalizePercentEncoding:ik,normalizePathEncoding:sk,escapePreservingEscapes:ak,removeDotSegments:tk,isIPv4:Vm,isUUID:G0,normalizeIPv6:Hm,stringArrayToHexStripped:oc}});var eh=v((wM,Xm)=>{"use strict";var{isUUID:uk}=ic(),lk=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dk=["http","https","ws","wss","urn","urn:uuid"];function fk(e){return dk.indexOf(e)!==-1}function sc(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 Jm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Ym(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 pk(e){return e.secure=sc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function mk(e){if((e.port===(sc(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 hk(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(lk);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=ac(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function gk(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=ac(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 yk(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!uk(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function _k(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Qm={scheme:"http",domainHost:!0,parse:Jm,serialize:Ym},wk={scheme:"https",domainHost:Qm.domainHost,parse:Jm,serialize:Ym},Jo={scheme:"ws",domainHost:!0,parse:pk,serialize:mk},vk={scheme:"wss",domainHost:Jo.domainHost,parse:Jo.parse,serialize:Jo.serialize},bk={scheme:"urn",parse:hk,serialize:gk,skipNormalize:!0},xk={scheme:"urn:uuid",parse:yk,serialize:_k,skipNormalize:!0},Yo={http:Qm,https:wk,ws:Jo,wss:vk,urn:bk,"urn:uuid":xk};Object.setPrototypeOf(Yo,null);function ac(e){return e&&(Yo[e]||Yo[e.toLowerCase()])||void 0}Xm.exports={wsIsSecure:sc,SCHEMES:Yo,isValidSchemeName:fk,getSchemeHandler:ac}});var sh=v((vM,Qo)=>{"use strict";var{normalizeIPv6:$k,removeDotSegments:Sn,recomposeAuthority:kk,normalizePercentEncoding:Sk,normalizePathEncoding:Ek,escapePreservingEscapes:Tk,reescapeHostDelimiters:Rk,isIPv4:Pk,nonSimpleDomain:zk}=ic(),{SCHEMES:Ok,getSchemeHandler:rh}=eh();function Ik(e,t){return typeof e=="string"?e=jk(e,t):typeof e=="object"&&(e=wr(Ht(e,t),t)),e}function Ak(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=nh(wr(e,n),wr(t,n),n,!0);return n.skipEscape=!0,Ht(o,n)}function nh(e,t,r,n){let o={};return n||(e=wr(Ht(e,r),r),t=wr(Ht(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=Sn(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=Sn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Sn(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=Sn(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 Nk(e,t,r){let n=th(e,r),o=th(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ht(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=rh(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Sk(r.path):(r.path=Tk(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=kk(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=Sn(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 Ck=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dk(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 oh(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(Ck);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=Dk(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(Pk(n.host)===!1){let u=$k(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=rh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&zk(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=Rk(unescape(n.host),i))),n.path&&(n.path=Ek(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 wr(e,t){return oh(e,t).parsed}function jk(e,t){return ih(e,t).normalized}function ih(e,t){let{parsed:r,malformedAuthorityOrPort:n}=oh(e,t);return{normalized:n?e:Ht(r,t),malformedAuthorityOrPort:n}}function th(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=ih(e,t);return n?void 0:r}if(typeof e=="object")return Ht(e,t)}var cc={SCHEMES:Ok,normalize:Ik,resolve:Ak,resolveComponent:nh,equal:Nk,serialize:Ht,parse:wr};Qo.exports=cc;Qo.exports.default=cc;Qo.exports.fastUri=cc});var ch=v(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var ah=sh();ah.code='require("ajv/dist/runtime/uri").default';uc.default=ah});var gh=v(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.CodeGen=pe.Name=pe.nil=pe.stringify=pe.str=pe._=pe.KeywordCxt=void 0;var Mk=$n();Object.defineProperty(pe,"KeywordCxt",{enumerable:!0,get:function(){return Mk.KeywordCxt}});var vr=C();Object.defineProperty(pe,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(pe,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(pe,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(pe,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(pe,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(pe,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var Lk=Ho(),ph=kn(),qk=ja(),En=Go(),Bk=C(),Tn=vn(),Xo=wn(),dc=q(),uh=Um(),Zk=ch(),mh=(e,t)=>new RegExp(e,t);mh.code="new RegExp";var Uk=["removeAdditional","useDefaults","coerceTypes"],Fk=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Vk={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."},Kk={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lh=200;function Hk(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,b,x,R,O,xe,Ne,nr,Wi;let qr=e.strict,Gi=(t=e.code)===null||t===void 0?void 0:t.optimize,hl=Gi===!0||Gi===void 0?1:Gi||0,gl=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:mh,Rw=(o=e.uriResolver)!==null&&o!==void 0?o:Zk.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:qr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:qr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:qr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:qr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:qr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:hl,regExp:gl}:{optimize:hl,regExp:gl},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:lh,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:lh,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(xe=e.validateSchema)!==null&&xe!==void 0?xe:!0,validateFormats:(Ne=e.validateFormats)!==null&&Ne!==void 0?Ne:!0,unicodeRegExp:(nr=e.unicodeRegExp)!==null&&nr!==void 0?nr:!0,int32range:(Wi=e.int32range)!==null&&Wi!==void 0?Wi:!0,uriResolver:Rw}}var Rn=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,...Hk(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Bk.ValueScope({scope:{},prefixes:Fk,es5:r,lines:n}),this.logger=Xk(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,qk.getRules)(),dh.call(this,Vk,t,"NOT SUPPORTED"),dh.call(this,Kk,t,"DEPRECATED","warn"),this._metaOpts=Yk.call(this),t.formats&&Gk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Jk.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Wk.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=uh;n==="id"&&(o={...uh},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 ph.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,Tn.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=fh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new En.SchemaEnv({schema:{},schemaId:n});if(r=En.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=fh.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,Tn.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(tS.call(this,n,r),!r)return(0,dc.eachItem)(n,i=>lc.call(this,i)),this;nS.call(this,r);let o={...r,type:(0,Xo.getJSONTypes)(r.type),schemaType:(0,Xo.getJSONTypes)(r.schemaType)};return(0,dc.eachItem)(n,o.type.length===0?i=>lc.call(this,i,o):i=>o.type.forEach(s=>lc.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]=hh(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,Tn.normalizeId)(s||n);let l=Tn.getSchemaRefs.call(this,t,n);return c=new En.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):En.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{En.compileSchema.call(this,t)}finally{this.opts=r}}};Rn.ValidationError=Lk.default;Rn.MissingRefError=ph.default;pe.default=Rn;function dh(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 fh(e){return e=(0,Tn.normalizeId)(e),this.schemas[e]||this.refs[e]}function Wk(){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 Gk(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Jk(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 Yk(){let e={...this.opts};for(let t of Uk)delete e[t];return e}var Qk={log(){},warn(){},error(){}};function Xk(e){if(e===!1)return Qk;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 eS=/^[a-z_$][a-z0-9_$:-]*$/i;function tS(e,t){let{RULES:r}=this;if((0,dc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!eS.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 lc(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,Xo.getJSONTypes)(t.type),schemaType:(0,Xo.getJSONTypes)(t.schemaType)}};t.before?rS.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 rS(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 nS(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=hh(t)),e.validateSchema=this.compile(t,!0))}var oS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function hh(e){return{anyOf:[e,oS]}}});var yh=v(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var iS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};fc.default=iS});var bh=v(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.callRef=Wt.getValidate=void 0;var sS=kn(),_h=Le(),Oe=C(),br=dt(),wh=Go(),ei=q(),aS={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=wh.resolveRef.call(c,l,o,r);if(u===void 0)throw new sS.default(n.opts.uriResolver,o,r);if(u instanceof wh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return ti(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return ti(e,(0,Oe._)`${m}.validate`,l,l.$async)}function f(m){let h=vh(e,m);ti(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Oe.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Oe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function vh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Oe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Wt.getValidate=vh;function ti(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?br.default.this:Oe.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,Oe._)`await ${(0,_h.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Oe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,_h.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Oe._)`${m}.errors`;o.assign(br.default.vErrors,(0,Oe._)`${br.default.vErrors} === null ? ${h} : ${br.default.vErrors}.concat(${h})`),o.assign(br.default.errors,(0,Oe._)`${br.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=ei.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Oe._)`${m}.evaluated.props`);i.props=ei.mergeEvaluated.props(o,w,i.props,Oe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=ei.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Oe._)`${m}.evaluated.items`);i.items=ei.mergeEvaluated.items(o,w,i.items,Oe.Name)}}}Wt.callRef=ti;Wt.default=aS});var xh=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var cS=yh(),uS=bh(),lS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cS.default,uS.default];pc.default=lS});var $h=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ri=C(),Rt=ri.operators,ni={maximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},minimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},exclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},exclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},dS={message:({keyword:e,schemaCode:t})=>(0,ri.str)`must be ${ni[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ri._)`{comparison: ${ni[e].okStr}, limit: ${t}}`},fS={keyword:Object.keys(ni),type:"number",schemaType:"number",$data:!0,error:dS,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ri._)`${r} ${ni[t].fail} ${n} || isNaN(${r})`)}};mc.default=fS});var kh=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Pn=C(),pS={message:({schemaCode:e})=>(0,Pn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Pn._)`{multipleOf: ${e}}`},mS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:pS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Pn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Pn._)`${s} !== parseInt(${s})`;e.fail$data((0,Pn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};hc.default=mS});var Eh=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});function Sh(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}gc.default=Sh;Sh.code='require("ajv/dist/runtime/ucs2length").default'});var Th=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Gt=C(),hS=q(),gS=Eh(),yS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Gt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Gt._)`{limit: ${e}}`},_S={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Gt.operators.GT:Gt.operators.LT,s=o.opts.unicode===!1?(0,Gt._)`${r}.length`:(0,Gt._)`${(0,hS.useFunc)(e.gen,gS.default)}(${r})`;e.fail$data((0,Gt._)`${s} ${i} ${n}`)}};yc.default=_S});var Rh=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var wS=Le(),vS=q(),xr=C(),bS={message:({schemaCode:e})=>(0,xr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,xr._)`{pattern: ${e}}`},xS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:bS,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,xr._)`new RegExp`:(0,vS.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,xr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,xr._)`!${u}`)}else{let c=(0,wS.usePattern)(e,o);e.fail$data((0,xr._)`!${c}.test(${r})`)}}};_c.default=xS});var Ph=v(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var zn=C(),$S={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,zn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,zn._)`{limit: ${e}}`},kS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$S,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?zn.operators.GT:zn.operators.LT;e.fail$data((0,zn._)`Object.keys(${r}).length ${o} ${n}`)}};wc.default=kS});var zh=v(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var On=Le(),In=C(),SS=q(),ES={message:({params:{missingProperty:e}})=>(0,In.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,In._)`{missingProperty: ${e}}`},TS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ES,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,SS.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(In.nil,d);else for(let p of r)(0,On.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,On.checkMissingProp)(e,r,p)),(0,On.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,On.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,On.propertyInData)(t,o,p,a.ownProperties)),t.if((0,In.not)(m),()=>{e.error(),t.break()})},In.nil)}}};vc.default=TS});var Oh=v(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var An=C(),RS={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,An.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,An._)`{limit: ${e}}`},PS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:RS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?An.operators.GT:An.operators.LT;e.fail$data((0,An._)`${r}.length ${o} ${n}`)}};bc.default=PS});var oi=v(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Ih=Va();Ih.code='require("ajv/dist/runtime/equal").default';xc.default=Ih});var Ah=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var $c=wn(),me=C(),zS=q(),OS=oi(),IS={message:({params:{i:e,j:t}})=>(0,me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,me._)`{i: ${e}, j: ${t}}`},AS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:IS,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,$c.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,me._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,me._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,me._)`${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,$c.checkDataTypes)(l,_,a.opts.strictNumbers,$c.DataType.Wrong),b=t.const("indices",(0,me._)`{}`);t.for((0,me._)`;${m}--;`,()=>{t.let(_,(0,me._)`${r}[${m}]`),t.if(w,(0,me._)`continue`),l.length>1&&t.if((0,me._)`typeof ${_} == "string"`,(0,me._)`${_} += "_"`),t.if((0,me._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(h,(0,me._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,me._)`${b}[${_}] = ${m}`)})}function p(m,h){let _=(0,zS.useFunc)(t,OS.default),w=t.name("outer");t.label(w).for((0,me._)`;${m}--;`,()=>t.for((0,me._)`${h} = ${m}; ${h}--;`,()=>t.if((0,me._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};kc.default=AS});var Nh=v(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Sc=C(),NS=q(),CS=oi(),DS={message:"must be equal to constant",params:({schemaCode:e})=>(0,Sc._)`{allowedValue: ${e}}`},jS={keyword:"const",$data:!0,error:DS,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Sc._)`!${(0,NS.useFunc)(t,CS.default)}(${r}, ${o})`):e.fail((0,Sc._)`${i} !== ${r}`)}};Ec.default=jS});var Ch=v(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Nn=C(),MS=q(),LS=oi(),qS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Nn._)`{allowedValues: ${e}}`},BS={keyword:"enum",schemaType:"array",$data:!0,error:qS,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,MS.useFunc)(t,LS.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,Nn.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,Nn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Nn._)`${l()}(${r}, ${p}[${m}])`:(0,Nn._)`${r} === ${h}`}}};Tc.default=BS});var Dh=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var ZS=$h(),US=kh(),FS=Th(),VS=Rh(),KS=Ph(),HS=zh(),WS=Oh(),GS=Ah(),JS=Nh(),YS=Ch(),QS=[ZS.default,US.default,FS.default,VS.default,KS.default,HS.default,WS.default,GS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},JS.default,YS.default];Rc.default=QS});var zc=v(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.validateAdditionalItems=void 0;var Jt=C(),Pc=q(),XS={message:({params:{len:e}})=>(0,Jt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Jt._)`{limit: ${e}}`},eE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:XS,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Pc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}jh(e,n)}};function jh(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Jt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Jt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Jt._)`${a} <= ${t.length}`);r.if((0,Jt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Pc.Type.Num},l),s.allErrors||r.if((0,Jt.not)(l),()=>r.break())})}}Cn.validateAdditionalItems=jh;Cn.default=eE});var Oc=v(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.validateTuple=void 0;var Mh=C(),ii=q(),tE=Le(),rE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Lh(e,"additionalItems",t);r.items=!0,!(0,ii.alwaysValidSchema)(r,t)&&e.ok((0,tE.validateArray)(e))}};function Lh(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=ii.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Mh._)`${i}.length`);r.forEach((d,f)=>{(0,ii.alwaysValidSchema)(a,d)||(n.if((0,Mh._)`${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,ii.checkStrictMode)(a,_,f.strictTuples)}}}Dn.validateTuple=Lh;Dn.default=rE});var qh=v(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var nE=Oc(),oE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,nE.validateTuple)(e,"items")};Ic.default=oE});var Zh=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Bh=C(),iE=q(),sE=Le(),aE=zc(),cE={message:({params:{len:e}})=>(0,Bh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Bh._)`{limit: ${e}}`},uE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cE,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,iE.alwaysValidSchema)(n,t)&&(o?(0,aE.validateAdditionalItems)(e,o):e.ok((0,sE.validateArray)(e)))}};Ac.default=uE});var Uh=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Be=C(),si=q(),lE={message:({params:{min:e,max:t}})=>t===void 0?(0,Be.str)`must contain at least ${e} valid item(s)`:(0,Be.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Be._)`{minContains: ${e}}`:(0,Be._)`{minContains: ${e}, maxContains: ${t}}`},dE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lE,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,Be._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,si.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,si.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,si.alwaysValidSchema)(i,r)){let h=(0,Be._)`${u} >= ${s}`;a!==void 0&&(h=(0,Be._)`${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,Be._)`${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:si.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Be._)`${h}++`),a===void 0?t.if((0,Be._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Be._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Be._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};Nc.default=dE});var Kh=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.validateSchemaDeps=rt.validatePropertyDeps=rt.error=void 0;var Cc=C(),fE=q(),jn=Le();rt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Cc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Cc._)`{property: ${e},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function K$({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function La(e,t,r,n=hr.Correct){let o=n===hr.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===hr.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}we.checkDataType=La;function qa(e,t,r,n){if(e.length===1)return La(e[0],t,r,n);let o,i=(0,lm.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,La(s,t,r,n));return o}we.checkDataTypes=qa;var H$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function Ba(e){let t=W$(e);(0,B$.reportError)(t,H$)}we.reportTypeError=Ba;function W$(e){let{gen:t,data:r,schema:n}=e,o=(0,lm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var mm=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.assignDefaults=void 0;var gr=C(),G$=q();function J$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)pm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>pm(e,i,o.default))}Uo.assignDefaults=J$;function pm(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,gr._)`${i}${(0,gr.getProperty)(t)}`;if(o){(0,G$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,gr._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,gr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,gr._)`${a} = ${(0,gr.stringify)(r)}`)}});var Le=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=C(),Za=q(),kt=pt(),Y$=q();function Q$(e,t){let{gen:r,data:n,it:o}=e;r.if(Fa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=Q$;function X$({gen:e,data:t,it:{opts:r}},n,o){return(0,ee.or)(...n.map(i=>(0,ee.and)(Fa(e,t,i,r.ownProperties),(0,ee._)`${o} = ${i}`)))}K.checkMissingProp=X$;function ek(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=ek;function hm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=hm;function Ua(e,t,r){return(0,ee._)`${hm(e)}.call(${t}, ${r})`}K.isOwnProperty=Ua;function tk(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} !== undefined`;return n?(0,ee._)`${o} && ${Ua(e,t,r)}`:o}K.propertyInData=tk;function Fa(e,t,r,n){let o=(0,ee._)`${t}${(0,ee.getProperty)(r)} === undefined`;return n?(0,ee.or)(o,(0,ee.not)(Ua(e,t,r))):o}K.noPropertyInData=Fa;function gm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=gm;function rk(e,t){return gm(t).filter(r=>!(0,Za.alwaysValidSchema)(e,t[r]))}K.schemaProperties=rk;function nk({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=[[kt.default.instancePath,(0,ee.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.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=nk;var ok=(0,ee._)`new RegExp`;function ik({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"?ok:(0,Y$.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=ik;function sk(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:Za.Type.Num},i),t.if((0,ee.not)(i),a)})}}K.validateArray=sk;function ak(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,Za.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=ak});var wm=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.validateKeywordUsage=rt.validSchemaType=rt.funcKeywordCode=rt.macroKeywordCode=void 0;var Se=C(),Vt=pt(),ck=Le(),uk=_n();function lk(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=_m(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Se.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}rt.macroKeywordCode=lk;function dk(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;pk(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=_m(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&&ym(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&ym(e),_(()=>fk(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Se._)`await `),b=>n.assign(d,!1).if((0,Se._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Se._)`${b}.errors`),()=>n.throw(b))),w}function m(){let w=(0,Se._)`${u}.errors`;return n.assign(w,null),h(Se.nil),w}function h(w=t.async?(0,Se._)`await `:Se.nil){let b=c.opts.passContext?Vt.default.this:Vt.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Se._)`${w}${(0,ck.callValidateCode)(e,u,b,x)}`,t.modifying)}function _(w){var b;n.if((0,Se.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}rt.funcKeywordCode=dk;function ym(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Se._)`${n.parentData}[${n.parentDataProperty}]`))}function fk(e,t){let{gen:r}=e;r.if((0,Se._)`Array.isArray(${t})`,()=>{r.assign(Vt.default.vErrors,(0,Se._)`${Vt.default.vErrors} === null ? ${t} : ${Vt.default.vErrors}.concat(${t})`).assign(Vt.default.errors,(0,Se._)`${Vt.default.vErrors}.length`),(0,uk.extendErrors)(e)},()=>e.error())}function pk({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function _m(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,Se.stringify)(r)})}function mk(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")}rt.validSchemaType=mk;function hk({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)}}rt.validateKeywordUsage=hk});var bm=v(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.extendSubschemaMode=St.extendSubschemaData=St.getSubschema=void 0;var nt=C(),vm=q();function gk(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,nt._)`${e.schemaPath}${(0,nt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,nt._)`${e.schemaPath}${(0,nt.getProperty)(t)}${(0,nt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,vm.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')}St.getSubschema=gk;function yk(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,nt._)`${t.data}${(0,nt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,nt.str)`${l}${(0,vm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,nt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof nt.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]}}St.extendSubschemaData=yk;function _k(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}St.extendSubschemaMode=_k});var Va=v((kM,xm)=>{"use strict";xm.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 km=v((SM,$m)=>{"use strict";var Et=$m.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(){};Fo(t,n,o,e,"",e)};Et.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Et.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Et.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Et.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 Fo(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 Et.arrayKeywords)for(var f=0;f<d.length;f++)Fo(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in Et.propsKeywords){if(d&&typeof d=="object")for(var p in d)Fo(e,t,r,d[p],o+"/"+u+"/"+wk(p),i,o,u,n,p)}else(u in Et.keywords||e.allKeys&&!(u in Et.skipKeywords))&&Fo(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function wk(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var vn=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.getSchemaRefs=ze.resolveUrl=ze.normalizeId=ze._getFullPath=ze.getFullPath=ze.inlineRef=void 0;var vk=q(),bk=Va(),xk=km(),$k=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kk(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ka(e):t?Sm(e)<=t:!1}ze.inlineRef=kk;var Sk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ka(e){for(let t in e){if(Sk.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ka)||typeof r=="object"&&Ka(r))return!0}return!1}function Sm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!$k.has(r)&&(typeof e[r]=="object"&&(0,vk.eachItem)(e[r],n=>t+=Sm(n)),t===1/0))return 1/0}return t}function Em(e,t="",r){r!==!1&&(t=yr(t));let n=e.parse(t);return Tm(e,n)}ze.getFullPath=Em;function Tm(e,t){return e.serialize(t).split("#")[0]+"#"}ze._getFullPath=Tm;var Ek=/#\/?$/;function yr(e){return e?e.replace(Ek,""):""}ze.normalizeId=yr;function Tk(e,t,r){return r=yr(r),e.resolve(t,r)}ze.resolveUrl=Tk;var Rk=/^[a-z_][-a-z0-9._]*$/i;function Pk(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=yr(e[r]||t),i={"":o},s=Em(n,o,!1),a={},c=new Set;return xk(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])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let R=this.opts.uriResolver.resolve;if(x=yr(_?R(_,x):x),c.has(x))throw u(x);c.add(x);let O=this.refs[x];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,x):x!==yr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!Rk.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!bk(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ze.getSchemaRefs=Pk});var $n=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Im=am(),Rm=wn(),Wa=Ma(),Vo=wn(),zk=mm(),xn=wm(),Ha=bm(),S=C(),A=pt(),Ok=vn(),mt=q(),bn=_n();function Ik(e){if(Cm(e)&&(Dm(e),Nm(e))){Ck(e);return}Am(e,()=>(0,Im.topBoolOrEmptySchema)(e))}Tt.validateFunctionCode=Ik;function Am({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Pm(r,o)}`),Nk(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${Ak(o)}`,n.$async,()=>e.code(Pm(r,o)).code(i))}function Ak(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function Nk(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function Ck(e){let{schema:t,opts:r,gen:n}=e;Am(e,()=>{r.$comment&&t.$comment&&Mm(e),qk(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&Dk(e),jm(e),Uk(e)})}function Dk(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Pm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function jk(e,t){if(Cm(e)&&(Dm(e),Nm(e))){Mk(e,t);return}(0,Im.boolOrEmptySchema)(e,t)}function Nm({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 Cm(e){return typeof e.schema!="boolean"}function Mk(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Mm(e),Bk(e),Zk(e);let i=n.const("_errs",A.default.errors);jm(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function Dm(e){(0,mt.checkUnknownRules)(e),Lk(e)}function jm(e,t){if(e.opts.jtd)return zm(e,[],!1,t);let r=(0,Rm.getSchemaTypes)(e.schema),n=(0,Rm.coerceAndCheckDataType)(e,r);zm(e,r,!n,t)}function Lk(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,mt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function qk(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,mt.checkStrictMode)(e,"default is ignored in the schema root")}function Bk(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Ok.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Zk(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Mm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Uk(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&Fk(e),t.return((0,S._)`${A.default.errors} === 0`))}function Fk({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function zm(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,mt.schemaHasRulesButRef)(i,u))){o.block(()=>qm(e,"$ref",u.all.$ref.definition));return}c.jtd||Vk(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Wa.shouldUseGroup)(i,f)&&(f.type?(o.if((0,Vo.checkDataType)(f.type,s,c.strictNumbers)),Om(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,Vo.reportTypeError)(e)),o.endIf()):Om(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Om(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,zk.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Wa.shouldUseRule)(n,i)&&qm(e,i.keyword,i.definition,t.type)})}function Vk(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Kk(e,t),e.opts.allowUnionTypes||Hk(e,t),Wk(e,e.dataTypes))}function Kk(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Lm(e.dataTypes,r)||Ga(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),Jk(e,t)}}function Hk(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ga(e,"use allowUnionTypes to allow union type keyword")}function Wk(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Wa.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Gk(t,s))&&Ga(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Gk(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Lm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Jk(e,t){let r=[];for(let n of e.dataTypes)Lm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ga(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,mt.checkStrictMode)(e,t,e.opts.strictTypes)}var Ko=class{constructor(t,r,n){if((0,xn.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,mt.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",Bm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,xn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",A.default.errors))}result(t,r,n){this.failResult((0,S.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,S.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,S._)`${r} !== undefined && (${(0,S.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?bn.reportExtraError:bn.reportError)(this,this.def.error,r)}$dataError(){(0,bn.reportError)(this,this.def.$dataError||bn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,bn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,Vo.checkDataTypes)(c,r,i.opts.strictNumbers,Vo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,Ha.getSubschema)(this.it,t);(0,Ha.extendSubschemaData)(n,this.it,t),(0,Ha.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return jk(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=mt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=mt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};Tt.KeywordCxt=Ko;function qm(e,t,r,n){let o=new Ko(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,xn.funcKeywordCode)(o,r):"macro"in r?(0,xn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,xn.funcKeywordCode)(o,r)}var Yk=/^\/(?:[^~]|~0|~1)*$/,Qk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Bm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!Yk.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=Qk.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,mt.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Tt.getData=Bm});var Ho=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Ja=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ya.default=Ja});var kn=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Qa=vn(),Xa=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qa.resolveUrl)(t,r,n),this.missingSchema=(0,Qa.normalizeId)((0,Qa.getFullPath)(t,this.missingRef))}};ec.default=Xa});var Go=v(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.resolveSchema=qe.getCompilingSchema=qe.resolveRef=qe.compileSchema=qe.SchemaEnv=void 0;var Ke=C(),Xk=Ho(),Kt=pt(),He=vn(),Zm=q(),e0=$n(),_r=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,He.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};qe.SchemaEnv=_r;function rc(e){let t=Um.call(this,e);if(t)return t;let r=(0,He.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ke.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:Xk.default,code:(0,Ke._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[Ke.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ke.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ke.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ke._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,e0.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Kt.default.self}`,`${Kt.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 Ke.Name?void 0:m,items:h instanceof Ke.Name?void 0:h,dynamicProps:m instanceof Ke.Name,dynamicItems:h instanceof Ke.Name},p.source&&(p.source.evaluated=(0,Ke.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)}}qe.compileSchema=rc;function t0(e,t,r){var n;r=(0,He.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=o0.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 _r({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=r0.call(this,i)}qe.resolveRef=t0;function r0(e){return(0,He.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:rc.call(this,e)}function Um(e){for(let t of this._compilations)if(n0(t,e))return t}qe.getCompilingSchema=Um;function n0(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function o0(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Wo.call(this,e,t)}function Wo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,He._getFullPath)(this.opts.uriResolver,r),o=(0,He.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return tc.call(this,r,e);let i=(0,He.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Wo.call(this,e,s);return typeof a?.schema!="object"?void 0:tc.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||rc.call(this,s),i===(0,He.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,He.resolveUrl)(this.opts.uriResolver,o,l)),new _r({schema:a,schemaId:c,root:e,baseId:o})}return tc.call(this,r,s)}}qe.resolveSchema=Wo;var i0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tc(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,Zm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!i0.has(a)&&l&&(t=(0,He.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Zm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,He.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Wo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new _r({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var Fm=v((OM,s0)=>{s0.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 ic=v((IM,Jm)=>{"use strict";var a0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Km=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),nc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),c0=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function oc(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 u0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Vm(e){return e.length=0,!0}function l0(e,t,r){if(e.length){let n=oc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function d0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=l0;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=Vm}else{o.push(l);continue}}return o.length&&(a===Vm?r.zone=o.join(""):s?n.push(o.join("")):n.push(oc(o))),r.address=n.join(""),r}function Wm(e){if(f0(e,":")<2)return{host:e,isIPV6:!1};let t=d0(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 f0(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function p0(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 m0={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},h0=/[@/?#:]/g,g0=/[@/?#]/g;function Gm(e,t){let r=t?g0:h0;return r.lastIndex=0,e.replace(r,n=>m0[n])}function y0(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(nc(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Hm(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function _0(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(nc(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Hm(i)?t+=i:t+="%"+o,r+=2;continue}}c0(e[r])?t+=e[r]:t+=escape(e[r])}return t}function w0(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(nc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function v0(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Km(r)){let n=Wm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Gm(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}Jm.exports={nonSimpleDomain:u0,recomposeAuthority:v0,reescapeHostDelimiters:Gm,normalizePercentEncoding:y0,normalizePathEncoding:_0,escapePreservingEscapes:w0,removeDotSegments:p0,isIPv4:Km,isUUID:a0,normalizeIPv6:Wm,stringArrayToHexStripped:oc}});var th=v((AM,eh)=>{"use strict";var{isUUID:b0}=ic(),x0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,$0=["http","https","ws","wss","urn","urn:uuid"];function k0(e){return $0.indexOf(e)!==-1}function sc(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 Ym(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Qm(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 S0(e){return e.secure=sc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function E0(e){if((e.port===(sc(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 T0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(x0);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=ac(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function R0(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=ac(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 P0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!b0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function z0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Xm={scheme:"http",domainHost:!0,parse:Ym,serialize:Qm},O0={scheme:"https",domainHost:Xm.domainHost,parse:Ym,serialize:Qm},Jo={scheme:"ws",domainHost:!0,parse:S0,serialize:E0},I0={scheme:"wss",domainHost:Jo.domainHost,parse:Jo.parse,serialize:Jo.serialize},A0={scheme:"urn",parse:T0,serialize:R0,skipNormalize:!0},N0={scheme:"urn:uuid",parse:P0,serialize:z0,skipNormalize:!0},Yo={http:Xm,https:O0,ws:Jo,wss:I0,urn:A0,"urn:uuid":N0};Object.setPrototypeOf(Yo,null);function ac(e){return e&&(Yo[e]||Yo[e.toLowerCase()])||void 0}eh.exports={wsIsSecure:sc,SCHEMES:Yo,isValidSchemeName:k0,getSchemeHandler:ac}});var ah=v((NM,Qo)=>{"use strict";var{normalizeIPv6:C0,removeDotSegments:Sn,recomposeAuthority:D0,normalizePercentEncoding:j0,normalizePathEncoding:M0,escapePreservingEscapes:L0,reescapeHostDelimiters:q0,isIPv4:B0,nonSimpleDomain:Z0}=ic(),{SCHEMES:U0,getSchemeHandler:nh}=th();function F0(e,t){return typeof e=="string"?e=G0(e,t):typeof e=="object"&&(e=wr(Ht(e,t),t)),e}function V0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=oh(wr(e,n),wr(t,n),n,!0);return n.skipEscape=!0,Ht(o,n)}function oh(e,t,r,n){let o={};return n||(e=wr(Ht(e,r),r),t=wr(Ht(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=Sn(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=Sn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Sn(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=Sn(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 K0(e,t,r){let n=rh(e,r),o=rh(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ht(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=nh(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=j0(r.path):(r.path=L0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=D0(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=Sn(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 H0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function W0(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 ih(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(H0);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=W0(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(B0(n.host)===!1){let u=C0(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=nh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&Z0(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=q0(unescape(n.host),i))),n.path&&(n.path=M0(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 wr(e,t){return ih(e,t).parsed}function G0(e,t){return sh(e,t).normalized}function sh(e,t){let{parsed:r,malformedAuthorityOrPort:n}=ih(e,t);return{normalized:n?e:Ht(r,t),malformedAuthorityOrPort:n}}function rh(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=sh(e,t);return n?void 0:r}if(typeof e=="object")return Ht(e,t)}var cc={SCHEMES:U0,normalize:F0,resolve:V0,resolveComponent:oh,equal:K0,serialize:Ht,parse:wr};Qo.exports=cc;Qo.exports.default=cc;Qo.exports.fastUri=cc});var uh=v(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var ch=ah();ch.code='require("ajv/dist/runtime/uri").default';uc.default=ch});var yh=v(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.CodeGen=pe.Name=pe.nil=pe.stringify=pe.str=pe._=pe.KeywordCxt=void 0;var J0=$n();Object.defineProperty(pe,"KeywordCxt",{enumerable:!0,get:function(){return J0.KeywordCxt}});var vr=C();Object.defineProperty(pe,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(pe,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(pe,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(pe,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(pe,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(pe,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var Y0=Ho(),mh=kn(),Q0=ja(),En=Go(),X0=C(),Tn=vn(),Xo=wn(),dc=q(),lh=Fm(),eS=uh(),hh=(e,t)=>new RegExp(e,t);hh.code="new RegExp";var tS=["removeAdditional","useDefaults","coerceTypes"],rS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),nS={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."},oS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},dh=200;function iS(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,b,x,R,O,xe,Ne,nr,Wi;let qr=e.strict,Gi=(t=e.code)===null||t===void 0?void 0:t.optimize,gl=Gi===!0||Gi===void 0?1:Gi||0,yl=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:hh,qw=(o=e.uriResolver)!==null&&o!==void 0?o:eS.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:qr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:qr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:qr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:qr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:qr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:gl,regExp:yl}:{optimize:gl,regExp:yl},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:dh,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:dh,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(xe=e.validateSchema)!==null&&xe!==void 0?xe:!0,validateFormats:(Ne=e.validateFormats)!==null&&Ne!==void 0?Ne:!0,unicodeRegExp:(nr=e.unicodeRegExp)!==null&&nr!==void 0?nr:!0,int32range:(Wi=e.int32range)!==null&&Wi!==void 0?Wi:!0,uriResolver:qw}}var Rn=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,...iS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new X0.ValueScope({scope:{},prefixes:rS,es5:r,lines:n}),this.logger=dS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Q0.getRules)(),fh.call(this,nS,t,"NOT SUPPORTED"),fh.call(this,oS,t,"DEPRECATED","warn"),this._metaOpts=uS.call(this),t.formats&&aS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&cS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),sS.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=lh;n==="id"&&(o={...lh},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 mh.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,Tn.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=ph.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new En.SchemaEnv({schema:{},schemaId:n});if(r=En.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=ph.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,Tn.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(pS.call(this,n,r),!r)return(0,dc.eachItem)(n,i=>lc.call(this,i)),this;hS.call(this,r);let o={...r,type:(0,Xo.getJSONTypes)(r.type),schemaType:(0,Xo.getJSONTypes)(r.schemaType)};return(0,dc.eachItem)(n,o.type.length===0?i=>lc.call(this,i,o):i=>o.type.forEach(s=>lc.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]=gh(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,Tn.normalizeId)(s||n);let l=Tn.getSchemaRefs.call(this,t,n);return c=new En.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):En.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{En.compileSchema.call(this,t)}finally{this.opts=r}}};Rn.ValidationError=Y0.default;Rn.MissingRefError=mh.default;pe.default=Rn;function fh(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 ph(e){return e=(0,Tn.normalizeId)(e),this.schemas[e]||this.refs[e]}function sS(){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 aS(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function cS(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 uS(){let e={...this.opts};for(let t of tS)delete e[t];return e}var lS={log(){},warn(){},error(){}};function dS(e){if(e===!1)return lS;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 fS=/^[a-z_$][a-z0-9_$:-]*$/i;function pS(e,t){let{RULES:r}=this;if((0,dc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!fS.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 lc(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,Xo.getJSONTypes)(t.type),schemaType:(0,Xo.getJSONTypes)(t.schemaType)}};t.before?mS.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 mS(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 hS(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=gh(t)),e.validateSchema=this.compile(t,!0))}var gS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function gh(e){return{anyOf:[e,gS]}}});var _h=v(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var yS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};fc.default=yS});var xh=v(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.callRef=Wt.getValidate=void 0;var _S=kn(),wh=Le(),Oe=C(),br=pt(),vh=Go(),ei=q(),wS={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=vh.resolveRef.call(c,l,o,r);if(u===void 0)throw new _S.default(n.opts.uriResolver,o,r);if(u instanceof vh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return ti(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return ti(e,(0,Oe._)`${m}.validate`,l,l.$async)}function f(m){let h=bh(e,m);ti(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Oe.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Oe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function bh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Oe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Wt.getValidate=bh;function ti(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?br.default.this:Oe.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,Oe._)`await ${(0,wh.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Oe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,wh.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Oe._)`${m}.errors`;o.assign(br.default.vErrors,(0,Oe._)`${br.default.vErrors} === null ? ${h} : ${br.default.vErrors}.concat(${h})`),o.assign(br.default.errors,(0,Oe._)`${br.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=ei.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Oe._)`${m}.evaluated.props`);i.props=ei.mergeEvaluated.props(o,w,i.props,Oe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=ei.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Oe._)`${m}.evaluated.items`);i.items=ei.mergeEvaluated.items(o,w,i.items,Oe.Name)}}}Wt.callRef=ti;Wt.default=wS});var $h=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var vS=_h(),bS=xh(),xS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vS.default,bS.default];pc.default=xS});var kh=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ri=C(),Rt=ri.operators,ni={maximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},minimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},exclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},exclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},$S={message:({keyword:e,schemaCode:t})=>(0,ri.str)`must be ${ni[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ri._)`{comparison: ${ni[e].okStr}, limit: ${t}}`},kS={keyword:Object.keys(ni),type:"number",schemaType:"number",$data:!0,error:$S,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ri._)`${r} ${ni[t].fail} ${n} || isNaN(${r})`)}};mc.default=kS});var Sh=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Pn=C(),SS={message:({schemaCode:e})=>(0,Pn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Pn._)`{multipleOf: ${e}}`},ES={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Pn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Pn._)`${s} !== parseInt(${s})`;e.fail$data((0,Pn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};hc.default=ES});var Th=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});function Eh(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}gc.default=Eh;Eh.code='require("ajv/dist/runtime/ucs2length").default'});var Rh=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Gt=C(),TS=q(),RS=Th(),PS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Gt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Gt._)`{limit: ${e}}`},zS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:PS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Gt.operators.GT:Gt.operators.LT,s=o.opts.unicode===!1?(0,Gt._)`${r}.length`:(0,Gt._)`${(0,TS.useFunc)(e.gen,RS.default)}(${r})`;e.fail$data((0,Gt._)`${s} ${i} ${n}`)}};yc.default=zS});var Ph=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var OS=Le(),IS=q(),xr=C(),AS={message:({schemaCode:e})=>(0,xr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,xr._)`{pattern: ${e}}`},NS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:AS,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,xr._)`new RegExp`:(0,IS.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,xr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,xr._)`!${u}`)}else{let c=(0,OS.usePattern)(e,o);e.fail$data((0,xr._)`!${c}.test(${r})`)}}};_c.default=NS});var zh=v(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var zn=C(),CS={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,zn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,zn._)`{limit: ${e}}`},DS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?zn.operators.GT:zn.operators.LT;e.fail$data((0,zn._)`Object.keys(${r}).length ${o} ${n}`)}};wc.default=DS});var Oh=v(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var On=Le(),In=C(),jS=q(),MS={message:({params:{missingProperty:e}})=>(0,In.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,In._)`{missingProperty: ${e}}`},LS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:MS,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,jS.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(In.nil,d);else for(let p of r)(0,On.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,On.checkMissingProp)(e,r,p)),(0,On.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,On.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,On.propertyInData)(t,o,p,a.ownProperties)),t.if((0,In.not)(m),()=>{e.error(),t.break()})},In.nil)}}};vc.default=LS});var Ih=v(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var An=C(),qS={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,An.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,An._)`{limit: ${e}}`},BS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:qS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?An.operators.GT:An.operators.LT;e.fail$data((0,An._)`${r}.length ${o} ${n}`)}};bc.default=BS});var oi=v(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Ah=Va();Ah.code='require("ajv/dist/runtime/equal").default';xc.default=Ah});var Nh=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var $c=wn(),me=C(),ZS=q(),US=oi(),FS={message:({params:{i:e,j:t}})=>(0,me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,me._)`{i: ${e}, j: ${t}}`},VS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FS,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,$c.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,me._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,me._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,me._)`${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,$c.checkDataTypes)(l,_,a.opts.strictNumbers,$c.DataType.Wrong),b=t.const("indices",(0,me._)`{}`);t.for((0,me._)`;${m}--;`,()=>{t.let(_,(0,me._)`${r}[${m}]`),t.if(w,(0,me._)`continue`),l.length>1&&t.if((0,me._)`typeof ${_} == "string"`,(0,me._)`${_} += "_"`),t.if((0,me._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(h,(0,me._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,me._)`${b}[${_}] = ${m}`)})}function p(m,h){let _=(0,ZS.useFunc)(t,US.default),w=t.name("outer");t.label(w).for((0,me._)`;${m}--;`,()=>t.for((0,me._)`${h} = ${m}; ${h}--;`,()=>t.if((0,me._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};kc.default=VS});var Ch=v(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Sc=C(),KS=q(),HS=oi(),WS={message:"must be equal to constant",params:({schemaCode:e})=>(0,Sc._)`{allowedValue: ${e}}`},GS={keyword:"const",$data:!0,error:WS,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Sc._)`!${(0,KS.useFunc)(t,HS.default)}(${r}, ${o})`):e.fail((0,Sc._)`${i} !== ${r}`)}};Ec.default=GS});var Dh=v(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Nn=C(),JS=q(),YS=oi(),QS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Nn._)`{allowedValues: ${e}}`},XS={keyword:"enum",schemaType:"array",$data:!0,error:QS,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,JS.useFunc)(t,YS.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,Nn.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,Nn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Nn._)`${l()}(${r}, ${p}[${m}])`:(0,Nn._)`${r} === ${h}`}}};Tc.default=XS});var jh=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var eE=kh(),tE=Sh(),rE=Rh(),nE=Ph(),oE=zh(),iE=Oh(),sE=Ih(),aE=Nh(),cE=Ch(),uE=Dh(),lE=[eE.default,tE.default,rE.default,nE.default,oE.default,iE.default,sE.default,aE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cE.default,uE.default];Rc.default=lE});var zc=v(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.validateAdditionalItems=void 0;var Jt=C(),Pc=q(),dE={message:({params:{len:e}})=>(0,Jt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Jt._)`{limit: ${e}}`},fE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dE,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Pc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Mh(e,n)}};function Mh(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Jt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Jt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Jt._)`${a} <= ${t.length}`);r.if((0,Jt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Pc.Type.Num},l),s.allErrors||r.if((0,Jt.not)(l),()=>r.break())})}}Cn.validateAdditionalItems=Mh;Cn.default=fE});var Oc=v(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.validateTuple=void 0;var Lh=C(),ii=q(),pE=Le(),mE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return qh(e,"additionalItems",t);r.items=!0,!(0,ii.alwaysValidSchema)(r,t)&&e.ok((0,pE.validateArray)(e))}};function qh(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=ii.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Lh._)`${i}.length`);r.forEach((d,f)=>{(0,ii.alwaysValidSchema)(a,d)||(n.if((0,Lh._)`${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,ii.checkStrictMode)(a,_,f.strictTuples)}}}Dn.validateTuple=qh;Dn.default=mE});var Bh=v(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var hE=Oc(),gE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,hE.validateTuple)(e,"items")};Ic.default=gE});var Uh=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Zh=C(),yE=q(),_E=Le(),wE=zc(),vE={message:({params:{len:e}})=>(0,Zh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zh._)`{limit: ${e}}`},bE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:vE,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,yE.alwaysValidSchema)(n,t)&&(o?(0,wE.validateAdditionalItems)(e,o):e.ok((0,_E.validateArray)(e)))}};Ac.default=bE});var Fh=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Be=C(),si=q(),xE={message:({params:{min:e,max:t}})=>t===void 0?(0,Be.str)`must contain at least ${e} valid item(s)`:(0,Be.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Be._)`{minContains: ${e}}`:(0,Be._)`{minContains: ${e}, maxContains: ${t}}`},$E={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:xE,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,Be._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,si.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,si.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,si.alwaysValidSchema)(i,r)){let h=(0,Be._)`${u} >= ${s}`;a!==void 0&&(h=(0,Be._)`${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,Be._)`${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:si.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Be._)`${h}++`),a===void 0?t.if((0,Be._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Be._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Be._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};Nc.default=$E});var Hh=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.validateSchemaDeps=ot.validatePropertyDeps=ot.error=void 0;var Cc=C(),kE=q(),jn=Le();ot.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Cc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Cc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var pE={keyword:"dependencies",type:"object",schemaType:"object",error:rt.error,code(e){let[t,r]=mE(e);Fh(e,t),Vh(e,r)}};function mE({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 Fh(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,jn.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,jn.checkReportMissingProp)(e,l)}):(r.if((0,Cc._)`${c} && (${(0,jn.checkMissingProp)(e,a,i)})`),(0,jn.reportMissingProp)(e,i),r.else())}}rt.validatePropertyDeps=Fh;function Vh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,fE.alwaysValidSchema)(i,t[a])||(r.if((0,jn.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))}rt.validateSchemaDeps=Vh;rt.default=pE});var Wh=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Hh=C(),hE=q(),gE={message:"property name must be valid",params:({params:e})=>(0,Hh._)`{propertyName: ${e.propertyName}}`},yE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:gE,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,hE.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,Hh.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Dc.default=yE});var Mc=v(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var ai=Le(),We=C(),_E=dt(),ci=q(),wE={message:"must NOT have additional properties",params:({params:e})=>(0,We._)`{additionalProperty: ${e.additionalProperty}}`},vE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:wE,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,ci.alwaysValidSchema)(s,r))return;let l=(0,ai.allSchemaProperties)(n.properties),u=(0,ai.allSchemaProperties)(n.patternProperties);d(),e.ok((0,We._)`${i} === ${_E.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 b=(0,ci.schemaRefOrVal)(s,n.properties,"properties");w=(0,ai.isOwnProperty)(t,b,_)}else l.length?w=(0,We.or)(...l.map(b=>(0,We._)`${_} === ${b}`)):w=We.nil;return u.length&&(w=(0,We.or)(w,...u.map(b=>(0,We._)`${(0,ai.usePattern)(e,b)}.test(${_})`))),(0,We.not)(w)}function p(_){t.code((0,We._)`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,ci.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,We.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,We.not)(w),()=>t.break()))}}function h(_,w,b){let x={keyword:"additionalProperties",dataProp:_,dataPropType:ci.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};jc.default=vE});var Yh=v(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bE=$n(),Gh=Le(),Lc=q(),Jh=Mc(),xE={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&&Jh.default.code(new bE.KeywordCxt(i,Jh.default,"additionalProperties"));let s=(0,Gh.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Lc.mergeEvaluated.props(t,(0,Lc.toHash)(s),i.props));let a=s.filter(d=>!(0,Lc.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,Gh.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)}}};qc.default=xE});var tg=v(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Qh=Le(),ui=C(),Xh=q(),eg=q(),$E={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,Qh.allSchemaProperties)(r),c=a.filter(h=>(0,Xh.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 ui.Name)&&(i.props=(0,eg.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,Xh.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,ui._)`${(0,Qh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:eg.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,ui._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,ui.not)(u),()=>t.break())})})}}};Bc.default=$E});var rg=v(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var kE=q(),SE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,kE.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"}};Zc.default=SE});var ng=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var EE=Le(),TE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:EE.validateUnion,error:{message:"must match a schema in anyOf"}};Uc.default=TE});var og=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var li=C(),RE=q(),PE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,li._)`{passingSchemas: ${e.passing}}`},zE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:PE,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,RE.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,li._)`${c} && ${s}`).assign(s,!1).assign(a,(0,li._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,li.Name)})})}}};Fc.default=zE});var ig=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var OE=q(),IE={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,OE.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Vc.default=IE});var cg=v(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var di=C(),ag=q(),AE={message:({params:e})=>(0,di.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,di._)`{failingKeyword: ${e.ifClause}}`},NE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:AE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,ag.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=sg(n,"then"),i=sg(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,di.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,di._)`${u}`):e.setParams({ifClause:u})}}}};function sg(e,t){let r=e.schema[t];return r!==void 0&&!(0,ag.alwaysValidSchema)(e,r)}Kc.default=NE});var ug=v(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var CE=q(),DE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,CE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hc.default=DE});var lg=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var jE=zc(),ME=qh(),LE=Oc(),qE=Zh(),BE=Uh(),ZE=Kh(),UE=Wh(),FE=Mc(),VE=Yh(),KE=tg(),HE=rg(),WE=ng(),GE=og(),JE=ig(),YE=cg(),QE=ug();function XE(e=!1){let t=[HE.default,WE.default,GE.default,JE.default,YE.default,QE.default,UE.default,FE.default,ZE.default,VE.default,KE.default];return e?t.push(ME.default,qE.default):t.push(jE.default,LE.default),t.push(BE.default),t}Wc.default=XE});var dg=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var se=C(),eT={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},tT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eT,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)(b(),x()));function b(){return c.strictSchema===!1?se.nil:(0,se._)`${s} && !${w}`}function x(){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){b();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(R());function b(){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 x(O){let xe=O instanceof RegExp?(0,se.regexpCode)(O):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(i)}`:void 0,Ne=r.scopeValue("formats",{key:i,ref:O,code:xe});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,se._)`${Ne}.validate`]:["string",O,Ne]}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})`}}}};Gc.default=tT});var fg=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var rT=dg(),nT=[rT.default];Jc.default=nT});var pg=v($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hg=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var oT=xh(),iT=Dh(),sT=lg(),aT=fg(),mg=pg(),cT=[oT.default,iT.default,(0,sT.default)(),aT.default,mg.metadataVocabulary,mg.contentVocabulary];Yc.default=cT});var yg=v(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.DiscrError=void 0;var gg;(function(e){e.Tag="tag",e.Mapping="mapping"})(gg||(fi.DiscrError=gg={}))});var wg=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var kr=C(),Qc=yg(),_g=Go(),uT=kn(),lT=q(),dT={message:({params:{discrError:e,tagName:t}})=>e===Qc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,kr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},fT={keyword:"discriminator",type:"object",schemaType:"object",error:dT,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,kr._)`${r}${(0,kr.getProperty)(a)}`);t.if((0,kr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Qc.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,kr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Qc.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,kr.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,lT.schemaHasRulesButRef)(O,i.self.RULES)){let Ne=O.$ref;if(O=_g.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ne),O instanceof _g.SchemaEnv&&(O=O.schema),O===void 0)throw new uT.default(i.opts.uriResolver,i.baseId,Ne)}let xe=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof xe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),b(xe,R)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(a)}function b(R,O){if(R.const)x(R.const,O);else if(R.enum)for(let xe of R.enum)x(xe,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(R,O){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[R]=O}}}};Xc.default=fT});var vg=v((cL,pT)=>{pT.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 tu=v((te,eu)=>{"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 mT=gh(),hT=hg(),gT=wg(),bg=vg(),yT=["/properties"],pi="http://json-schema.org/draft-07/schema",Sr=class extends mT.default{_addVocabularies(){super._addVocabularies(),hT.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(gT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(bg,yT):bg;this.addMetaSchema(t,pi,!1),this.refs["http://json-schema.org/schema"]=pi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pi)?pi:void 0)}};te.Ajv=Sr;eu.exports=te=Sr;eu.exports.Ajv=Sr;Object.defineProperty(te,"__esModule",{value:!0});te.default=Sr;var _T=$n();Object.defineProperty(te,"KeywordCxt",{enumerable:!0,get:function(){return _T.KeywordCxt}});var Er=C();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Er.Name}});Object.defineProperty(te,"CodeGen",{enumerable:!0,get:function(){return Er.CodeGen}});var wT=Ho();Object.defineProperty(te,"ValidationError",{enumerable:!0,get:function(){return wT.default}});var vT=kn();Object.defineProperty(te,"MissingRefError",{enumerable:!0,get:function(){return vT.default}})});var Pg=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.formatNames=ot.fastFormats=ot.fullFormats=void 0;function nt(e,t){return{validate:e,compare:t}}ot.fullFormats={date:nt(Sg,iu),time:nt(nu(!0),su),"date-time":nt(xg(!0),Tg),"iso-time":nt(nu(),Eg),"iso-date-time":nt(xg(),Rg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ET,"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:AT,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:TT,int32:{type:"number",validate:zT},int64:{type:"number",validate:OT},float:{type:"number",validate:kg},double:{type:"number",validate:kg},password:!0,binary:!0};ot.fastFormats={...ot.fullFormats,date:nt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,iu),time:nt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,su),"date-time":nt(/^\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,Tg),"iso-time":nt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Eg),"iso-date-time":nt(/^\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,Rg),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};ot.formatNames=Object.keys(ot.fullFormats);function bT(e){return e%4===0&&(e%100!==0||e%400===0)}var xT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$T=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Sg(e){let t=xT.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&&bT(r)?29:$T[n])}function iu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var ru=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function nu(e){return function(r){let n=ru.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 su(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 Eg(e,t){if(!(e&&t))return;let r=ru.exec(e),n=ru.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 ou=/t|\s/i;function xg(e){let t=nu(e);return function(n){let o=n.split(ou);return o.length===2&&Sg(o[0])&&t(o[1])}}function Tg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Rg(e,t){if(!(e&&t))return;let[r,n]=e.split(ou),[o,i]=t.split(ou),s=iu(r,o);if(s!==void 0)return s||su(n,i)}var kT=/\/|:/,ST=/^(?:[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 ET(e){return kT.test(e)&&ST.test(e)}var $g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function TT(e){return $g.lastIndex=0,$g.test(e)}var RT=-(2**31),PT=2**31-1;function zT(e){return Number.isInteger(e)&&e<=PT&&e>=RT}function OT(e){return Number.isInteger(e)}function kg(){return!0}var IT=/[^\\]\\Z/;function AT(e){if(IT.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var zg=v(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.formatLimitDefinition=void 0;var NT=tu(),Ge=C(),Pt=Ge.operators,mi={formatMaximum:{okStr:"<=",ok:Pt.LTE,fail:Pt.GT},formatMinimum:{okStr:">=",ok:Pt.GTE,fail:Pt.LT},formatExclusiveMaximum:{okStr:"<",ok:Pt.LT,fail:Pt.GTE},formatExclusiveMinimum:{okStr:">",ok:Pt.GT,fail:Pt.LTE}},CT={message:({keyword:e,schemaCode:t})=>(0,Ge.str)`should be ${mi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ge._)`{comparison: ${mi[e].okStr}, limit: ${t}}`};Tr.formatLimitDefinition={keyword:Object.keys(mi),type:"string",schemaType:"string",$data:!0,error:CT,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 NT.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,Ge._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ge.or)((0,Ge._)`typeof ${p} != "object"`,(0,Ge._)`${p} instanceof RegExp`,(0,Ge._)`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,Ge._)`${s.code.formats}${(0,Ge.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ge._)`${f}.compare(${r}, ${n}) ${mi[o].fail} 0`}},dependencies:["format"]};var DT=e=>(e.addKeyword(Tr.formatLimitDefinition),e);Tr.default=DT});var Ng=v((Mn,Ag)=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});var Rr=Pg(),jT=zg(),au=C(),Og=new au.Name("fullFormats"),MT=new au.Name("fastFormats"),cu=(e,t={keywords:!0})=>{if(Array.isArray(t))return Ig(e,t,Rr.fullFormats,Og),e;let[r,n]=t.mode==="fast"?[Rr.fastFormats,MT]:[Rr.fullFormats,Og],o=t.formats||Rr.formatNames;return Ig(e,o,r,n),t.keywords&&(0,jT.default)(e),e};cu.get=(e,t="full")=>{let n=(t==="fast"?Rr.fastFormats:Rr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Ig(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,au._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Ag.exports=Mn=cu;Object.defineProperty(Mn,"__esModule",{value:!0});Mn.default=cu});var Ug=v((xL,Zg)=>{Zg.exports=Bg;Bg.sync=ZT;var Lg=yt("fs");function BT(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 qg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:BT(t,r)}function Bg(e,t,r){Lg.stat(e,function(n,o){r(n,n?!1:qg(o,e,t))})}function ZT(e,t){return qg(Lg.statSync(e),e,t)}});var Wg=v(($L,Hg)=>{Hg.exports=Vg;Vg.sync=UT;var Fg=yt("fs");function Vg(e,t,r){Fg.stat(e,function(n,o){r(n,n?!1:Kg(o,t))})}function UT(e,t){return Kg(Fg.statSync(e),t)}function Kg(e,t){return e.isFile()&&FT(e,t)}function FT(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 Jg=v((SL,Gg)=>{var kL=yt("fs"),wi;process.platform==="win32"||global.TESTING_WINDOWS?wi=Ug():wi=Wg();Gg.exports=uu;uu.sync=VT;function uu(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){uu(e,t||{},function(i,s){i?o(i):n(s)})})}wi(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function VT(e,t){try{return wi.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var ny=v((EL,ry)=>{var Pr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Yg=yt("path"),KT=Pr?";":":",Qg=Jg(),Xg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),ey=(e,t)=>{let r=t.colon||KT,n=e.match(/\//)||Pr&&e.match(/\\/)?[""]:[...Pr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Pr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Pr?o.split(r):[""];return Pr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},ty=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=ey(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(Xg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=Yg.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];Qg(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)},HT=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=ey(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Yg.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(Qg.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 Xg(e)};ry.exports=ty;ty.sync=HT});var iy=v((TL,lu)=>{"use strict";var oy=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};lu.exports=oy;lu.exports.default=oy});var uy=v((RL,cy)=>{"use strict";var sy=yt("path"),WT=ny(),GT=iy();function ay(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=WT.sync(e.command,{path:r[GT({env:r})],pathExt:t?sy.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=sy.resolve(o?e.options.cwd:"",s)),s}function JT(e){return ay(e)||ay(e,!0)}cy.exports=JT});var ly=v((PL,fu)=>{"use strict";var du=/([()\][%!^"`<>&|;, *?])/g;function YT(e){return e=e.replace(du,"^$1"),e}function QT(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(du,"^$1"),t&&(e=e.replace(du,"^$1")),e}fu.exports.command=YT;fu.exports.argument=QT});var fy=v((zL,dy)=>{"use strict";dy.exports=/^#!(.*)/});var my=v((OL,py)=>{"use strict";var XT=fy();py.exports=(e="")=>{let t=e.match(XT);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var gy=v((IL,hy)=>{"use strict";var pu=yt("fs"),eR=my();function tR(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 eR(r.toString())}hy.exports=tR});var vy=v((AL,wy)=>{"use strict";var rR=yt("path"),yy=uy(),_y=ly(),nR=gy(),oR=process.platform==="win32",iR=/\.(?:com|exe)$/i,sR=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function aR(e){e.file=yy(e);let t=e.file&&nR(e.file);return t?(e.args.unshift(e.file),e.command=t,yy(e)):e.file}function cR(e){if(!oR)return e;let t=aR(e),r=!iR.test(t);if(e.options.forceShell||r){let n=sR.test(t);e.command=rR.normalize(e.command),e.command=_y.command(e.command),e.args=e.args.map(i=>_y.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 uR(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:cR(n)}wy.exports=uR});var $y=v((NL,xy)=>{"use strict";var mu=process.platform==="win32";function hu(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 lR(e,t){if(!mu)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=by(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function by(e,t){return mu&&e===1&&!t.file?hu(t.original,"spawn"):null}function dR(e,t){return mu&&e===1&&!t.file?hu(t.original,"spawnSync"):null}xy.exports={hookChildProcess:lR,verifyENOENT:by,verifyENOENTSync:dR,notFoundError:hu}});var Ey=v((CL,zr)=>{"use strict";var ky=yt("child_process"),gu=vy(),yu=$y();function Sy(e,t,r){let n=gu(e,t,r),o=ky.spawn(n.command,n.args,n.options);return yu.hookChildProcess(o,n),o}function fR(e,t,r){let n=gu(e,t,r),o=ky.spawnSync(n.command,n.args,n.options);return o.error=o.error||yu.verifyENOENTSync(o.status,n),o}zr.exports=Sy;zr.exports.spawn=Sy;zr.exports.sync=fR;zr.exports._parse=gu;zr.exports._enoent=yu});import{readFile as XI,mkdir as eA,writeFile as tA}from"node:fs/promises";import{dirname as rA,join as Tw}from"node:path";function _l(e){let t={app:e,version:Cw(or("__RED_BUILD_VERSION__",()=>"3.0.3")??"0.0.0-dev"),gitSha:or("__RED_BUILD_GIT_SHA__",()=>"7994a78a62bd88712414f58cd428ca0d3eb6fcb3")??"unknown",buildTime:or("__RED_BUILD_TIME__",()=>"2026-07-30T22:45:13-03:00")??"unknown",bundleAsset:or("__RED_BUNDLE_ASSET__",()=>"brain.bundle.min.mjs")??"unknown"},r=or("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=or("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Cw(e){return e.startsWith("v")?e.slice(1):e}function wl(e){return`${e.app} ${e.version} ${e.gitSha}`}function or(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var bA=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 xA=Symbol("zod_brand"),at=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},oo={};function Ce(e){return e&&Object.assign(oo,e),oo}var U={};yl(U,{BIGINT_FORMAT_RANGES:()=>bl,Class:()=>Xi,NUMBER_FORMAT_RANGES:()=>as,aborted:()=>Dt,allowsEval:()=>os,assert:()=>qw,assertEqual:()=>Dw,assertIs:()=>Mw,assertNever:()=>Lw,assertNotEqual:()=>jw,assignProp:()=>ns,cached:()=>Zr,captureStackTrace:()=>so,cleanEnum:()=>Xw,cleanRegex:()=>Fr,clone:()=>Qe,createTransparentProxy:()=>Kw,defineLazy:()=>W,esc:()=>Ct,escapeRegex:()=>_t,extend:()=>Gw,finalizeIssue:()=>Ue,floatSafeRemainder:()=>rs,getElementAtPath:()=>Bw,getEnumValues:()=>es,getLengthableOrigin:()=>Vr,getParsedType:()=>Vw,getSizableOrigin:()=>xl,isObject:()=>ir,isPlainObject:()=>sr,issue:()=>cs,joinValues:()=>io,jsonStringifyReplacer:()=>ts,merge:()=>Jw,normalizeParams:()=>P,nullish:()=>Ur,numKeys:()=>Fw,omit:()=>Ww,optionalKeys:()=>ss,partial:()=>Yw,pick:()=>Hw,prefixIssues:()=>Xe,primitiveTypes:()=>vl,promiseAllObject:()=>Zw,propertyKeyTypes:()=>is,randomString:()=>Uw,required:()=>Qw,stringifyPrimitive:()=>ao,unwrapMessage:()=>Br});function Dw(e){return e}function jw(e){return e}function Mw(e){}function Lw(e){throw new Error}function qw(e){}function es(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 io(e,t="|"){return e.map(r=>ao(r)).join(t)}function ts(e,t){return typeof t=="bigint"?t.toString():t}function Zr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ur(e){return e==null}function Fr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rs(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 ns(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bw(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Zw(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 Uw(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Ct(e){return JSON.stringify(e)}var so=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var os=Zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function sr(e){if(ir(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(ir(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Fw(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Vw=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}`)}},is=new Set(["string","number","symbol"]),vl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qe(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 Kw(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 ao(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ss(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var as={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]},bl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Hw(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 Qe(e,{...e._zod.def,shape:r,checks:[]})}function Ww(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 Qe(e,{...e._zod.def,shape:r,checks:[]})}function Gw(e,t){if(!sr(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 ns(this,"shape",n),n},checks:[]};return Qe(e,r)}function Jw(e,t){return Qe(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ns(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Yw(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 Qe(t,{...t._zod.def,shape:o,checks:[]})}function Qw(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 Qe(t,{...t._zod.def,shape:o,checks:[]})}function Dt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Xe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Br(e){return typeof e=="string"?e:e?.message}function Ue(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Br(e.inst?._zod.def?.error?.(e))??Br(t?.error?.(e))??Br(r.customError?.(e))??Br(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function xl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Vr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cs(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Xw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Xi=class{constructor(...t){}};var $l=(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,ts,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},co=y("$ZodError",$l),us=y("$ZodError",$l,{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 Sl(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 El=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 at;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ue(c,i,Ce())));throw so(a,o?.callee),a}return s.value};var Tl=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=>Ue(c,i,Ce())));throw so(a,o?.callee),a}return s.value};var ls=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 at;return i.issues.length?{success:!1,error:new(e??co)(i.issues.map(s=>Ue(s,o,Ce())))}:{success:!0,data:i.value}},Kr=ls(us),ds=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=>Ue(s,o,Ce())))}:{success:!0,data:i.value}},uo=ds(us);var Rl=/^[cC][^\s-]{8,}$/,Pl=/^[0-9a-z]+$/,zl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ol=/^[0-9a-vA-V]{20}$/,Il=/^[A-Za-z0-9]{27}$/,Al=/^[a-zA-Z0-9_-]{21}$/,Nl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Cl=/^([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})$/,fs=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 Dl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var tv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jl(){return new RegExp(tv,"u")}var Ml=/^(?:(?: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])$/,Ll=/^(([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})$/,ql=/^((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])$/,Bl=/^(([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])$/,Zl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ps=/^[A-Za-z0-9_-]*$/,Ul=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Fl=/^\+(?:[0-9]){6,14}[0-9]$/,Vl="(?:(?:\\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])))",Kl=new RegExp(`^${Vl}$`);function Hl(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 Wl(e){return new RegExp(`^${Hl(e)}$`)}function Gl(e){let t=Hl({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(`^${Vl}T(?:${n})$`)}var Jl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Yl=/^\d+$/,Ql=/^-?\d+(?:\.\d+)?/i,Xl=/true|false/i,ed=/null/i;var td=/^[^A-Z]*$/,rd=/^[^a-z]*$/;var ge=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),nd={number:"number",bigint:"bigint",object:"date"},hs=y("$ZodCheckLessThan",(e,t)=>{ge.init(e,t);let r=nd[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})}}),gs=y("$ZodCheckGreaterThan",(e,t)=>{ge.init(e,t);let r=nd[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})}}),od=y("$ZodCheckMultipleOf",(e,t)=>{ge.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):rs(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})}}),id=y("$ZodCheckNumberFormat",(e,t)=>{ge.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=as[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=Yl)}),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 sd=y("$ZodCheckMaxLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ad=y("$ZodCheckMinLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cd=y("$ZodCheckLengthEquals",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(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})}}),Hr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;ge.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=()=>{})}),ud=y("$ZodCheckRegex",(e,t)=>{Hr.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})}}),ld=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=td),Hr.init(e,t)}),dd=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=rd),Hr.init(e,t)}),fd=y("$ZodCheckIncludes",(e,t)=>{ge.init(e,t);let r=_t(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})}}),pd=y("$ZodCheckStartsWith",(e,t)=>{ge.init(e,t);let r=new RegExp(`^${_t(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})}}),md=y("$ZodCheckEndsWith",(e,t)=>{ge.init(e,t);let r=new RegExp(`.*${_t(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 hd=y("$ZodCheckOverwrite",(e,t)=>{ge.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var lo=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 SE={keyword:"dependencies",type:"object",schemaType:"object",error:ot.error,code(e){let[t,r]=EE(e);Vh(e,t),Kh(e,r)}};function EE({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 Vh(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,jn.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,jn.checkReportMissingProp)(e,l)}):(r.if((0,Cc._)`${c} && (${(0,jn.checkMissingProp)(e,a,i)})`),(0,jn.reportMissingProp)(e,i),r.else())}}ot.validatePropertyDeps=Vh;function Kh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,kE.alwaysValidSchema)(i,t[a])||(r.if((0,jn.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))}ot.validateSchemaDeps=Kh;ot.default=SE});var Gh=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Wh=C(),TE=q(),RE={message:"property name must be valid",params:({params:e})=>(0,Wh._)`{propertyName: ${e.propertyName}}`},PE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RE,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,TE.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,Wh.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Dc.default=PE});var Mc=v(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var ai=Le(),We=C(),zE=pt(),ci=q(),OE={message:"must NOT have additional properties",params:({params:e})=>(0,We._)`{additionalProperty: ${e.additionalProperty}}`},IE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:OE,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,ci.alwaysValidSchema)(s,r))return;let l=(0,ai.allSchemaProperties)(n.properties),u=(0,ai.allSchemaProperties)(n.patternProperties);d(),e.ok((0,We._)`${i} === ${zE.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 b=(0,ci.schemaRefOrVal)(s,n.properties,"properties");w=(0,ai.isOwnProperty)(t,b,_)}else l.length?w=(0,We.or)(...l.map(b=>(0,We._)`${_} === ${b}`)):w=We.nil;return u.length&&(w=(0,We.or)(w,...u.map(b=>(0,We._)`${(0,ai.usePattern)(e,b)}.test(${_})`))),(0,We.not)(w)}function p(_){t.code((0,We._)`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,ci.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,We.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,We.not)(w),()=>t.break()))}}function h(_,w,b){let x={keyword:"additionalProperties",dataProp:_,dataPropType:ci.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};jc.default=IE});var Qh=v(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var AE=$n(),Jh=Le(),Lc=q(),Yh=Mc(),NE={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&&Yh.default.code(new AE.KeywordCxt(i,Yh.default,"additionalProperties"));let s=(0,Jh.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Lc.mergeEvaluated.props(t,(0,Lc.toHash)(s),i.props));let a=s.filter(d=>!(0,Lc.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,Jh.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)}}};qc.default=NE});var rg=v(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Xh=Le(),ui=C(),eg=q(),tg=q(),CE={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,Xh.allSchemaProperties)(r),c=a.filter(h=>(0,eg.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 ui.Name)&&(i.props=(0,tg.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,eg.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,ui._)`${(0,Xh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:tg.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,ui._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,ui.not)(u),()=>t.break())})})}}};Bc.default=CE});var ng=v(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var DE=q(),jE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,DE.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"}};Zc.default=jE});var og=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var ME=Le(),LE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ME.validateUnion,error:{message:"must match a schema in anyOf"}};Uc.default=LE});var ig=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var li=C(),qE=q(),BE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,li._)`{passingSchemas: ${e.passing}}`},ZE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:BE,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,qE.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,li._)`${c} && ${s}`).assign(s,!1).assign(a,(0,li._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,li.Name)})})}}};Fc.default=ZE});var sg=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var UE=q(),FE={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,UE.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Vc.default=FE});var ug=v(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var di=C(),cg=q(),VE={message:({params:e})=>(0,di.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,di._)`{failingKeyword: ${e.ifClause}}`},KE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,cg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ag(n,"then"),i=ag(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,di.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,di._)`${u}`):e.setParams({ifClause:u})}}}};function ag(e,t){let r=e.schema[t];return r!==void 0&&!(0,cg.alwaysValidSchema)(e,r)}Kc.default=KE});var lg=v(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var HE=q(),WE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,HE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hc.default=WE});var dg=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var GE=zc(),JE=Bh(),YE=Oc(),QE=Uh(),XE=Fh(),eT=Hh(),tT=Gh(),rT=Mc(),nT=Qh(),oT=rg(),iT=ng(),sT=og(),aT=ig(),cT=sg(),uT=ug(),lT=lg();function dT(e=!1){let t=[iT.default,sT.default,aT.default,cT.default,uT.default,lT.default,tT.default,rT.default,eT.default,nT.default,oT.default];return e?t.push(JE.default,QE.default):t.push(GE.default,YE.default),t.push(XE.default),t}Wc.default=dT});var fg=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var se=C(),fT={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},pT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:fT,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)(b(),x()));function b(){return c.strictSchema===!1?se.nil:(0,se._)`${s} && !${w}`}function x(){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){b();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(R());function b(){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 x(O){let xe=O instanceof RegExp?(0,se.regexpCode)(O):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(i)}`:void 0,Ne=r.scopeValue("formats",{key:i,ref:O,code:xe});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,se._)`${Ne}.validate`]:["string",O,Ne]}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})`}}}};Gc.default=pT});var pg=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var mT=fg(),hT=[mT.default];Jc.default=hT});var mg=v($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var gg=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var gT=$h(),yT=jh(),_T=dg(),wT=pg(),hg=mg(),vT=[gT.default,yT.default,(0,_T.default)(),wT.default,hg.metadataVocabulary,hg.contentVocabulary];Yc.default=vT});var _g=v(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.DiscrError=void 0;var yg;(function(e){e.Tag="tag",e.Mapping="mapping"})(yg||(fi.DiscrError=yg={}))});var vg=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var kr=C(),Qc=_g(),wg=Go(),bT=kn(),xT=q(),$T={message:({params:{discrError:e,tagName:t}})=>e===Qc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,kr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},kT={keyword:"discriminator",type:"object",schemaType:"object",error:$T,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,kr._)`${r}${(0,kr.getProperty)(a)}`);t.if((0,kr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Qc.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,kr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Qc.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,kr.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,xT.schemaHasRulesButRef)(O,i.self.RULES)){let Ne=O.$ref;if(O=wg.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ne),O instanceof wg.SchemaEnv&&(O=O.schema),O===void 0)throw new bT.default(i.opts.uriResolver,i.baseId,Ne)}let xe=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof xe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),b(xe,R)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(a)}function b(R,O){if(R.const)x(R.const,O);else if(R.enum)for(let xe of R.enum)x(xe,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(R,O){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[R]=O}}}};Xc.default=kT});var bg=v((xL,ST)=>{ST.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 tu=v((te,eu)=>{"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 ET=yh(),TT=gg(),RT=vg(),xg=bg(),PT=["/properties"],pi="http://json-schema.org/draft-07/schema",Sr=class extends ET.default{_addVocabularies(){super._addVocabularies(),TT.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(RT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(xg,PT):xg;this.addMetaSchema(t,pi,!1),this.refs["http://json-schema.org/schema"]=pi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pi)?pi:void 0)}};te.Ajv=Sr;eu.exports=te=Sr;eu.exports.Ajv=Sr;Object.defineProperty(te,"__esModule",{value:!0});te.default=Sr;var zT=$n();Object.defineProperty(te,"KeywordCxt",{enumerable:!0,get:function(){return zT.KeywordCxt}});var Er=C();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Er.Name}});Object.defineProperty(te,"CodeGen",{enumerable:!0,get:function(){return Er.CodeGen}});var OT=Ho();Object.defineProperty(te,"ValidationError",{enumerable:!0,get:function(){return OT.default}});var IT=kn();Object.defineProperty(te,"MissingRefError",{enumerable:!0,get:function(){return IT.default}})});var zg=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.formatNames=st.fastFormats=st.fullFormats=void 0;function it(e,t){return{validate:e,compare:t}}st.fullFormats={date:it(Eg,iu),time:it(nu(!0),su),"date-time":it($g(!0),Rg),"iso-time":it(nu(),Tg),"iso-date-time":it($g(),Pg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MT,"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:VT,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:LT,int32:{type:"number",validate:ZT},int64:{type:"number",validate:UT},float:{type:"number",validate:Sg},double:{type:"number",validate:Sg},password:!0,binary:!0};st.fastFormats={...st.fullFormats,date:it(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,iu),time:it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,su),"date-time":it(/^\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,Rg),"iso-time":it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Tg),"iso-date-time":it(/^\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,Pg),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};st.formatNames=Object.keys(st.fullFormats);function AT(e){return e%4===0&&(e%100!==0||e%400===0)}var NT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Eg(e){let t=NT.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&&AT(r)?29:CT[n])}function iu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var ru=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function nu(e){return function(r){let n=ru.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 su(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 Tg(e,t){if(!(e&&t))return;let r=ru.exec(e),n=ru.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 ou=/t|\s/i;function $g(e){let t=nu(e);return function(n){let o=n.split(ou);return o.length===2&&Eg(o[0])&&t(o[1])}}function Rg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Pg(e,t){if(!(e&&t))return;let[r,n]=e.split(ou),[o,i]=t.split(ou),s=iu(r,o);if(s!==void 0)return s||su(n,i)}var DT=/\/|:/,jT=/^(?:[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 MT(e){return DT.test(e)&&jT.test(e)}var kg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function LT(e){return kg.lastIndex=0,kg.test(e)}var qT=-(2**31),BT=2**31-1;function ZT(e){return Number.isInteger(e)&&e<=BT&&e>=qT}function UT(e){return Number.isInteger(e)}function Sg(){return!0}var FT=/[^\\]\\Z/;function VT(e){if(FT.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Og=v(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.formatLimitDefinition=void 0;var KT=tu(),Ge=C(),Pt=Ge.operators,mi={formatMaximum:{okStr:"<=",ok:Pt.LTE,fail:Pt.GT},formatMinimum:{okStr:">=",ok:Pt.GTE,fail:Pt.LT},formatExclusiveMaximum:{okStr:"<",ok:Pt.LT,fail:Pt.GTE},formatExclusiveMinimum:{okStr:">",ok:Pt.GT,fail:Pt.LTE}},HT={message:({keyword:e,schemaCode:t})=>(0,Ge.str)`should be ${mi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ge._)`{comparison: ${mi[e].okStr}, limit: ${t}}`};Tr.formatLimitDefinition={keyword:Object.keys(mi),type:"string",schemaType:"string",$data:!0,error:HT,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 KT.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,Ge._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ge.or)((0,Ge._)`typeof ${p} != "object"`,(0,Ge._)`${p} instanceof RegExp`,(0,Ge._)`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,Ge._)`${s.code.formats}${(0,Ge.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ge._)`${f}.compare(${r}, ${n}) ${mi[o].fail} 0`}},dependencies:["format"]};var WT=e=>(e.addKeyword(Tr.formatLimitDefinition),e);Tr.default=WT});var Cg=v((Mn,Ng)=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});var Rr=zg(),GT=Og(),au=C(),Ig=new au.Name("fullFormats"),JT=new au.Name("fastFormats"),cu=(e,t={keywords:!0})=>{if(Array.isArray(t))return Ag(e,t,Rr.fullFormats,Ig),e;let[r,n]=t.mode==="fast"?[Rr.fastFormats,JT]:[Rr.fullFormats,Ig],o=t.formats||Rr.formatNames;return Ag(e,o,r,n),t.keywords&&(0,GT.default)(e),e};cu.get=(e,t="full")=>{let n=(t==="fast"?Rr.fastFormats:Rr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Ag(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,au._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Ng.exports=Mn=cu;Object.defineProperty(Mn,"__esModule",{value:!0});Mn.default=cu});var Fg=v((DL,Ug)=>{Ug.exports=Zg;Zg.sync=eR;var qg=yt("fs");function XT(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 Bg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:XT(t,r)}function Zg(e,t,r){qg.stat(e,function(n,o){r(n,n?!1:Bg(o,e,t))})}function eR(e,t){return Bg(qg.statSync(e),e,t)}});var Gg=v((jL,Wg)=>{Wg.exports=Kg;Kg.sync=tR;var Vg=yt("fs");function Kg(e,t,r){Vg.stat(e,function(n,o){r(n,n?!1:Hg(o,t))})}function tR(e,t){return Hg(Vg.statSync(e),t)}function Hg(e,t){return e.isFile()&&rR(e,t)}function rR(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 Yg=v((LL,Jg)=>{var ML=yt("fs"),wi;process.platform==="win32"||global.TESTING_WINDOWS?wi=Fg():wi=Gg();Jg.exports=uu;uu.sync=nR;function uu(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){uu(e,t||{},function(i,s){i?o(i):n(s)})})}wi(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function nR(e,t){try{return wi.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var oy=v((qL,ny)=>{var Pr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Qg=yt("path"),oR=Pr?";":":",Xg=Yg(),ey=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),ty=(e,t)=>{let r=t.colon||oR,n=e.match(/\//)||Pr&&e.match(/\\/)?[""]:[...Pr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Pr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Pr?o.split(r):[""];return Pr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},ry=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=ty(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(ey(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=Qg.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];Xg(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)},iR=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=ty(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Qg.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(Xg.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 ey(e)};ny.exports=ry;ry.sync=iR});var sy=v((BL,lu)=>{"use strict";var iy=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};lu.exports=iy;lu.exports.default=iy});var ly=v((ZL,uy)=>{"use strict";var ay=yt("path"),sR=oy(),aR=sy();function cy(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=sR.sync(e.command,{path:r[aR({env:r})],pathExt:t?ay.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=ay.resolve(o?e.options.cwd:"",s)),s}function cR(e){return cy(e)||cy(e,!0)}uy.exports=cR});var dy=v((UL,fu)=>{"use strict";var du=/([()\][%!^"`<>&|;, *?])/g;function uR(e){return e=e.replace(du,"^$1"),e}function lR(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(du,"^$1"),t&&(e=e.replace(du,"^$1")),e}fu.exports.command=uR;fu.exports.argument=lR});var py=v((FL,fy)=>{"use strict";fy.exports=/^#!(.*)/});var hy=v((VL,my)=>{"use strict";var dR=py();my.exports=(e="")=>{let t=e.match(dR);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var yy=v((KL,gy)=>{"use strict";var pu=yt("fs"),fR=hy();function pR(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 fR(r.toString())}gy.exports=pR});var by=v((HL,vy)=>{"use strict";var mR=yt("path"),_y=ly(),wy=dy(),hR=yy(),gR=process.platform==="win32",yR=/\.(?:com|exe)$/i,_R=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function wR(e){e.file=_y(e);let t=e.file&&hR(e.file);return t?(e.args.unshift(e.file),e.command=t,_y(e)):e.file}function vR(e){if(!gR)return e;let t=wR(e),r=!yR.test(t);if(e.options.forceShell||r){let n=_R.test(t);e.command=mR.normalize(e.command),e.command=wy.command(e.command),e.args=e.args.map(i=>wy.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 bR(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:vR(n)}vy.exports=bR});var ky=v((WL,$y)=>{"use strict";var mu=process.platform==="win32";function hu(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 xR(e,t){if(!mu)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=xy(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function xy(e,t){return mu&&e===1&&!t.file?hu(t.original,"spawn"):null}function $R(e,t){return mu&&e===1&&!t.file?hu(t.original,"spawnSync"):null}$y.exports={hookChildProcess:xR,verifyENOENT:xy,verifyENOENTSync:$R,notFoundError:hu}});var Ty=v((GL,zr)=>{"use strict";var Sy=yt("child_process"),gu=by(),yu=ky();function Ey(e,t,r){let n=gu(e,t,r),o=Sy.spawn(n.command,n.args,n.options);return yu.hookChildProcess(o,n),o}function kR(e,t,r){let n=gu(e,t,r),o=Sy.spawnSync(n.command,n.args,n.options);return o.error=o.error||yu.verifyENOENTSync(o.status,n),o}zr.exports=Ey;zr.exports.spawn=Ey;zr.exports.sync=kR;zr.exports._parse=gu;zr.exports._enoent=yu});import{readFile as pA,mkdir as mA,writeFile as hA}from"node:fs/promises";import{dirname as gA,join as Lw}from"node:path";function wl(e){let t={app:e,version:Hw(or("__RED_BUILD_VERSION__",()=>"3.1.0")??"0.0.0-dev"),gitSha:or("__RED_BUILD_GIT_SHA__",()=>"540d78ae57d6bb7186540d12ab175eea62ec82a4")??"unknown",buildTime:or("__RED_BUILD_TIME__",()=>"2026-07-31T20:29:52Z")??"unknown",bundleAsset:or("__RED_BUNDLE_ASSET__",()=>"brain.bundle.min.mjs")??"unknown"},r=or("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=or("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Hw(e){return e.startsWith("v")?e.slice(1):e}function vl(e){return`${e.app} ${e.version} ${e.gitSha}`}function or(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var CA=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 DA=Symbol("zod_brand"),ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},oo={};function Ce(e){return e&&Object.assign(oo,e),oo}var U={};_l(U,{BIGINT_FORMAT_RANGES:()=>xl,Class:()=>Xi,NUMBER_FORMAT_RANGES:()=>as,aborted:()=>Dt,allowsEval:()=>os,assert:()=>Qw,assertEqual:()=>Ww,assertIs:()=>Jw,assertNever:()=>Yw,assertNotEqual:()=>Gw,assignProp:()=>ns,cached:()=>Zr,captureStackTrace:()=>so,cleanEnum:()=>dv,cleanRegex:()=>Fr,clone:()=>et,createTransparentProxy:()=>ov,defineLazy:()=>W,esc:()=>Ct,escapeRegex:()=>_t,extend:()=>av,finalizeIssue:()=>Ue,floatSafeRemainder:()=>rs,getElementAtPath:()=>Xw,getEnumValues:()=>es,getLengthableOrigin:()=>Vr,getParsedType:()=>nv,getSizableOrigin:()=>$l,isObject:()=>ir,isPlainObject:()=>sr,issue:()=>cs,joinValues:()=>io,jsonStringifyReplacer:()=>ts,merge:()=>cv,normalizeParams:()=>P,nullish:()=>Ur,numKeys:()=>rv,omit:()=>sv,optionalKeys:()=>ss,partial:()=>uv,pick:()=>iv,prefixIssues:()=>tt,primitiveTypes:()=>bl,promiseAllObject:()=>ev,propertyKeyTypes:()=>is,randomString:()=>tv,required:()=>lv,stringifyPrimitive:()=>ao,unwrapMessage:()=>Br});function Ww(e){return e}function Gw(e){return e}function Jw(e){}function Yw(e){throw new Error}function Qw(e){}function es(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 io(e,t="|"){return e.map(r=>ao(r)).join(t)}function ts(e,t){return typeof t=="bigint"?t.toString():t}function Zr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ur(e){return e==null}function Fr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rs(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 ns(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Xw(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function ev(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 tv(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Ct(e){return JSON.stringify(e)}var so=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var os=Zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function sr(e){if(ir(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(ir(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function rv(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var nv=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}`)}},is=new Set(["string","number","symbol"]),bl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function et(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 ov(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 ao(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ss(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var as={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]},xl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function iv(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 et(e,{...e._zod.def,shape:r,checks:[]})}function sv(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 et(e,{...e._zod.def,shape:r,checks:[]})}function av(e,t){if(!sr(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 ns(this,"shape",n),n},checks:[]};return et(e,r)}function cv(e,t){return et(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ns(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function uv(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 et(t,{...t._zod.def,shape:o,checks:[]})}function lv(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 et(t,{...t._zod.def,shape:o,checks:[]})}function Dt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function tt(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Br(e){return typeof e=="string"?e:e?.message}function Ue(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Br(e.inst?._zod.def?.error?.(e))??Br(t?.error?.(e))??Br(r.customError?.(e))??Br(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function $l(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Vr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cs(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function dv(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Xi=class{constructor(...t){}};var kl=(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,ts,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},co=y("$ZodError",kl),us=y("$ZodError",kl,{Parent:Error});function Sl(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 El(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 Tl=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 ut;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ue(c,i,Ce())));throw so(a,o?.callee),a}return s.value};var Rl=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=>Ue(c,i,Ce())));throw so(a,o?.callee),a}return s.value};var ls=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 ut;return i.issues.length?{success:!1,error:new(e??co)(i.issues.map(s=>Ue(s,o,Ce())))}:{success:!0,data:i.value}},Kr=ls(us),ds=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=>Ue(s,o,Ce())))}:{success:!0,data:i.value}},uo=ds(us);var Pl=/^[cC][^\s-]{8,}$/,zl=/^[0-9a-z]+$/,Ol=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Il=/^[0-9a-vA-V]{20}$/,Al=/^[A-Za-z0-9]{27}$/,Nl=/^[a-zA-Z0-9_-]{21}$/,Cl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Dl=/^([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})$/,fs=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 jl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var pv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ml(){return new RegExp(pv,"u")}var Ll=/^(?:(?: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])$/,ql=/^(([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})$/,Bl=/^((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])$/,Zl=/^(([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])$/,Ul=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ps=/^[A-Za-z0-9_-]*$/,Fl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Vl=/^\+(?:[0-9]){6,14}[0-9]$/,Kl="(?:(?:\\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])))",Hl=new RegExp(`^${Kl}$`);function Wl(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 Gl(e){return new RegExp(`^${Wl(e)}$`)}function Jl(e){let t=Wl({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(`^${Kl}T(?:${n})$`)}var Yl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ql=/^\d+$/,Xl=/^-?\d+(?:\.\d+)?/i,ed=/true|false/i,td=/null/i;var rd=/^[^A-Z]*$/,nd=/^[^a-z]*$/;var ge=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),od={number:"number",bigint:"bigint",object:"date"},hs=y("$ZodCheckLessThan",(e,t)=>{ge.init(e,t);let r=od[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})}}),gs=y("$ZodCheckGreaterThan",(e,t)=>{ge.init(e,t);let r=od[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})}}),id=y("$ZodCheckMultipleOf",(e,t)=>{ge.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):rs(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})}}),sd=y("$ZodCheckNumberFormat",(e,t)=>{ge.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=as[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=Ql)}),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 ad=y("$ZodCheckMaxLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cd=y("$ZodCheckMinLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ud=y("$ZodCheckLengthEquals",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(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=Vr(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})}}),Hr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;ge.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=()=>{})}),ld=y("$ZodCheckRegex",(e,t)=>{Hr.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})}}),dd=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=rd),Hr.init(e,t)}),fd=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=nd),Hr.init(e,t)}),pd=y("$ZodCheckIncludes",(e,t)=>{ge.init(e,t);let r=_t(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})}}),md=y("$ZodCheckStartsWith",(e,t)=>{ge.init(e,t);let r=new RegExp(`^${_t(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})}}),hd=y("$ZodCheckEndsWith",(e,t)=>{ge.init(e,t);let r=new RegExp(`.*${_t(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 gd=y("$ZodCheckOverwrite",(e,t)=>{ge.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var lo=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 yd={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=yd;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=Dt(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 at;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Dt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Dt(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 at;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Kr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return uo(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),po=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jl(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)=>{Hr.init(e,t),po.init(e,t)}),Td=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cl),Q.init(e,t)}),Rd=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=fs(n))}else t.pattern??(t.pattern=fs());Q.init(e,t)}),Pd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Dl),Q.init(e,t)}),zd=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:Ul.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})}}}),Od=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jl()),Q.init(e,t)}),Id=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Al),Q.init(e,t)}),Ad=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rl),Q.init(e,t)}),Nd=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pl),Q.init(e,t)}),Cd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=zl),Q.init(e,t)}),Dd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ol),Q.init(e,t)}),jd=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Il),Q.init(e,t)}),Md=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gl(t)),Q.init(e,t)}),Ld=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kl),Q.init(e,t)}),qd=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Wl(t)),Q.init(e,t)}),Bd=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Nl),Q.init(e,t)}),Zd=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ml),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Ud=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ll),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})}}}),Fd=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ql),Q.init(e,t)}),Vd=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Bl),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 Kd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Hd=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Zl),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Kd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function rv(e){if(!ps.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Kd(r)}var Wd=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=>{rv(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Gd=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Fl),Q.init(e,t)});function nv(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 Jd=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{nv(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var _s=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ql,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}}),Yd=y("$ZodNumber",(e,t)=>{id.init(e,t),_s.init(e,t)}),Qd=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=Xl,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 Xd=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=ed,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 ef=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),tf=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 _d(e,t,r){e.issues.length&&t.issues.push(...Xe(r,e.issues)),t.value[r]=e.value}var rf=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=>_d(l,r,s))):_d(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function fo(e,t,r){e.issues.length&&t.issues.push(...Xe(r,e.issues)),t.value[r]=e.value}function wd(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(...Xe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var nf=y("$ZodObject",(e,t)=>{G.init(e,t);let r=Zr(()=>{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=ss(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 lo(["shape","payload","ctx"]),p=r.value,m=b=>{let x=Ct(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let b of p.keys)h[b]=`key_${_++}`;f.write("const newResult = {}");for(let b of p.keys)if(p.optionalKeys.has(b)){let x=h[b];f.write(`const ${x} = ${m(b)};`);let R=Ct(b);f.write(`
12
+ `))}};var _d={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=_d;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=Dt(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 ut;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Dt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Dt(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 ut;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Kr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return uo(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),po=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yl(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)=>{Hr.init(e,t),po.init(e,t)}),Rd=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Dl),Q.init(e,t)}),Pd=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=fs(n))}else t.pattern??(t.pattern=fs());Q.init(e,t)}),zd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=jl),Q.init(e,t)}),Od=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:Fl.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})}}}),Id=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ml()),Q.init(e,t)}),Ad=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Nl),Q.init(e,t)}),Nd=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Pl),Q.init(e,t)}),Cd=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=zl),Q.init(e,t)}),Dd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ol),Q.init(e,t)}),jd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Il),Q.init(e,t)}),Md=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Al),Q.init(e,t)}),Ld=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Jl(t)),Q.init(e,t)}),qd=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Hl),Q.init(e,t)}),Bd=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Gl(t)),Q.init(e,t)}),Zd=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Cl),Q.init(e,t)}),Ud=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ll),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Fd=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ql),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})}}}),Vd=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Bl),Q.init(e,t)}),Kd=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Zl),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 Hd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Wd=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ul),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Hd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function mv(e){if(!ps.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Hd(r)}var Gd=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=>{mv(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Jd=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vl),Q.init(e,t)});function hv(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 Yd=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{hv(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var _s=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xl,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}}),Qd=y("$ZodNumber",(e,t)=>{sd.init(e,t),_s.init(e,t)}),Xd=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=ed,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 ef=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=td,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 tf=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),rf=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 wd(e,t,r){e.issues.length&&t.issues.push(...tt(r,e.issues)),t.value[r]=e.value}var nf=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=>wd(l,r,s))):wd(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function fo(e,t,r){e.issues.length&&t.issues.push(...tt(r,e.issues)),t.value[r]=e.value}function vd(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(...tt(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var of=y("$ZodObject",(e,t)=>{G.init(e,t);let r=Zr(()=>{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=ss(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 lo(["shape","payload","ctx"]),p=r.value,m=b=>{let x=Ct(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let b of p.keys)h[b]=`key_${_++}`;f.write("const newResult = {}");for(let b of p.keys)if(p.optionalKeys.has(b)){let x=h[b];f.write(`const ${x} = ${m(b)};`);let R=Ct(b);f.write(`
13
13
  if (${x}.issues.length) {
14
14
  if (input[${R}] === undefined) {
15
15
  if (${R} in input) {
@@ -32,48 +32,55 @@ var Pw=Object.create;var Ji=Object.defineProperty;var zw=Object.getOwnPropertyDe
32
32
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
33
33
  ...iss,
34
34
  path: iss.path ? [${Ct(b)}, ...iss.path] : [${Ct(b)}]
35
- })));`),f.write(`newResult[${Ct(b)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,x)=>w(d,b,x)},o,i=ir,s=!oo.jitless,c=s&&os.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 x=u.shape;for(let R of u.keys){let O=x[R],xe=O._zod.run({value:p[R],issues:[]},f),Ne=O._zod.optin==="optional"&&O._zod.optout==="optional";xe instanceof Promise?m.push(xe.then(nr=>Ne?wd(nr,d,R,p):fo(nr,d,R))):Ne?wd(xe,d,R,p):fo(xe,d,R)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,b=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(b==="never"){h.push(x);continue}let R=w.run({value:p[x],issues:[]},f);R instanceof Promise?m.push(R.then(O=>fo(O,d,x))):fo(R,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function vd(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=>Ue(i,n,Ce())))}),t}var ws=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=>Fr(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=>vd(s,r,e,n)):vd(i,r,e,n)}}),of=y("$ZodDiscriminatedUnion",(e,t)=>{ws.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=Zr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!ir(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)}}),sf=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])=>bd(r,c,l)):bd(r,i,s)}});function ys(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(sr(e)&&sr(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=ys(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=ys(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 bd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Dt(e))return e;let n=ys(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 af=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!sr(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(...Xe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Xe(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=>Ue(l,n,Ce())),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(...Xe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Xe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var cf=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=es(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>is.has(typeof n)).map(n=>typeof n=="string"?_t(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}}),uf=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"?_t(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 lf=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 at;return r.value=o,r}}),df=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(`^(${Fr(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)}),ff=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(`^(${Fr(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)}),pf=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=>xd(i,t)):xd(o,t)}});function xd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var mf=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))}),hf=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=>$d(i,e)):$d(o,e)}});function $d(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 gf=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=>Ue(s,n,Ce()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ue(i,n,Ce()))},input:r.value}),r.issues=[]),r)}});var yf=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 Dt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var _f=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(Sd):Sd(o)}});function Sd(e){return e.value=Object.freeze(e.value),e}var wf=y("$ZodCustom",(e,t)=>{ge.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=>Ed(i,r,n,e));Ed(o,r,n,e)}});function Ed(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(cs(o))}}var ov=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},iv=()=>{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 ${ov(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ao(n.values[0])}`:`Invalid option: expected one of ${io(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":""}: ${io(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 vf(){return{localeError:iv()}}var DA=Symbol("ZodOutput"),jA=Symbol("ZodInput"),vs=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 sv(){return new vs}var Wr=sv();function bf(e,t){return new e({type:"string",...P(t)})}function xf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function bs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function $f(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 Sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Tf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Rf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Pf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function zf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Of(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function If(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function Af(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Nf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function Cf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function Df(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function jf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Mf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Lf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function qf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function Bf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function Zf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function Uf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Ff(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function Vf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function Kf(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Hf(e,t){return new e({type:"number",checks:[],...P(t)})}function Wf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Gf(e,t){return new e({type:"boolean",...P(t)})}function Jf(e,t){return new e({type:"null",...P(t)})}function Yf(e){return new e({type:"unknown"})}function Qf(e,t){return new e({type:"never",...P(t)})}function mo(e,t){return new hs({check:"less_than",...P(t),value:e,inclusive:!1})}function Gr(e,t){return new hs({check:"less_than",...P(t),value:e,inclusive:!0})}function ho(e,t){return new gs({check:"greater_than",...P(t),value:e,inclusive:!1})}function Jr(e,t){return new gs({check:"greater_than",...P(t),value:e,inclusive:!0})}function go(e,t){return new od({check:"multiple_of",...P(t),value:e})}function yo(e,t){return new sd({check:"max_length",...P(t),maximum:e})}function ar(e,t){return new ad({check:"min_length",...P(t),minimum:e})}function _o(e,t){return new cd({check:"length_equals",...P(t),length:e})}function xs(e,t){return new ud({check:"string_format",format:"regex",...P(t),pattern:e})}function $s(e){return new ld({check:"string_format",format:"lowercase",...P(e)})}function ks(e){return new dd({check:"string_format",format:"uppercase",...P(e)})}function Ss(e,t){return new fd({check:"string_format",format:"includes",...P(t),includes:e})}function Es(e,t){return new pd({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Ts(e,t){return new md({check:"string_format",format:"ends_with",...P(t),suffix:e})}function jt(e){return new hd({check:"overwrite",tx:e})}function Rs(e){return jt(t=>t.normalize(e))}function Ps(){return jt(e=>e.trim())}function zs(){return jt(e=>e.toLowerCase())}function Os(){return jt(e=>e.toUpperCase())}function Xf(e,t,r){return new e({type:"array",element:t,...P(r)})}function ep(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function tp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function cr(e){return!!e._zod}function Fe(e,t){return cr(e)?Kr(e,t):e.safeParse(t)}function wo(e){if(!e)return;let t;if(cr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function rp(e){if(cr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var Qr={};yl(Qr,{ZodISODate:()=>op,ZodISODateTime:()=>np,ZodISODuration:()=>sp,ZodISOTime:()=>ip,date:()=>As,datetime:()=>Is,duration:()=>Cs,time:()=>Ns});var np=y("ZodISODateTime",(e,t)=>{Md.init(e,t),re.init(e,t)});function Is(e){return Uf(np,e)}var op=y("ZodISODate",(e,t)=>{Ld.init(e,t),re.init(e,t)});function As(e){return Ff(op,e)}var ip=y("ZodISOTime",(e,t)=>{qd.init(e,t),re.init(e,t)});function Ns(e){return Vf(ip,e)}var sp=y("ZodISODuration",(e,t)=>{Bd.init(e,t),re.init(e,t)});function Cs(e){return Kf(sp,e)}var ap=(e,t)=>{co.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Sl(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}}})},yN=y("ZodError",ap),Xr=y("ZodError",ap,{Parent:Error});var cp=El(Xr),up=Tl(Xr),lp=ls(Xr),dp=ds(Xr);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)=>Qe(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>cp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>lp(e,r,n),e.parseAsync=async(r,n)=>up(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>dp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(nb(r,n)),e.superRefine=r=>e.check(ob(r)),e.overwrite=r=>e.check(jt(r)),e.optional=()=>oe(e),e.nullable=()=>mp(e),e.nullish=()=>oe(mp(e)),e.nonoptional=r=>Jv(e,r),e.array=()=>M(e),e.or=r=>X([e,r]),e.and=r=>bo(e,r),e.transform=r=>js(e,vp(r)),e.default=r=>Hv(e,r),e.prefault=r=>Gv(e,r),e.catch=r=>Qv(e,r),e.pipe=r=>js(e,r),e.readonly=()=>tb(e),e.describe=r=>{let n=e.clone();return Wr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Wr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Wr.get(e);let n=e.clone();return Wr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),hp=y("_ZodString",(e,t)=>{po.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(xs(...n)),e.includes=(...n)=>e.check(Ss(...n)),e.startsWith=(...n)=>e.check(Es(...n)),e.endsWith=(...n)=>e.check(Ts(...n)),e.min=(...n)=>e.check(ar(...n)),e.max=(...n)=>e.check(yo(...n)),e.length=(...n)=>e.check(_o(...n)),e.nonempty=(...n)=>e.check(ar(1,...n)),e.lowercase=n=>e.check($s(n)),e.uppercase=n=>e.check(ks(n)),e.trim=()=>e.check(Ps()),e.normalize=(...n)=>e.check(Rs(...n)),e.toLowerCase=()=>e.check(zs()),e.toUpperCase=()=>e.check(Os())}),hv=y("ZodString",(e,t)=>{po.init(e,t),hp.init(e,t),e.email=r=>e.check(xf(gv,r)),e.url=r=>e.check(Tf(yv,r)),e.jwt=r=>e.check(Zf(Iv,r)),e.emoji=r=>e.check(Rf(_v,r)),e.guid=r=>e.check(bs(fp,r)),e.uuid=r=>e.check($f(vo,r)),e.uuidv4=r=>e.check(kf(vo,r)),e.uuidv6=r=>e.check(Sf(vo,r)),e.uuidv7=r=>e.check(Ef(vo,r)),e.nanoid=r=>e.check(Pf(wv,r)),e.guid=r=>e.check(bs(fp,r)),e.cuid=r=>e.check(zf(vv,r)),e.cuid2=r=>e.check(Of(bv,r)),e.ulid=r=>e.check(If(xv,r)),e.base64=r=>e.check(Lf(Pv,r)),e.base64url=r=>e.check(qf(zv,r)),e.xid=r=>e.check(Af($v,r)),e.ksuid=r=>e.check(Nf(kv,r)),e.ipv4=r=>e.check(Cf(Sv,r)),e.ipv6=r=>e.check(Df(Ev,r)),e.cidrv4=r=>e.check(jf(Tv,r)),e.cidrv6=r=>e.check(Mf(Rv,r)),e.e164=r=>e.check(Bf(Ov,r)),e.datetime=r=>e.check(Is(r)),e.date=r=>e.check(As(r)),e.time=r=>e.check(Ns(r)),e.duration=r=>e.check(Cs(r))});function g(e){return bf(hv,e)}var re=y("ZodStringFormat",(e,t)=>{Q.init(e,t),hp.init(e,t)}),gv=y("ZodEmail",(e,t)=>{Pd.init(e,t),re.init(e,t)});var fp=y("ZodGUID",(e,t)=>{Td.init(e,t),re.init(e,t)});var vo=y("ZodUUID",(e,t)=>{Rd.init(e,t),re.init(e,t)});var yv=y("ZodURL",(e,t)=>{zd.init(e,t),re.init(e,t)});var _v=y("ZodEmoji",(e,t)=>{Od.init(e,t),re.init(e,t)});var wv=y("ZodNanoID",(e,t)=>{Id.init(e,t),re.init(e,t)});var vv=y("ZodCUID",(e,t)=>{Ad.init(e,t),re.init(e,t)});var bv=y("ZodCUID2",(e,t)=>{Nd.init(e,t),re.init(e,t)});var xv=y("ZodULID",(e,t)=>{Cd.init(e,t),re.init(e,t)});var $v=y("ZodXID",(e,t)=>{Dd.init(e,t),re.init(e,t)});var kv=y("ZodKSUID",(e,t)=>{jd.init(e,t),re.init(e,t)});var Sv=y("ZodIPv4",(e,t)=>{Zd.init(e,t),re.init(e,t)});var Ev=y("ZodIPv6",(e,t)=>{Ud.init(e,t),re.init(e,t)});var Tv=y("ZodCIDRv4",(e,t)=>{Fd.init(e,t),re.init(e,t)});var Rv=y("ZodCIDRv6",(e,t)=>{Vd.init(e,t),re.init(e,t)});var Pv=y("ZodBase64",(e,t)=>{Hd.init(e,t),re.init(e,t)});var zv=y("ZodBase64URL",(e,t)=>{Wd.init(e,t),re.init(e,t)});var Ov=y("ZodE164",(e,t)=>{Gd.init(e,t),re.init(e,t)});var Iv=y("ZodJWT",(e,t)=>{Jd.init(e,t),re.init(e,t)});var gp=y("ZodNumber",(e,t)=>{_s.init(e,t),ie.init(e,t),e.gt=(n,o)=>e.check(ho(n,o)),e.gte=(n,o)=>e.check(Jr(n,o)),e.min=(n,o)=>e.check(Jr(n,o)),e.lt=(n,o)=>e.check(mo(n,o)),e.lte=(n,o)=>e.check(Gr(n,o)),e.max=(n,o)=>e.check(Gr(n,o)),e.int=n=>e.check(pp(n)),e.safe=n=>e.check(pp(n)),e.positive=n=>e.check(ho(0,n)),e.nonnegative=n=>e.check(Jr(0,n)),e.negative=n=>e.check(mo(0,n)),e.nonpositive=n=>e.check(Gr(0,n)),e.multipleOf=(n,o)=>e.check(go(n,o)),e.step=(n,o)=>e.check(go(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 Hf(gp,e)}var Av=y("ZodNumberFormat",(e,t)=>{Yd.init(e,t),gp.init(e,t)});function pp(e){return Wf(Av,e)}var Nv=y("ZodBoolean",(e,t)=>{Qd.init(e,t),ie.init(e,t)});function ue(e){return Gf(Nv,e)}var Cv=y("ZodNull",(e,t)=>{Xd.init(e,t),ie.init(e,t)});function yp(e){return Jf(Cv,e)}var Dv=y("ZodUnknown",(e,t)=>{ef.init(e,t),ie.init(e,t)});function ne(){return Yf(Dv)}var jv=y("ZodNever",(e,t)=>{tf.init(e,t),ie.init(e,t)});function Mv(e){return Qf(jv,e)}var Lv=y("ZodArray",(e,t)=>{rf.init(e,t),ie.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ar(r,n)),e.nonempty=r=>e.check(ar(1,r)),e.max=(r,n)=>e.check(yo(r,n)),e.length=(r,n)=>e.check(_o(r,n)),e.unwrap=()=>e.element});function M(e,t){return Xf(Lv,e,t)}var _p=y("ZodObject",(e,t)=>{nf.init(e,t),ie.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Te(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:Mv()}),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(bp,e,r[0]),e.required=(...r)=>U.required(xp,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 _p(r)}function $e(e,t){return new _p({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:ne(),...U.normalizeParams(t)})}var wp=y("ZodUnion",(e,t)=>{ws.init(e,t),ie.init(e,t),e.options=t.options});function X(e,t){return new wp({type:"union",options:e,...U.normalizeParams(t)})}var qv=y("ZodDiscriminatedUnion",(e,t)=>{wp.init(e,t),of.init(e,t)});function Ms(e,t,r){return new qv({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Bv=y("ZodIntersection",(e,t)=>{sf.init(e,t),ie.init(e,t)});function bo(e,t){return new Bv({type:"intersection",left:e,right:t})}var Zv=y("ZodRecord",(e,t)=>{af.init(e,t),ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new Zv({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var Ds=y("ZodEnum",(e,t)=>{cf.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 Ds({...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 Ds({...t,checks:[],...U.normalizeParams(o),entries:i})}});function Te(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ds({type:"enum",entries:r,...U.normalizeParams(t)})}var Uv=y("ZodLiteral",(e,t)=>{uf.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 k(e,t){return new Uv({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var Fv=y("ZodTransform",(e,t)=>{lf.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 vp(e){return new Fv({type:"transform",transform:e})}var bp=y("ZodOptional",(e,t)=>{df.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function oe(e){return new bp({type:"optional",innerType:e})}var Vv=y("ZodNullable",(e,t)=>{ff.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mp(e){return new Vv({type:"nullable",innerType:e})}var Kv=y("ZodDefault",(e,t)=>{pf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hv(e,t){return new Kv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Wv=y("ZodPrefault",(e,t)=>{mf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gv(e,t){return new Wv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var xp=y("ZodNonOptional",(e,t)=>{hf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Jv(e,t){return new xp({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var Yv=y("ZodCatch",(e,t)=>{gf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qv(e,t){return new Yv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Xv=y("ZodPipe",(e,t)=>{yf.init(e,t),ie.init(e,t),e.in=t.in,e.out=t.out});function js(e,t){return new Xv({type:"pipe",in:e,out:t})}var eb=y("ZodReadonly",(e,t)=>{_f.init(e,t),ie.init(e,t)});function tb(e){return new eb({type:"readonly",innerType:e})}var $p=y("ZodCustom",(e,t)=>{wf.init(e,t),ie.init(e,t)});function rb(e){let t=new ge({check:"custom"});return t._zod.check=e,t}function kp(e,t){return ep($p,e??(()=>!0),t)}function nb(e,t={}){return tp($p,e,t)}function ob(e){let t=rb(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 Ls(e,t){return js(vp(e),t)}Ce(vf());var Bs="2025-11-25";var Sp=[Bs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],wt="io.modelcontextprotocol/related-task",$o="2.0",ce=kp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Ep=X([g(),V().int()]),Tp=g(),lC=$e({ttl:V().optional(),pollInterval:V().optional()}),ib=$({ttl:V().optional()}),sb=$({taskId:g()}),Zs=$e({progressToken:Ep.optional(),[wt]:sb.optional()}),Ae=$({_meta:Zs.optional()}),en=Ae.extend({task:ib.optional()}),Rp=e=>en.safeParse(e).success,le=$({method:g(),params:Ae.loose().optional()}),De=$({_meta:Zs.optional()}),je=$({method:g(),params:De.loose().optional()}),de=$e({_meta:Zs.optional()}),ko=X([g(),V().int()]),Pp=$({jsonrpc:k($o),id:ko,...le.shape}).strict(),Us=e=>Pp.safeParse(e).success,zp=$({jsonrpc:k($o),...je.shape}).strict(),Op=e=>zp.safeParse(e).success,Fs=$({jsonrpc:k($o),id:ko,result:de}).strict(),tn=e=>Fs.safeParse(e).success;var I;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(I||(I={}));var Vs=$({jsonrpc:k($o),id:ko.optional(),error:$({code:V().int(),message:g(),data:ne().optional()})}).strict();var Ip=e=>Vs.safeParse(e).success;var Ap=X([Pp,zp,Fs,Vs]),dC=X([Fs,Vs]),Mt=de.strict(),ab=De.extend({requestId:ko.optional(),reason:g().optional()}),So=je.extend({method:k("notifications/cancelled"),params:ab}),cb=$({src:g(),mimeType:g().optional(),sizes:M(g()).optional(),theme:Te(["light","dark"]).optional()}),rn=$({icons:M(cb).optional()}),ur=$({name:g(),title:g().optional()}),Np=ur.extend({...ur.shape,...rn.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),ub=bo($({applyDefaults:ue().optional()}),J(g(),ne())),lb=Ls(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,bo($({form:ub.optional(),url:ce.optional()}),J(g(),ne()).optional())),db=$e({list:ce.optional(),cancel:ce.optional(),requests:$e({sampling:$e({createMessage:ce.optional()}).optional(),elicitation:$e({create:ce.optional()}).optional()}).optional()}),fb=$e({list:ce.optional(),cancel:ce.optional(),requests:$e({tools:$e({call:ce.optional()}).optional()}).optional()}),pb=$({experimental:J(g(),ce).optional(),sampling:$({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:lb.optional(),roots:$({listChanged:ue().optional()}).optional(),tasks:db.optional(),extensions:J(g(),ce).optional()}),mb=Ae.extend({protocolVersion:g(),capabilities:pb,clientInfo:Np}),hb=le.extend({method:k("initialize"),params:mb});var gb=$({experimental:J(g(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:$({listChanged:ue().optional()}).optional(),resources:$({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:$({listChanged:ue().optional()}).optional(),tasks:fb.optional(),extensions:J(g(),ce).optional()}),Ks=de.extend({protocolVersion:g(),capabilities:gb,serverInfo:Np,instructions:g().optional()}),yb=je.extend({method:k("notifications/initialized"),params:De.optional()});var Eo=le.extend({method:k("ping"),params:Ae.optional()}),_b=$({progress:V(),total:oe(V()),message:oe(g())}),wb=$({...De.shape,..._b.shape,progressToken:Ep}),To=je.extend({method:k("notifications/progress"),params:wb}),vb=Ae.extend({cursor:Tp.optional()}),nn=le.extend({params:vb.optional()}),on=de.extend({nextCursor:Tp.optional()}),bb=Te(["working","input_required","completed","failed","cancelled"]),sn=$({taskId:g(),status:bb,ttl:X([V(),yp()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:oe(V()),statusMessage:oe(g())}),Lt=de.extend({task:sn}),xb=De.merge(sn),an=je.extend({method:k("notifications/tasks/status"),params:xb}),Ro=le.extend({method:k("tasks/get"),params:Ae.extend({taskId:g()})}),Po=de.merge(sn),zo=le.extend({method:k("tasks/result"),params:Ae.extend({taskId:g()})}),fC=de.loose(),Oo=nn.extend({method:k("tasks/list")}),Io=on.extend({tasks:M(sn)}),Ao=le.extend({method:k("tasks/cancel"),params:Ae.extend({taskId:g()})}),Cp=de.merge(sn),Dp=$({uri:g(),mimeType:oe(g()),_meta:J(g(),ne()).optional()}),jp=Dp.extend({text:g()}),Hs=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mp=Dp.extend({blob:Hs}),cn=Te(["user","assistant"]),lr=$({audience:M(cn).optional(),priority:V().min(0).max(1).optional(),lastModified:Qr.datetime({offset:!0}).optional()}),Lp=$({...ur.shape,...rn.shape,uri:g(),description:oe(g()),mimeType:oe(g()),size:oe(V()),annotations:lr.optional(),_meta:oe($e({}))}),$b=$({...ur.shape,...rn.shape,uriTemplate:g(),description:oe(g()),mimeType:oe(g()),annotations:lr.optional(),_meta:oe($e({}))}),kb=nn.extend({method:k("resources/list")}),Ws=on.extend({resources:M(Lp)}),Sb=nn.extend({method:k("resources/templates/list")}),Gs=on.extend({resourceTemplates:M($b)}),Js=Ae.extend({uri:g()}),Eb=Js,Tb=le.extend({method:k("resources/read"),params:Eb}),Ys=de.extend({contents:M(X([jp,Mp]))}),Qs=je.extend({method:k("notifications/resources/list_changed"),params:De.optional()}),Rb=Js,Pb=le.extend({method:k("resources/subscribe"),params:Rb}),zb=Js,Ob=le.extend({method:k("resources/unsubscribe"),params:zb}),Ib=De.extend({uri:g()}),Ab=je.extend({method:k("notifications/resources/updated"),params:Ib}),Nb=$({name:g(),description:oe(g()),required:oe(ue())}),Cb=$({...ur.shape,...rn.shape,description:oe(g()),arguments:oe(M(Nb)),_meta:oe($e({}))}),Db=nn.extend({method:k("prompts/list")}),Xs=on.extend({prompts:M(Cb)}),jb=Ae.extend({name:g(),arguments:J(g(),g()).optional()}),Mb=le.extend({method:k("prompts/get"),params:jb}),ea=$({type:k("text"),text:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),ta=$({type:k("image"),data:Hs,mimeType:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),ra=$({type:k("audio"),data:Hs,mimeType:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),Lb=$({type:k("tool_use"),name:g(),id:g(),input:J(g(),ne()),_meta:J(g(),ne()).optional()}),qb=$({type:k("resource"),resource:X([jp,Mp]),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),Bb=Lp.extend({type:k("resource_link")}),na=X([ea,ta,ra,Bb,qb]),Zb=$({role:cn,content:na}),oa=de.extend({description:g().optional(),messages:M(Zb)}),ia=je.extend({method:k("notifications/prompts/list_changed"),params:De.optional()}),Ub=$({title:g().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),Fb=$({taskSupport:Te(["required","optional","forbidden"]).optional()}),qp=$({...ur.shape,...rn.shape,description:g().optional(),inputSchema:$({type:k("object"),properties:J(g(),ce).optional(),required:M(g()).optional()}).catchall(ne()),outputSchema:$({type:k("object"),properties:J(g(),ce).optional(),required:M(g()).optional()}).catchall(ne()).optional(),annotations:Ub.optional(),execution:Fb.optional(),_meta:J(g(),ne()).optional()}),Vb=nn.extend({method:k("tools/list")}),sa=on.extend({tools:M(qp)}),vt=de.extend({content:M(na).default([]),structuredContent:J(g(),ne()).optional(),isError:ue().optional()}),pC=vt.or(de.extend({toolResult:ne()})),Kb=en.extend({name:g(),arguments:J(g(),ne()).optional()}),Hb=le.extend({method:k("tools/call"),params:Kb}),aa=je.extend({method:k("notifications/tools/list_changed"),params:De.optional()}),Bp=$({autoRefresh:ue().default(!0),debounceMs:V().int().nonnegative().default(300)}),Zp=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),Wb=Ae.extend({level:Zp}),Gb=le.extend({method:k("logging/setLevel"),params:Wb}),Jb=De.extend({level:Zp,logger:g().optional(),data:ne()}),Yb=je.extend({method:k("notifications/message"),params:Jb}),Qb=$({name:g().optional()}),Xb=$({hints:M(Qb).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),ex=$({mode:Te(["auto","required","none"]).optional()}),tx=$({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:M(na).default([]),structuredContent:$({}).loose().optional(),isError:ue().optional(),_meta:J(g(),ne()).optional()}),rx=Ms("type",[ea,ta,ra]),xo=Ms("type",[ea,ta,ra,Lb,tx]),nx=$({role:cn,content:X([xo,M(xo)]),_meta:J(g(),ne()).optional()}),ox=en.extend({messages:M(nx),modelPreferences:Xb.optional(),systemPrompt:g().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:M(g()).optional(),metadata:ce.optional(),tools:M(qp).optional(),toolChoice:ex.optional()}),ca=le.extend({method:k("sampling/createMessage"),params:ox}),ua=de.extend({model:g(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens"]).or(g())),role:cn,content:rx}),la=de.extend({model:g(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:cn,content:X([xo,M(xo)])}),ix=$({type:k("boolean"),title:g().optional(),description:g().optional(),default:ue().optional()}),sx=$({type:k("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:g().optional()}),ax=$({type:Te(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),cx=$({type:k("string"),title:g().optional(),description:g().optional(),enum:M(g()),default:g().optional()}),ux=$({type:k("string"),title:g().optional(),description:g().optional(),oneOf:M($({const:g(),title:g()})),default:g().optional()}),lx=$({type:k("string"),title:g().optional(),description:g().optional(),enum:M(g()),enumNames:M(g()).optional(),default:g().optional()}),dx=X([cx,ux]),fx=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:k("string"),enum:M(g())}),default:M(g()).optional()}),px=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:M($({const:g(),title:g()}))}),default:M(g()).optional()}),mx=X([fx,px]),hx=X([lx,dx,mx]),gx=X([hx,ix,sx,ax]),yx=en.extend({mode:k("form").optional(),message:g(),requestedSchema:$({type:k("object"),properties:J(g(),gx),required:M(g()).optional()})}),_x=en.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),wx=X([yx,_x]),da=le.extend({method:k("elicitation/create"),params:wx}),vx=De.extend({elicitationId:g()}),bx=je.extend({method:k("notifications/elicitation/complete"),params:vx}),fa=de.extend({action:Te(["accept","decline","cancel"]),content:Ls(e=>e===null?void 0:e,J(g(),X([g(),V(),ue(),M(g())])).optional())}),xx=$({type:k("ref/resource"),uri:g()});var $x=$({type:k("ref/prompt"),name:g()}),kx=Ae.extend({ref:X([$x,xx]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),Sx=le.extend({method:k("completion/complete"),params:kx});var pa=de.extend({completion:$e({values:M(g()).max(100),total:oe(V().int()),hasMore:oe(ue())})}),Ex=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),ne()).optional()}),Tx=le.extend({method:k("roots/list"),params:Ae.optional()}),Rx=de.extend({roots:M(Ex)}),Px=je.extend({method:k("notifications/roots/list_changed"),params:De.optional()}),mC=X([Eo,hb,Sx,Gb,Mb,Db,kb,Sb,Tb,Pb,Ob,Hb,Vb,Ro,zo,Oo,Ao]),hC=X([So,To,yb,Px,an]),gC=X([Mt,ua,la,fa,Rx,Po,Io,Lt]),yC=X([Eo,ca,da,Tx,Ro,zo,Oo,Ao]),_C=X([So,To,Yb,Ab,Qs,aa,ia,an,bx]),wC=X([Mt,Ks,pa,oa,Xs,Ws,Gs,Ys,vt,sa,Po,Io,Lt]),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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new qs(o.elicitations,r)}return new e(t,r,n)}},qs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function bt(e){return e==="completed"||e==="failed"||e==="cancelled"}var zx=Symbol("Let zodToJsonSchema decide on which parser to use");var QC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ma(e){let r=wo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=rp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ha(e,t){let r=Fe(e,t);if(!r.success)throw r.error;return r.data}var Dx=6e4,No=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(So,r=>{this._oncancel(r)}),this.setNotificationHandler(To,r=>{this._onprogress(r)}),this.setRequestHandler(Eo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ro,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.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(I.InvalidParams,`Task not found: ${i}`);if(!bt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(bt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[wt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Oo,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(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ao,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(bt(o.status))throw new T(I.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new T(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(I.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),T.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),tn(i)||Ip(i)?this._onresponse(i):Us(i)?this._onrequest(i,s):Op(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(I.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[wt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Rp(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(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),tn(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(tn(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),tn(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(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Lt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},bt(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(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[wt]:c}});let m=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let x=b instanceof T?b:new T(I.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=Fe(r,b.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??Dx,_=()=>m(T.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=x=>{let R=this._responseHandlers.get(f);R?R(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),u(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Po,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},Io,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Cp,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||{},[wt]: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||{},[wt]: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||{},[wt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ma(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ha(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=ma(t);this._notificationHandlers.set(n,o=>{let i=ha(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"&&Us(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new T(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(I.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=an.parse({method:"notifications/tasks/status",params:a});await this.notification(c),bt(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(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(bt(a.status))throw new T(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=an.parse({method:"notifications/tasks/status",params:c});await this.notification(l),bt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Up(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fp(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];Up(s)&&Up(i)?r[o]={...s,...i}:r[o]=i}return r}var Cg=Yi(tu(),1),Dg=Yi(Ng(),1);function LT(){let e=new Cg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Dg.default)(e),e}var hi=class{constructor(t){this._ajv=t??LT()}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 gi=class{constructor(t){this._client=t}async*callToolStream(t,r=vt,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(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new T(I.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(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function jg(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 Mg(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 yi(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&&yi(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&yi(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&yi(r,t)}}function qT(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 _i=class extends No{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 hi,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",aa,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ia,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Qs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new gi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fp(this._capabilities,t)}setRequestHandler(t,r){let o=wo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(cr(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=Fe(da,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=qT(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let b=Fe(Lt,m);if(!b.success){let x=b.error instanceof Error?b.error.message:String(b.error);throw new T(I.InvalidParams,`Invalid task creation result: ${x}`)}return b.data}let h=Fe(fa,m);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid elicitation result: ${b}`)}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{yi(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Fe(ca,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Fe(Lt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?la:ua,h=Fe(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Bs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ks,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sp.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){jg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Mg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mt,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}},Mt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},oa,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Xs,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ws,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Gs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Ys,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mt,r)}async callTool(t,r=vt,n){if(this.isToolTaskRequired(t.name))throw new T(I.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new T(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new T(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},sa,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=Bp.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 Ry=Yi(Ey(),1);import _u from"node:process";import{PassThrough as mR}from"node:stream";var vi=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),pR(r)}clear(){this._buffer=void 0}};function pR(e){return Ap.parse(JSON.parse(e))}function Ty(e){return JSON.stringify(e)+`
37
- `}var hR=_u.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function gR(){let e={};for(let t of hR){let r=_u.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var bi=class{constructor(t){this._readBuffer=new vi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new mR)}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,Ry.default)(this._serverParams.command,this._serverParams.args??[],{env:{...gR(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:_u.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=Ty(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var yR=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Yt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new bi({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??_R(),stderr:t.stderr??"pipe"}),n=new _i({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:vR(r).map(bR),nextCursor:Py(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!xi(n,["error"])&&kR(n,["ok","success"],!0),target:t,messageId:Je(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:xR(r).map($R).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=yR.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:wR(r)},vt);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 _R(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function wR(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function vR(e){if(Array.isArray(e))return e;if(!Or(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&Or(r)?[r]:[]}function bR(e){return Or(e)?{id:Je(e,["id","message_id","messageId"]),cursor:Py(e,["cursor"]),type:Je(e,["type","event_type","eventType"]),platform:Je(e,["platform"]),target:Je(e,["target"]),sessionKey:Je(e,["session_key","sessionKey"]),timestamp:Je(e,["timestamp","created_at","createdAt"]),message:Je(e,["message","text","content"]),raw:e}:{raw:e}}function xR(e){if(Array.isArray(e))return e;if(!Or(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function $R(e){if(!Or(e))return null;let t=Je(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Je(e,["platform"]),name:Je(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Je(e,t){let r=xi(e,t);return typeof r=="string"?r:void 0}function kR(e,t,r){let n=xi(e,t);return typeof n=="boolean"?n:r}function Py(e,t){let r=xi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function xi(e,t){if(Or(e))for(let r of t){let n=e[r];if(n!=null)return n}}function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as rI,writeFile as nI}from"node:fs/promises";import{join as W_}from"node:path";var $i=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function E(e,t){return new $i(e,t)}var ve=",";function wu(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 it(e){return E(e,"invalid quoted string")}function zt(e,t){if(e==="")return"";if(e.startsWith('"'))return zy(e,t);if(e.includes('"'))throw it(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:SR(e)?Number(e):e}function Qt(e,t){let r=e.trim();if(r.startsWith('"'))return[zy(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function zy(e,t){if(e[0]!=='"')throw it(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw it(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw it(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw it(t);r+=String.fromCharCode(a),n+=4;break}default:throw it(t)}continue}if(o<" "&&o!==" ")throw it(t);r+=o}throw it(t)}function Ln(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw it(r);return n.push(e.slice(o).trim()),n}function Ie(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw it(r);return-1}function SR(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ER(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function TR(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw E(0,"number is not representable in TOON");return String(e)}function ki(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function Ot(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return TR(e);if(typeof e=="string")return PR(e,t);throw E(0,"not a primitive")}function RR(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function st(e){return RR(e)?e:Oy(e)}function PR(e,t){return zR(e,t)?Oy(e):e}function zR(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||ER(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function Oy(e){let t='"';for(let r of e)switch(r){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
41
- `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:r<" "?t+=`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=r}return`${t}"`}function qn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Eu=2;function OR(e={}){return{indent:Math.max(1,e.indent??Eu),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function IR(e,t){let r=[],n=!1;return wu(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 E(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw E(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function pt(e,t){let r=OR(t),n=IR(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw E(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=Pu(o.content,Ie(o.content,":",o.number))}catch(u){if(r.strict)throw ku(u,o.number);l=void 0}if(l!==void 0)return CR(l,n,r)}if(i&&Ie(o.content,":",o.number)===-1)return zt(o.content.trim(),o.number);let s={index:0},a=Tu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function Tu(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 E(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=AR(e,t,r,n);Ny(o,s,a,c,n,i.number)}return o}function AR(e,t,r,n){let o=e[t.index],i=o.content,s=Ie(i,":",o.number);if(s===-1)throw E(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=Ie(a,"[",o.number),u=Ie(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=LR(a)}catch(_){if(n.strict)throw ku(_,o.number);t.index+=1;let w=vu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw E(o.number,"expected keyed map rows");let h=NR(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=Pu(a,s)}catch(_){if(n.strict)throw ku(_,o.number);t.index+=1;let w=vu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw E(o.number,"expected non-empty field name");let h=Ru(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Qt(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=vu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function vu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return zt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?Tu(e,t,r+1,i):{}}function NR(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 E(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw E(s.number,"blank line inside keyed map");let a=Ie(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Qt(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Ln(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw E(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{Bn(d,f,zt(u[p],s.number),o,s.number)}),Ny(i,c,l,d,o,s.number),r.index+=1}return i}function CR(e,t,r){let n=t[0],o=Ie(n.content,":",n.number);if(o===-1)throw E(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=Ru(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function Ru(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 E(s,"expected tabular rows");return DR(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Ln(a,e.delimiter,s).map(l=>zt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return jR(e,r,n,o+1,i)}function DR(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw xu(r,n.index);if(c.depth<o)break;if(c.depth>o)throw E(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw E(c.number,"blank line inside array");if(!Iy(c.content,e.delimiter,c.number))break;let l=Ln(c.content,e.delimiter,c.number);if(l.length!==t.length)throw E(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{Bn(u,d,zt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw xu(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Iy(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function Iy(e,t,r){let n=Ie(e,":",r);if(n===-1)return!0;let o=Ie(e,t,r);return o===-1?!1:o<n}function jR(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 xu(t,r.index);if(a.depth>n)throw E(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw E(a.number,"blank line inside array");i.push(MR(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw E(s.number,"array length mismatch");return i}function MR(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw E(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=Ie(i,":",o.number),a;try{a=Pu(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return Ru(a,c,e,t,r,n)}}if(Ie(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 Tu(s,{index:0},r+1,n)}return t.index+=1,zt(i,o.number)}function xu(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function Pu(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=Ie(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Qt(r.slice(0,n),0)}catch{throw E(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw E(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 E(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 E(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{p=Ay(f.slice(1,-1),d)}catch(m){throw E(0,m.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw E(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function LR(e){let t=Ie(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Qt(e.slice(0,t),0)}catch{throw E(0,"invalid keyed map header")}if(r===""&&!n)throw E(0,"expected non-empty field name");let o;try{o=Ay(e.slice(t+1,-1),ve)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:ve,fields:o}}function Ay(e,t){let r=[],n=0;function o(a,c){let l=0;for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw E(0,"invalid array header");let u=n;for(;n<e.length;){let f=e[n];if(f==='"'){i();continue}if(f===t||f==="{"||f==="}")break;n+=1}let[d]=Qt(e.slice(u,n),0);if(d==="")throw E(0,"invalid array header");if(l+=1,e[n]==="{"){n+=1;let f=r.length;if(o([...a,d],!0),e[n]!=="}"||r.length===f)throw E(0,"invalid array header");n+=1}else r.push([...a,d]);if(e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw E(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw E(0,"invalid array header")}if(l===0)throw E(0,"invalid array header")}function i(){for(n+=1;n<e.length;){let a=e[n];if(n+=1,a==="\\")n+=1;else if(a==='"')return}}if(o([],!1),n!==e.length)throw E(0,"invalid array header");let s=new Set;for(let a=0;a<r.length;a+=1)for(let c=a+1;c<r.length;c+=1)if(qR(r[a],r[c])||$u(r[a],r[c])||$u(r[c],r[a]))throw E(0,"duplicate key");for(let a of r){let c=a.join("\0");if(s.has(c))throw E(0,"duplicate key");s.add(c)}return r}function qR(e,t){return e.length===t.length&&$u(e,t)}function $u(e,t){return t.every((r,n)=>e[n]===r)}function ku(e,t){return E(t,e.reason??String(e.message))}function Ny(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(BR)){Bn(e,s,n,o,i);return}}Bn(e,[t],n,o,i)}function Bn(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw E(o,"duplicate key");qn(e,i,r);return}if(s&&!Ir(e[i])){if(n.strict)throw E(o,"path expansion conflict");qn(e,i,{})}else s||qn(e,i,{});Bn(e[i],t.slice(1),r,n,o)}function BR(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mt(e,t={}){let r={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},n=[];return Array.isArray(e)?zu(n,void 0,e,0,!1,r):Ir(e)?Cy(n,e,0,r):n.push(Ot(e,ve)),n.join("")}function Zn(e,t){e.push(" ".repeat(t*Eu))}function Cy(e,t,r,n){for(let[o,i]of Object.entries(t))Zn(e,r),Su(e,o,i,r,n)}function Su(e,t,r,n,o){if(Array.isArray(r)){zu(e,t,r,n,!1,o);return}if(Ir(r)){let i=o.keyedMapCollapse?UR(r,o):void 0;if(i!==void 0){e.push(st(t),"{",i.fields.map(Ou).join(ve),`}:
42
- `);for(let[s,a]of Object.entries(r))Zn(e,n+1),e.push(st(s),": ",i.paths.map(c=>Ot(Ly(a,c),ve)).join(ve),`
43
- `);return}e.push(st(t),`:
44
- `),Cy(e,r,n+1,o);return}e.push(st(t),": ",Ot(r,ve),`
45
- `)}function zu(e,t,r,n,o,i){if(r.length===0){t!==void 0?e.push(st(t),`: []
35
+ })));`),f.write(`newResult[${Ct(b)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,x)=>w(d,b,x)},o,i=ir,s=!oo.jitless,c=s&&os.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 x=u.shape;for(let R of u.keys){let O=x[R],xe=O._zod.run({value:p[R],issues:[]},f),Ne=O._zod.optin==="optional"&&O._zod.optout==="optional";xe instanceof Promise?m.push(xe.then(nr=>Ne?vd(nr,d,R,p):fo(nr,d,R))):Ne?vd(xe,d,R,p):fo(xe,d,R)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,b=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(b==="never"){h.push(x);continue}let R=w.run({value:p[x],issues:[]},f);R instanceof Promise?m.push(R.then(O=>fo(O,d,x))):fo(R,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function bd(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=>Ue(i,n,Ce())))}),t}var ws=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=>Fr(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=>bd(s,r,e,n)):bd(i,r,e,n)}}),sf=y("$ZodDiscriminatedUnion",(e,t)=>{ws.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=Zr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!ir(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)}}),af=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])=>xd(r,c,l)):xd(r,i,s)}});function ys(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(sr(e)&&sr(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=ys(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=ys(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 xd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Dt(e))return e;let n=ys(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 cf=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!sr(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(...tt(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...tt(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=>Ue(l,n,Ce())),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(...tt(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...tt(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var uf=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=es(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>is.has(typeof n)).map(n=>typeof n=="string"?_t(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}}),lf=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"?_t(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 df=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 ut;return r.value=o,r}}),ff=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(`^(${Fr(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)}),pf=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(`^(${Fr(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)}),mf=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=>$d(i,t)):$d(o,t)}});function $d(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var hf=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))}),gf=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=>kd(i,e)):kd(o,e)}});function kd(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 yf=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=>Ue(s,n,Ce()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ue(i,n,Ce()))},input:r.value}),r.issues=[]),r)}});var _f=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=>Sd(i,t,n)):Sd(o,t,n)}});function Sd(e,t,r){return Dt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var wf=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(Ed):Ed(o)}});function Ed(e){return e.value=Object.freeze(e.value),e}var vf=y("$ZodCustom",(e,t)=>{ge.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=>Td(i,r,n,e));Td(o,r,n,e)}});function Td(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(cs(o))}}var gv=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},yv=()=>{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 ${gv(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ao(n.values[0])}`:`Invalid option: expected one of ${io(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":""}: ${io(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 bf(){return{localeError:yv()}}var JA=Symbol("ZodOutput"),YA=Symbol("ZodInput"),vs=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 _v(){return new vs}var Wr=_v();function xf(e,t){return new e({type:"string",...P(t)})}function $f(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function bs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function kf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function Sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function Tf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Rf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function Pf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function zf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Of(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function If(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function Af(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function Nf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Cf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function Df(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function jf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Mf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Lf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function qf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function Bf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function Zf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function Uf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function Ff(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Vf(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function Kf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function Hf(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Wf(e,t){return new e({type:"number",checks:[],...P(t)})}function Gf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Jf(e,t){return new e({type:"boolean",...P(t)})}function Yf(e,t){return new e({type:"null",...P(t)})}function Qf(e){return new e({type:"unknown"})}function Xf(e,t){return new e({type:"never",...P(t)})}function mo(e,t){return new hs({check:"less_than",...P(t),value:e,inclusive:!1})}function Gr(e,t){return new hs({check:"less_than",...P(t),value:e,inclusive:!0})}function ho(e,t){return new gs({check:"greater_than",...P(t),value:e,inclusive:!1})}function Jr(e,t){return new gs({check:"greater_than",...P(t),value:e,inclusive:!0})}function go(e,t){return new id({check:"multiple_of",...P(t),value:e})}function yo(e,t){return new ad({check:"max_length",...P(t),maximum:e})}function ar(e,t){return new cd({check:"min_length",...P(t),minimum:e})}function _o(e,t){return new ud({check:"length_equals",...P(t),length:e})}function xs(e,t){return new ld({check:"string_format",format:"regex",...P(t),pattern:e})}function $s(e){return new dd({check:"string_format",format:"lowercase",...P(e)})}function ks(e){return new fd({check:"string_format",format:"uppercase",...P(e)})}function Ss(e,t){return new pd({check:"string_format",format:"includes",...P(t),includes:e})}function Es(e,t){return new md({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Ts(e,t){return new hd({check:"string_format",format:"ends_with",...P(t),suffix:e})}function jt(e){return new gd({check:"overwrite",tx:e})}function Rs(e){return jt(t=>t.normalize(e))}function Ps(){return jt(e=>e.trim())}function zs(){return jt(e=>e.toLowerCase())}function Os(){return jt(e=>e.toUpperCase())}function ep(e,t,r){return new e({type:"array",element:t,...P(r)})}function tp(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function rp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function cr(e){return!!e._zod}function Fe(e,t){return cr(e)?Kr(e,t):e.safeParse(t)}function wo(e){if(!e)return;let t;if(cr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function np(e){if(cr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var Qr={};_l(Qr,{ZodISODate:()=>ip,ZodISODateTime:()=>op,ZodISODuration:()=>ap,ZodISOTime:()=>sp,date:()=>As,datetime:()=>Is,duration:()=>Cs,time:()=>Ns});var op=y("ZodISODateTime",(e,t)=>{Ld.init(e,t),re.init(e,t)});function Is(e){return Ff(op,e)}var ip=y("ZodISODate",(e,t)=>{qd.init(e,t),re.init(e,t)});function As(e){return Vf(ip,e)}var sp=y("ZodISOTime",(e,t)=>{Bd.init(e,t),re.init(e,t)});function Ns(e){return Kf(sp,e)}var ap=y("ZodISODuration",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Cs(e){return Hf(ap,e)}var cp=(e,t)=>{co.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>El(e,r)},flatten:{value:r=>Sl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},ON=y("ZodError",cp),Xr=y("ZodError",cp,{Parent:Error});var up=Tl(Xr),lp=Rl(Xr),dp=ls(Xr),fp=ds(Xr);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)=>et(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>up(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>dp(e,r,n),e.parseAsync=async(r,n)=>lp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>fp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(hb(r,n)),e.superRefine=r=>e.check(gb(r)),e.overwrite=r=>e.check(jt(r)),e.optional=()=>oe(e),e.nullable=()=>hp(e),e.nullish=()=>oe(hp(e)),e.nonoptional=r=>cb(e,r),e.array=()=>M(e),e.or=r=>X([e,r]),e.and=r=>bo(e,r),e.transform=r=>js(e,bp(r)),e.default=r=>ib(e,r),e.prefault=r=>ab(e,r),e.catch=r=>lb(e,r),e.pipe=r=>js(e,r),e.readonly=()=>pb(e),e.describe=r=>{let n=e.clone();return Wr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Wr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Wr.get(e);let n=e.clone();return Wr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),gp=y("_ZodString",(e,t)=>{po.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(xs(...n)),e.includes=(...n)=>e.check(Ss(...n)),e.startsWith=(...n)=>e.check(Es(...n)),e.endsWith=(...n)=>e.check(Ts(...n)),e.min=(...n)=>e.check(ar(...n)),e.max=(...n)=>e.check(yo(...n)),e.length=(...n)=>e.check(_o(...n)),e.nonempty=(...n)=>e.check(ar(1,...n)),e.lowercase=n=>e.check($s(n)),e.uppercase=n=>e.check(ks(n)),e.trim=()=>e.check(Ps()),e.normalize=(...n)=>e.check(Rs(...n)),e.toLowerCase=()=>e.check(zs()),e.toUpperCase=()=>e.check(Os())}),Tv=y("ZodString",(e,t)=>{po.init(e,t),gp.init(e,t),e.email=r=>e.check($f(Rv,r)),e.url=r=>e.check(Rf(Pv,r)),e.jwt=r=>e.check(Uf(Fv,r)),e.emoji=r=>e.check(Pf(zv,r)),e.guid=r=>e.check(bs(pp,r)),e.uuid=r=>e.check(kf(vo,r)),e.uuidv4=r=>e.check(Sf(vo,r)),e.uuidv6=r=>e.check(Ef(vo,r)),e.uuidv7=r=>e.check(Tf(vo,r)),e.nanoid=r=>e.check(zf(Ov,r)),e.guid=r=>e.check(bs(pp,r)),e.cuid=r=>e.check(Of(Iv,r)),e.cuid2=r=>e.check(If(Av,r)),e.ulid=r=>e.check(Af(Nv,r)),e.base64=r=>e.check(qf(Bv,r)),e.base64url=r=>e.check(Bf(Zv,r)),e.xid=r=>e.check(Nf(Cv,r)),e.ksuid=r=>e.check(Cf(Dv,r)),e.ipv4=r=>e.check(Df(jv,r)),e.ipv6=r=>e.check(jf(Mv,r)),e.cidrv4=r=>e.check(Mf(Lv,r)),e.cidrv6=r=>e.check(Lf(qv,r)),e.e164=r=>e.check(Zf(Uv,r)),e.datetime=r=>e.check(Is(r)),e.date=r=>e.check(As(r)),e.time=r=>e.check(Ns(r)),e.duration=r=>e.check(Cs(r))});function g(e){return xf(Tv,e)}var re=y("ZodStringFormat",(e,t)=>{Q.init(e,t),gp.init(e,t)}),Rv=y("ZodEmail",(e,t)=>{zd.init(e,t),re.init(e,t)});var pp=y("ZodGUID",(e,t)=>{Rd.init(e,t),re.init(e,t)});var vo=y("ZodUUID",(e,t)=>{Pd.init(e,t),re.init(e,t)});var Pv=y("ZodURL",(e,t)=>{Od.init(e,t),re.init(e,t)});var zv=y("ZodEmoji",(e,t)=>{Id.init(e,t),re.init(e,t)});var Ov=y("ZodNanoID",(e,t)=>{Ad.init(e,t),re.init(e,t)});var Iv=y("ZodCUID",(e,t)=>{Nd.init(e,t),re.init(e,t)});var Av=y("ZodCUID2",(e,t)=>{Cd.init(e,t),re.init(e,t)});var Nv=y("ZodULID",(e,t)=>{Dd.init(e,t),re.init(e,t)});var Cv=y("ZodXID",(e,t)=>{jd.init(e,t),re.init(e,t)});var Dv=y("ZodKSUID",(e,t)=>{Md.init(e,t),re.init(e,t)});var jv=y("ZodIPv4",(e,t)=>{Ud.init(e,t),re.init(e,t)});var Mv=y("ZodIPv6",(e,t)=>{Fd.init(e,t),re.init(e,t)});var Lv=y("ZodCIDRv4",(e,t)=>{Vd.init(e,t),re.init(e,t)});var qv=y("ZodCIDRv6",(e,t)=>{Kd.init(e,t),re.init(e,t)});var Bv=y("ZodBase64",(e,t)=>{Wd.init(e,t),re.init(e,t)});var Zv=y("ZodBase64URL",(e,t)=>{Gd.init(e,t),re.init(e,t)});var Uv=y("ZodE164",(e,t)=>{Jd.init(e,t),re.init(e,t)});var Fv=y("ZodJWT",(e,t)=>{Yd.init(e,t),re.init(e,t)});var yp=y("ZodNumber",(e,t)=>{_s.init(e,t),ie.init(e,t),e.gt=(n,o)=>e.check(ho(n,o)),e.gte=(n,o)=>e.check(Jr(n,o)),e.min=(n,o)=>e.check(Jr(n,o)),e.lt=(n,o)=>e.check(mo(n,o)),e.lte=(n,o)=>e.check(Gr(n,o)),e.max=(n,o)=>e.check(Gr(n,o)),e.int=n=>e.check(mp(n)),e.safe=n=>e.check(mp(n)),e.positive=n=>e.check(ho(0,n)),e.nonnegative=n=>e.check(Jr(0,n)),e.negative=n=>e.check(mo(0,n)),e.nonpositive=n=>e.check(Gr(0,n)),e.multipleOf=(n,o)=>e.check(go(n,o)),e.step=(n,o)=>e.check(go(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 Wf(yp,e)}var Vv=y("ZodNumberFormat",(e,t)=>{Qd.init(e,t),yp.init(e,t)});function mp(e){return Gf(Vv,e)}var Kv=y("ZodBoolean",(e,t)=>{Xd.init(e,t),ie.init(e,t)});function ue(e){return Jf(Kv,e)}var Hv=y("ZodNull",(e,t)=>{ef.init(e,t),ie.init(e,t)});function _p(e){return Yf(Hv,e)}var Wv=y("ZodUnknown",(e,t)=>{tf.init(e,t),ie.init(e,t)});function ne(){return Qf(Wv)}var Gv=y("ZodNever",(e,t)=>{rf.init(e,t),ie.init(e,t)});function Jv(e){return Xf(Gv,e)}var Yv=y("ZodArray",(e,t)=>{nf.init(e,t),ie.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ar(r,n)),e.nonempty=r=>e.check(ar(1,r)),e.max=(r,n)=>e.check(yo(r,n)),e.length=(r,n)=>e.check(_o(r,n)),e.unwrap=()=>e.element});function M(e,t){return ep(Yv,e,t)}var wp=y("ZodObject",(e,t)=>{of.init(e,t),ie.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Te(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:Jv()}),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(xp,e,r[0]),e.required=(...r)=>U.required($p,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 wp(r)}function $e(e,t){return new wp({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:ne(),...U.normalizeParams(t)})}var vp=y("ZodUnion",(e,t)=>{ws.init(e,t),ie.init(e,t),e.options=t.options});function X(e,t){return new vp({type:"union",options:e,...U.normalizeParams(t)})}var Qv=y("ZodDiscriminatedUnion",(e,t)=>{vp.init(e,t),sf.init(e,t)});function Ms(e,t,r){return new Qv({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Xv=y("ZodIntersection",(e,t)=>{af.init(e,t),ie.init(e,t)});function bo(e,t){return new Xv({type:"intersection",left:e,right:t})}var eb=y("ZodRecord",(e,t)=>{cf.init(e,t),ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new eb({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var Ds=y("ZodEnum",(e,t)=>{uf.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 Ds({...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 Ds({...t,checks:[],...U.normalizeParams(o),entries:i})}});function Te(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ds({type:"enum",entries:r,...U.normalizeParams(t)})}var tb=y("ZodLiteral",(e,t)=>{lf.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 k(e,t){return new tb({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var rb=y("ZodTransform",(e,t)=>{df.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 bp(e){return new rb({type:"transform",transform:e})}var xp=y("ZodOptional",(e,t)=>{ff.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function oe(e){return new xp({type:"optional",innerType:e})}var nb=y("ZodNullable",(e,t)=>{pf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hp(e){return new nb({type:"nullable",innerType:e})}var ob=y("ZodDefault",(e,t)=>{mf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ib(e,t){return new ob({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var sb=y("ZodPrefault",(e,t)=>{hf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ab(e,t){return new sb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var $p=y("ZodNonOptional",(e,t)=>{gf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cb(e,t){return new $p({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var ub=y("ZodCatch",(e,t)=>{yf.init(e,t),ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function lb(e,t){return new ub({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var db=y("ZodPipe",(e,t)=>{_f.init(e,t),ie.init(e,t),e.in=t.in,e.out=t.out});function js(e,t){return new db({type:"pipe",in:e,out:t})}var fb=y("ZodReadonly",(e,t)=>{wf.init(e,t),ie.init(e,t)});function pb(e){return new fb({type:"readonly",innerType:e})}var kp=y("ZodCustom",(e,t)=>{vf.init(e,t),ie.init(e,t)});function mb(e){let t=new ge({check:"custom"});return t._zod.check=e,t}function Sp(e,t){return tp(kp,e??(()=>!0),t)}function hb(e,t={}){return rp(kp,e,t)}function gb(e){let t=mb(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 Ls(e,t){return js(bp(e),t)}Ce(bf());var Bs="2025-11-25";var Ep=[Bs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],wt="io.modelcontextprotocol/related-task",$o="2.0",ce=Sp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Tp=X([g(),V().int()]),Rp=g(),kC=$e({ttl:V().optional(),pollInterval:V().optional()}),yb=$({ttl:V().optional()}),_b=$({taskId:g()}),Zs=$e({progressToken:Tp.optional(),[wt]:_b.optional()}),Ae=$({_meta:Zs.optional()}),en=Ae.extend({task:yb.optional()}),Pp=e=>en.safeParse(e).success,le=$({method:g(),params:Ae.loose().optional()}),De=$({_meta:Zs.optional()}),je=$({method:g(),params:De.loose().optional()}),de=$e({_meta:Zs.optional()}),ko=X([g(),V().int()]),zp=$({jsonrpc:k($o),id:ko,...le.shape}).strict(),Us=e=>zp.safeParse(e).success,Op=$({jsonrpc:k($o),...je.shape}).strict(),Ip=e=>Op.safeParse(e).success,Fs=$({jsonrpc:k($o),id:ko,result:de}).strict(),tn=e=>Fs.safeParse(e).success;var I;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(I||(I={}));var Vs=$({jsonrpc:k($o),id:ko.optional(),error:$({code:V().int(),message:g(),data:ne().optional()})}).strict();var Ap=e=>Vs.safeParse(e).success;var Np=X([zp,Op,Fs,Vs]),SC=X([Fs,Vs]),Mt=de.strict(),wb=De.extend({requestId:ko.optional(),reason:g().optional()}),So=je.extend({method:k("notifications/cancelled"),params:wb}),vb=$({src:g(),mimeType:g().optional(),sizes:M(g()).optional(),theme:Te(["light","dark"]).optional()}),rn=$({icons:M(vb).optional()}),ur=$({name:g(),title:g().optional()}),Cp=ur.extend({...ur.shape,...rn.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),bb=bo($({applyDefaults:ue().optional()}),J(g(),ne())),xb=Ls(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,bo($({form:bb.optional(),url:ce.optional()}),J(g(),ne()).optional())),$b=$e({list:ce.optional(),cancel:ce.optional(),requests:$e({sampling:$e({createMessage:ce.optional()}).optional(),elicitation:$e({create:ce.optional()}).optional()}).optional()}),kb=$e({list:ce.optional(),cancel:ce.optional(),requests:$e({tools:$e({call:ce.optional()}).optional()}).optional()}),Sb=$({experimental:J(g(),ce).optional(),sampling:$({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:xb.optional(),roots:$({listChanged:ue().optional()}).optional(),tasks:$b.optional(),extensions:J(g(),ce).optional()}),Eb=Ae.extend({protocolVersion:g(),capabilities:Sb,clientInfo:Cp}),Tb=le.extend({method:k("initialize"),params:Eb});var Rb=$({experimental:J(g(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:$({listChanged:ue().optional()}).optional(),resources:$({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:$({listChanged:ue().optional()}).optional(),tasks:kb.optional(),extensions:J(g(),ce).optional()}),Ks=de.extend({protocolVersion:g(),capabilities:Rb,serverInfo:Cp,instructions:g().optional()}),Pb=je.extend({method:k("notifications/initialized"),params:De.optional()});var Eo=le.extend({method:k("ping"),params:Ae.optional()}),zb=$({progress:V(),total:oe(V()),message:oe(g())}),Ob=$({...De.shape,...zb.shape,progressToken:Tp}),To=je.extend({method:k("notifications/progress"),params:Ob}),Ib=Ae.extend({cursor:Rp.optional()}),nn=le.extend({params:Ib.optional()}),on=de.extend({nextCursor:Rp.optional()}),Ab=Te(["working","input_required","completed","failed","cancelled"]),sn=$({taskId:g(),status:Ab,ttl:X([V(),_p()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:oe(V()),statusMessage:oe(g())}),Lt=de.extend({task:sn}),Nb=De.merge(sn),an=je.extend({method:k("notifications/tasks/status"),params:Nb}),Ro=le.extend({method:k("tasks/get"),params:Ae.extend({taskId:g()})}),Po=de.merge(sn),zo=le.extend({method:k("tasks/result"),params:Ae.extend({taskId:g()})}),EC=de.loose(),Oo=nn.extend({method:k("tasks/list")}),Io=on.extend({tasks:M(sn)}),Ao=le.extend({method:k("tasks/cancel"),params:Ae.extend({taskId:g()})}),Dp=de.merge(sn),jp=$({uri:g(),mimeType:oe(g()),_meta:J(g(),ne()).optional()}),Mp=jp.extend({text:g()}),Hs=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Lp=jp.extend({blob:Hs}),cn=Te(["user","assistant"]),lr=$({audience:M(cn).optional(),priority:V().min(0).max(1).optional(),lastModified:Qr.datetime({offset:!0}).optional()}),qp=$({...ur.shape,...rn.shape,uri:g(),description:oe(g()),mimeType:oe(g()),size:oe(V()),annotations:lr.optional(),_meta:oe($e({}))}),Cb=$({...ur.shape,...rn.shape,uriTemplate:g(),description:oe(g()),mimeType:oe(g()),annotations:lr.optional(),_meta:oe($e({}))}),Db=nn.extend({method:k("resources/list")}),Ws=on.extend({resources:M(qp)}),jb=nn.extend({method:k("resources/templates/list")}),Gs=on.extend({resourceTemplates:M(Cb)}),Js=Ae.extend({uri:g()}),Mb=Js,Lb=le.extend({method:k("resources/read"),params:Mb}),Ys=de.extend({contents:M(X([Mp,Lp]))}),Qs=je.extend({method:k("notifications/resources/list_changed"),params:De.optional()}),qb=Js,Bb=le.extend({method:k("resources/subscribe"),params:qb}),Zb=Js,Ub=le.extend({method:k("resources/unsubscribe"),params:Zb}),Fb=De.extend({uri:g()}),Vb=je.extend({method:k("notifications/resources/updated"),params:Fb}),Kb=$({name:g(),description:oe(g()),required:oe(ue())}),Hb=$({...ur.shape,...rn.shape,description:oe(g()),arguments:oe(M(Kb)),_meta:oe($e({}))}),Wb=nn.extend({method:k("prompts/list")}),Xs=on.extend({prompts:M(Hb)}),Gb=Ae.extend({name:g(),arguments:J(g(),g()).optional()}),Jb=le.extend({method:k("prompts/get"),params:Gb}),ea=$({type:k("text"),text:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),ta=$({type:k("image"),data:Hs,mimeType:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),ra=$({type:k("audio"),data:Hs,mimeType:g(),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),Yb=$({type:k("tool_use"),name:g(),id:g(),input:J(g(),ne()),_meta:J(g(),ne()).optional()}),Qb=$({type:k("resource"),resource:X([Mp,Lp]),annotations:lr.optional(),_meta:J(g(),ne()).optional()}),Xb=qp.extend({type:k("resource_link")}),na=X([ea,ta,ra,Xb,Qb]),ex=$({role:cn,content:na}),oa=de.extend({description:g().optional(),messages:M(ex)}),ia=je.extend({method:k("notifications/prompts/list_changed"),params:De.optional()}),tx=$({title:g().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),rx=$({taskSupport:Te(["required","optional","forbidden"]).optional()}),Bp=$({...ur.shape,...rn.shape,description:g().optional(),inputSchema:$({type:k("object"),properties:J(g(),ce).optional(),required:M(g()).optional()}).catchall(ne()),outputSchema:$({type:k("object"),properties:J(g(),ce).optional(),required:M(g()).optional()}).catchall(ne()).optional(),annotations:tx.optional(),execution:rx.optional(),_meta:J(g(),ne()).optional()}),nx=nn.extend({method:k("tools/list")}),sa=on.extend({tools:M(Bp)}),vt=de.extend({content:M(na).default([]),structuredContent:J(g(),ne()).optional(),isError:ue().optional()}),TC=vt.or(de.extend({toolResult:ne()})),ox=en.extend({name:g(),arguments:J(g(),ne()).optional()}),ix=le.extend({method:k("tools/call"),params:ox}),aa=je.extend({method:k("notifications/tools/list_changed"),params:De.optional()}),Zp=$({autoRefresh:ue().default(!0),debounceMs:V().int().nonnegative().default(300)}),Up=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),sx=Ae.extend({level:Up}),ax=le.extend({method:k("logging/setLevel"),params:sx}),cx=De.extend({level:Up,logger:g().optional(),data:ne()}),ux=je.extend({method:k("notifications/message"),params:cx}),lx=$({name:g().optional()}),dx=$({hints:M(lx).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),fx=$({mode:Te(["auto","required","none"]).optional()}),px=$({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:M(na).default([]),structuredContent:$({}).loose().optional(),isError:ue().optional(),_meta:J(g(),ne()).optional()}),mx=Ms("type",[ea,ta,ra]),xo=Ms("type",[ea,ta,ra,Yb,px]),hx=$({role:cn,content:X([xo,M(xo)]),_meta:J(g(),ne()).optional()}),gx=en.extend({messages:M(hx),modelPreferences:dx.optional(),systemPrompt:g().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:M(g()).optional(),metadata:ce.optional(),tools:M(Bp).optional(),toolChoice:fx.optional()}),ca=le.extend({method:k("sampling/createMessage"),params:gx}),ua=de.extend({model:g(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens"]).or(g())),role:cn,content:mx}),la=de.extend({model:g(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:cn,content:X([xo,M(xo)])}),yx=$({type:k("boolean"),title:g().optional(),description:g().optional(),default:ue().optional()}),_x=$({type:k("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:g().optional()}),wx=$({type:Te(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),vx=$({type:k("string"),title:g().optional(),description:g().optional(),enum:M(g()),default:g().optional()}),bx=$({type:k("string"),title:g().optional(),description:g().optional(),oneOf:M($({const:g(),title:g()})),default:g().optional()}),xx=$({type:k("string"),title:g().optional(),description:g().optional(),enum:M(g()),enumNames:M(g()).optional(),default:g().optional()}),$x=X([vx,bx]),kx=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:k("string"),enum:M(g())}),default:M(g()).optional()}),Sx=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:M($({const:g(),title:g()}))}),default:M(g()).optional()}),Ex=X([kx,Sx]),Tx=X([xx,$x,Ex]),Rx=X([Tx,yx,_x,wx]),Px=en.extend({mode:k("form").optional(),message:g(),requestedSchema:$({type:k("object"),properties:J(g(),Rx),required:M(g()).optional()})}),zx=en.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),Ox=X([Px,zx]),da=le.extend({method:k("elicitation/create"),params:Ox}),Ix=De.extend({elicitationId:g()}),Ax=je.extend({method:k("notifications/elicitation/complete"),params:Ix}),fa=de.extend({action:Te(["accept","decline","cancel"]),content:Ls(e=>e===null?void 0:e,J(g(),X([g(),V(),ue(),M(g())])).optional())}),Nx=$({type:k("ref/resource"),uri:g()});var Cx=$({type:k("ref/prompt"),name:g()}),Dx=Ae.extend({ref:X([Cx,Nx]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),jx=le.extend({method:k("completion/complete"),params:Dx});var pa=de.extend({completion:$e({values:M(g()).max(100),total:oe(V().int()),hasMore:oe(ue())})}),Mx=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),ne()).optional()}),Lx=le.extend({method:k("roots/list"),params:Ae.optional()}),qx=de.extend({roots:M(Mx)}),Bx=je.extend({method:k("notifications/roots/list_changed"),params:De.optional()}),RC=X([Eo,Tb,jx,ax,Jb,Wb,Db,jb,Lb,Bb,Ub,ix,nx,Ro,zo,Oo,Ao]),PC=X([So,To,Pb,Bx,an]),zC=X([Mt,ua,la,fa,qx,Po,Io,Lt]),OC=X([Eo,ca,da,Lx,Ro,zo,Oo,Ao]),IC=X([So,To,ux,Vb,Qs,aa,ia,an,Ax]),AC=X([Mt,Ks,pa,oa,Xs,Ws,Gs,Ys,vt,sa,Po,Io,Lt]),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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new qs(o.elicitations,r)}return new e(t,r,n)}},qs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function bt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Zx=Symbol("Let zodToJsonSchema decide on which parser to use");var f1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ma(e){let r=wo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=np(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ha(e,t){let r=Fe(e,t);if(!r.success)throw r.error;return r.data}var Wx=6e4,No=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(So,r=>{this._oncancel(r)}),this.setNotificationHandler(To,r=>{this._onprogress(r)}),this.setRequestHandler(Eo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ro,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.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(I.InvalidParams,`Task not found: ${i}`);if(!bt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(bt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[wt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Oo,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(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ao,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(bt(o.status))throw new T(I.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new T(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(I.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),T.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),tn(i)||Ap(i)?this._onresponse(i):Us(i)?this._onrequest(i,s):Ip(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(I.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[wt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Pp(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(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),tn(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(tn(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),tn(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(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Lt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},bt(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(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[wt]:c}});let m=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let x=b instanceof T?b:new T(I.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=Fe(r,b.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??Wx,_=()=>m(T.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=x=>{let R=this._responseHandlers.get(f);R?R(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),u(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Po,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},Io,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Dp,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||{},[wt]: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||{},[wt]: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||{},[wt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ma(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ha(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=ma(t);this._notificationHandlers.set(n,o=>{let i=ha(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"&&Us(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new T(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(I.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=an.parse({method:"notifications/tasks/status",params:a});await this.notification(c),bt(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(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(bt(a.status))throw new T(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=an.parse({method:"notifications/tasks/status",params:c});await this.notification(l),bt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Fp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vp(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];Fp(s)&&Fp(i)?r[o]={...s,...i}:r[o]=i}return r}var Dg=Yi(tu(),1),jg=Yi(Cg(),1);function YT(){let e=new Dg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,jg.default)(e),e}var hi=class{constructor(t){this._ajv=t??YT()}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 gi=class{constructor(t){this._client=t}async*callToolStream(t,r=vt,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(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new T(I.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(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Mg(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 Lg(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 yi(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&&yi(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&yi(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&yi(r,t)}}function QT(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 _i=class extends No{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 hi,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",aa,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ia,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Qs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new gi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vp(this._capabilities,t)}setRequestHandler(t,r){let o=wo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(cr(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=Fe(da,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=QT(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let b=Fe(Lt,m);if(!b.success){let x=b.error instanceof Error?b.error.message:String(b.error);throw new T(I.InvalidParams,`Invalid task creation result: ${x}`)}return b.data}let h=Fe(fa,m);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid elicitation result: ${b}`)}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{yi(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Fe(ca,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Fe(Lt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?la:ua,h=Fe(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Bs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ks,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Ep.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){Mg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Lg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mt,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}},Mt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},oa,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Xs,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ws,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Gs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Ys,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mt,r)}async callTool(t,r=vt,n){if(this.isToolTaskRequired(t.name))throw new T(I.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new T(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new T(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},sa,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=Zp.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 Py=Yi(Ty(),1);import _u from"node:process";import{PassThrough as ER}from"node:stream";var vi=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),SR(r)}clear(){this._buffer=void 0}};function SR(e){return Np.parse(JSON.parse(e))}function Ry(e){return JSON.stringify(e)+`
37
+ `}var TR=_u.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function RR(){let e={};for(let t of TR){let r=_u.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var bi=class{constructor(t){this._readBuffer=new vi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new ER)}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,Py.default)(this._serverParams.command,this._serverParams.args??[],{env:{...RR(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:_u.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=Ry(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var PR=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Yt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new bi({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??zR(),stderr:t.stderr??"pipe"}),n=new _i({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:IR(r).map(AR),nextCursor:zy(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!xi(n,["error"])&&DR(n,["ok","success"],!0),target:t,messageId:Je(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:NR(r).map(CR).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=PR.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:OR(r)},vt);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 zR(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function OR(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function IR(e){if(Array.isArray(e))return e;if(!Or(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&Or(r)?[r]:[]}function AR(e){return Or(e)?{id:Je(e,["id","message_id","messageId"]),cursor:zy(e,["cursor"]),type:Je(e,["type","event_type","eventType"]),platform:Je(e,["platform"]),target:Je(e,["target"]),sessionKey:Je(e,["session_key","sessionKey"]),timestamp:Je(e,["timestamp","created_at","createdAt"]),message:Je(e,["message","text","content"]),raw:e}:{raw:e}}function NR(e){if(Array.isArray(e))return e;if(!Or(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function CR(e){if(!Or(e))return null;let t=Je(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Je(e,["platform"]),name:Je(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Je(e,t){let r=xi(e,t);return typeof r=="string"?r:void 0}function DR(e,t,r){let n=xi(e,t);return typeof n=="boolean"?n:r}function zy(e,t){let r=xi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function xi(e,t){if(Or(e))for(let r of t){let n=e[r];if(n!=null)return n}}function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as gI,writeFile as yI}from"node:fs/promises";import{join as sw}from"node:path";var $i=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function E(e,t){return new $i(e,t)}var ve=",";function wu(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 at(e){return E(e,"invalid quoted string")}function zt(e,t){if(e==="")return"";if(e.startsWith('"'))return Oy(e,t);if(e.includes('"'))throw at(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:jR(e)?Number(e):e}function Qt(e,t){let r=e.trim();if(r.startsWith('"'))return[Oy(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function Oy(e,t){if(e[0]!=='"')throw at(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw at(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
+ `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw at(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw at(t);r+=String.fromCharCode(a),n+=4;break}default:throw at(t)}continue}if(o<" "&&o!==" ")throw at(t);r+=o}throw at(t)}function Ln(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw at(r);return n.push(e.slice(o).trim()),n}function Ie(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw at(r);return-1}function jR(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function MR(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function LR(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw E(0,"number is not representable in TOON");return String(e)}function ki(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function Ot(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return LR(e);if(typeof e=="string")return BR(e,t);throw E(0,"not a primitive")}function qR(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function ct(e){return qR(e)?e:Iy(e)}function BR(e,t){return ZR(e,t)?Iy(e):e}function ZR(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||MR(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function Iy(e){let t='"';for(let r of e)switch(r){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
41
+ `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:r<" "?t+=`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=r}return`${t}"`}function qn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Eu=2;function UR(e={}){return{indent:Math.max(1,e.indent??Eu),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function FR(e,t){let r=[],n=!1;return wu(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 E(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw E(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function Ye(e,t){let r=UR(t),n=FR(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw E(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=Pu(o.content,Ie(o.content,":",o.number))}catch(u){if(r.strict)throw ku(u,o.number);l=void 0}if(l!==void 0)return HR(l,n,r)}if(i&&Ie(o.content,":",o.number)===-1)return zt(o.content.trim(),o.number);let s={index:0},a=Tu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function Tu(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 E(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=VR(e,t,r,n);Cy(o,s,a,c,n,i.number)}return o}function VR(e,t,r,n){let o=e[t.index],i=o.content,s=Ie(i,":",o.number);if(s===-1)throw E(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=Ie(a,"[",o.number),u=Ie(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=YR(a)}catch(_){if(n.strict)throw ku(_,o.number);t.index+=1;let w=vu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw E(o.number,"expected keyed map rows");let h=KR(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=Pu(a,s)}catch(_){if(n.strict)throw ku(_,o.number);t.index+=1;let w=vu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw E(o.number,"expected non-empty field name");let h=Ru(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Qt(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=vu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function vu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return zt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?Tu(e,t,r+1,i):{}}function KR(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 E(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw E(s.number,"blank line inside keyed map");let a=Ie(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Qt(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Ln(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw E(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{Bn(d,f,zt(u[p],s.number),o,s.number)}),Cy(i,c,l,d,o,s.number),r.index+=1}return i}function HR(e,t,r){let n=t[0],o=Ie(n.content,":",n.number);if(o===-1)throw E(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=Ru(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function Ru(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 E(s,"expected tabular rows");return WR(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Ln(a,e.delimiter,s).map(l=>zt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return GR(e,r,n,o+1,i)}function WR(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw xu(r,n.index);if(c.depth<o)break;if(c.depth>o)throw E(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw E(c.number,"blank line inside array");if(!Ay(c.content,e.delimiter,c.number))break;let l=Ln(c.content,e.delimiter,c.number);if(l.length!==t.length)throw E(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{Bn(u,d,zt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw xu(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Ay(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function Ay(e,t,r){let n=Ie(e,":",r);if(n===-1)return!0;let o=Ie(e,t,r);return o===-1?!1:o<n}function GR(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 xu(t,r.index);if(a.depth>n)throw E(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw E(a.number,"blank line inside array");i.push(JR(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw E(s.number,"array length mismatch");return i}function JR(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw E(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=Ie(i,":",o.number),a;try{a=Pu(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return Ru(a,c,e,t,r,n)}}if(Ie(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 Tu(s,{index:0},r+1,n)}return t.index+=1,zt(i,o.number)}function xu(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function Pu(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=Ie(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Qt(r.slice(0,n),0)}catch{throw E(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw E(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 E(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 E(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{p=Ny(f.slice(1,-1),d)}catch(m){throw E(0,m.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw E(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function YR(e){let t=Ie(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Qt(e.slice(0,t),0)}catch{throw E(0,"invalid keyed map header")}if(r===""&&!n)throw E(0,"expected non-empty field name");let o;try{o=Ny(e.slice(t+1,-1),ve)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:ve,fields:o}}function Ny(e,t){let r=[],n=0;function o(a,c){let l=0;for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw E(0,"invalid array header");let u=n;for(;n<e.length;){let f=e[n];if(f==='"'){i();continue}if(f===t||f==="{"||f==="}")break;n+=1}let[d]=Qt(e.slice(u,n),0);if(d==="")throw E(0,"invalid array header");if(l+=1,e[n]==="{"){n+=1;let f=r.length;if(o([...a,d],!0),e[n]!=="}"||r.length===f)throw E(0,"invalid array header");n+=1}else r.push([...a,d]);if(e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw E(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw E(0,"invalid array header")}if(l===0)throw E(0,"invalid array header")}function i(){for(n+=1;n<e.length;){let a=e[n];if(n+=1,a==="\\")n+=1;else if(a==='"')return}}if(o([],!1),n!==e.length)throw E(0,"invalid array header");let s=new Set;for(let a=0;a<r.length;a+=1)for(let c=a+1;c<r.length;c+=1)if(QR(r[a],r[c])||$u(r[a],r[c])||$u(r[c],r[a]))throw E(0,"duplicate key");for(let a of r){let c=a.join("\0");if(s.has(c))throw E(0,"duplicate key");s.add(c)}return r}function QR(e,t){return e.length===t.length&&$u(e,t)}function $u(e,t){return t.every((r,n)=>e[n]===r)}function ku(e,t){return E(t,e.reason??String(e.message))}function Cy(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(XR)){Bn(e,s,n,o,i);return}}Bn(e,[t],n,o,i)}function Bn(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw E(o,"duplicate key");qn(e,i,r);return}if(s&&!Ir(e[i])){if(n.strict)throw E(o,"path expansion conflict");qn(e,i,{})}else s||qn(e,i,{});Bn(e[i],t.slice(1),r,n,o)}function XR(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qe(e,t={}){let r={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},n=[];return Array.isArray(e)?zu(n,void 0,e,0,!1,r):Ir(e)?Dy(n,e,0,r):n.push(Ot(e,ve)),n.join("")}function Zn(e,t){e.push(" ".repeat(t*Eu))}function Dy(e,t,r,n){for(let[o,i]of Object.entries(t))Zn(e,r),Su(e,o,i,r,n)}function Su(e,t,r,n,o){if(Array.isArray(r)){zu(e,t,r,n,!1,o);return}if(Ir(r)){let i=o.keyedMapCollapse?tP(r,o):void 0;if(i!==void 0){e.push(ct(t),"{",i.fields.map(Ou).join(ve),`}:
42
+ `);for(let[s,a]of Object.entries(r))Zn(e,n+1),e.push(ct(s),": ",i.paths.map(c=>Ot(qy(a,c),ve)).join(ve),`
43
+ `);return}e.push(ct(t),`:
44
+ `),Dy(e,r,n+1,o);return}e.push(ct(t),": ",Ot(r,ve),`
45
+ `)}function zu(e,t,r,n,o,i){if(r.length===0){t!==void 0?e.push(ct(t),`: []
46
46
  `):o?e.push(`[0]:
47
47
  `):e.push(`[]
48
48
  `);return}if(r.every(ki)){bu(e,t,r.length,void 0),e.push(" "),e.push(r.map(a=>Ot(a,ve)).join(ve)),e.push(`
49
- `);return}let s=o?void 0:Dy(r,i);if(s!==void 0){bu(e,t,r.length,s.fields),e.push(`
50
- `);for(let a of r)Zn(e,n+1),e.push(s.paths.map(c=>Ot(Ly(a,c),ve)).join(ve)),e.push(`
49
+ `);return}let s=o?void 0:jy(r,i);if(s!==void 0){bu(e,t,r.length,s.fields),e.push(`
50
+ `);for(let a of r)Zn(e,n+1),e.push(s.paths.map(c=>Ot(qy(a,c),ve)).join(ve)),e.push(`
51
51
  `);return}bu(e,t,r.length,void 0),e.push(`
52
- `);for(let a of r)Zn(e,n+1),ZR(e,a,n+1,i)}function ZR(e,t,r,n){if(Array.isArray(t)){e.push("- "),zu(e,void 0,t,r,!0,n);return}if(Ir(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
52
+ `);for(let a of r)Zn(e,n+1),eP(e,a,n+1,i)}function eP(e,t,r,n){if(Array.isArray(t)){e.push("- "),zu(e,void 0,t,r,!0,n);return}if(Ir(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
53
53
  `);return}e.push("- "),Su(e,o[0][0],o[0][1],r+1,n);for(let[i,s]of o.slice(1))Zn(e,r+1),Su(e,i,s,r+1,n);return}e.push("- ",Ot(t,ve),`
54
- `)}function bu(e,t,r,n){t!==void 0&&e.push(st(t)),e.push("[",String(r),"]"),n!==void 0&&e.push("{",n.map(Ou).join(ve),"}"),e.push(":")}function Dy(e,t){let r=jy(e.map(n=>({value:n})),t);return r===void 0?void 0:{fields:r,paths:My(r)}}function UR(e,t){let r=Object.values(e);if(!(r.length<2))return Dy(r,t)}function jy(e,t){let r=e[0]?.value;if(!Ir(r))return;let n=Object.keys(r).map(o=>({key:o}));if(n.length!==0){for(let{value:o}of e)if(!Ir(o)||Object.keys(o).length!==n.length||n.some(s=>!Object.prototype.hasOwnProperty.call(o,s.key)))return;for(let o of n){let i=e.map(({value:a})=>({value:a[o.key]}));if(i.every(({value:a})=>ki(a)))continue;if(!t.nestedTabularHeaders)return;let s=jy(i,t);if(s===void 0)return;o.children=s}return n}}function My(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children===void 0?[n]:My(r.children,n)})}function Ly(e,t){let r=e;for(let n of t)r=r[n];return r}function Ou(e){return e.children===void 0?st(e.key):`${st(e.key)}{${e.children.map(Ou).join(ve)}}`}var iq=new TextEncoder,sq=new TextDecoder;import{basename as H_}from"node:path";import{randomUUID as Zu}from"node:crypto";import{spawn as gP}from"node:child_process";import{readFileSync as yP}from"node:fs";import{mkdir as _P,readFile as wP,rename as eB,rm as Un,stat as tB,writeFile as rB}from"node:fs/promises";import{dirname as Fn,join as ht,resolve as Uu}from"node:path";import{isAbsolute as Cq,join as Ar,resolve as VR}from"node:path";var KR=".red";function HR(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function qy(e){return Ar(HR(e),KR)}function By(e){return Ar(qy(e),"state")}function WR(e){return Ar(qy(e),"tmp")}function Iu(e){return Ar(By(e),"rsp")}function Au(e){return Ar(By(e),"red-skills.rdb")}var GR=".red/tmp/red-skills.rdb";function Zy(e){return Ar(WR(e),"red-skills.rdb")}function Uy(e,t){let r=Au(e);if(t(r))return r;let n=Zy(e);if(t(n))throw Nu();return r}function Fy(e,t){return t===GR||VR(e,t)===Zy(e)}function Nu(){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 JR}from"node:crypto";import{constants as Cu}from"node:fs";import{mkdir as YR,open as QR}from"node:fs/promises";import{createConnection as XR}from"node:net";import{tmpdir as eP}from"node:os";import{dirname as tP,join as Du}from"node:path";var rP=108;async function Vy(e,t,r="resident server"){let n=e.timeoutMs??1e3;return await new Promise((o,i)=>{let s=XR(e.socketPath),a=!1,c="",l=setTimeout(()=>{u(()=>i(new Error(`${r} timed out`))),s.destroy()},n);function u(d){a||(a=!0,clearTimeout(l),d())}s.on("connect",()=>{s.write(`${JSON.stringify(t)}
55
- `)}),s.on("data",d=>{c+=d.toString("utf8");let f=c.indexOf(`
56
- `);if(f<0)return;let p=c.slice(0,f);u(()=>{try{o(JSON.parse(p))}catch(m){i(m)}}),s.end()}),s.on("error",d=>u(()=>i(d))),s.on("close",()=>{a||u(()=>i(new Error(`${r} closed without response`)))})})}async function Ky(e){await YR(tP(e),{recursive:!0,mode:448});try{return await QR(e,Cu.O_CREAT|Cu.O_EXCL|Cu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function Nr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function Hy(e,t=1e3){if(!Nr(e))return;try{process.kill(e,"SIGTERM")}catch{return}let r=Date.now()+t;for(;Date.now()<r;){if(!Nr(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}function Wy(e){let t=e.env??process.env,r=JR("sha256").update(e.key).digest("hex").slice(0,20),n=t.XDG_RUNTIME_DIR;if(n){let i=Du(n,"red-skills",r);if(Du(i,e.socketFileName).length<rP)return i}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return Du(eP(),`red-skills-${o}`,r)}async function Si(e,t){return await Vy(e,t,"resident rsp server")}import{existsSync as nP,readdirSync as oP}from"node:fs";import{homedir as iP}from"node:os";import{basename as Mu,dirname as ju,join as Ze,resolve as Ei}from"node:path";var Ti="rsp-resident-entry-unresolved";function sP(e){return"command"in e}var Ri=class extends Error{code=Ti;searched;callerEntry;constructor(t){super(`${Ti}: no rsp entrypoint found for the resident auto-spawn${t.callerEntry?` (caller entry: ${t.callerEntry})`:""}
54
+ `)}function bu(e,t,r,n){t!==void 0&&e.push(ct(t)),e.push("[",String(r),"]"),n!==void 0&&e.push("{",n.map(Ou).join(ve),"}"),e.push(":")}function jy(e,t){let r=My(e.map(n=>({value:n})),t);return r===void 0?void 0:{fields:r,paths:Ly(r)}}function tP(e,t){let r=Object.values(e);if(!(r.length<2))return jy(r,t)}function My(e,t){let r=e[0]?.value;if(!Ir(r))return;let n=Object.keys(r).map(o=>({key:o}));if(n.length!==0){for(let{value:o}of e)if(!Ir(o)||Object.keys(o).length!==n.length||n.some(s=>!Object.prototype.hasOwnProperty.call(o,s.key)))return;for(let o of n){let i=e.map(({value:a})=>({value:a[o.key]}));if(i.every(({value:a})=>ki(a)))continue;if(!t.nestedTabularHeaders)return;let s=My(i,t);if(s===void 0)return;o.children=s}return n}}function Ly(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children===void 0?[n]:Ly(r.children,n)})}function qy(e,t){let r=e;for(let n of t)r=r[n];return r}function Ou(e){return e.children===void 0?ct(e.key):`${ct(e.key)}{${e.children.map(Ou).join(ve)}}`}var wq=new TextEncoder,vq=new TextDecoder;import{basename as iw}from"node:path";import{randomUUID as Uu}from"node:crypto";import{spawn as zP}from"node:child_process";import{readFileSync as OP}from"node:fs";import{mkdir as IP,readFile as AP,rename as yB,rm as Un,stat as _B,writeFile as wB}from"node:fs/promises";import{dirname as Fn,join as ht,resolve as Fu}from"node:path";import{isAbsolute as Gq,join as Ar,resolve as nP}from"node:path";var oP=".red";function iP(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function By(e){return Ar(iP(e),oP)}function Zy(e){return Ar(By(e),"state")}function sP(e){return Ar(By(e),"tmp")}function Iu(e){return Ar(Zy(e),"rsp")}function Au(e){return Ar(Zy(e),"red-skills.rdb")}var aP=".red/tmp/red-skills.rdb";function Uy(e){return Ar(sP(e),"red-skills.rdb")}function Fy(e,t){let r=Au(e);if(t(r))return r;let n=Uy(e);if(t(n))throw Nu();return r}function Vy(e,t){return t===aP||nP(e,t)===Uy(e)}function Nu(){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 lP}from"node:crypto";import{constants as Du}from"node:fs";import{mkdir as dP,open as fP}from"node:fs/promises";import{createConnection as pP}from"node:net";import{tmpdir as mP}from"node:os";import{dirname as hP,join as ju}from"node:path";var cP="toon";function Wy(e){return e.trimStart().startsWith("{")?"json":"toon"}function Gy(e){let t=0;for(;e[t]===`
55
+ `||e[t]==="\r";)t+=1;let r=e.slice(t);if(r==="")return null;let n=Wy(r);if(n==="json"){let i=r.indexOf(`
56
+ `);return i<0?null:{frame:r.slice(0,i),dialect:n,rest:r.slice(i+1)}}let o=r.indexOf(`
57
+
58
+ `);return o<0?null:{frame:r.slice(0,o+1),dialect:n,rest:r.slice(o+2)}}function Jy(e){let t=Wy(e)==="json"?Cu:Ky,r=t===Cu?Ky:Cu;try{return t(e)}catch(n){try{return r(e)}catch{throw n}}}function Cu(e){return JSON.parse(e)}function Ky(e){return Ye(e)}function Yy(e,t){if(t==="toon"){let r=uP(e);if(r!==null)return r.endsWith(`
59
+ `)?`${r}
60
+ `:`${r}
61
+
62
+ `}return`${JSON.stringify(e)}
63
+ `}function uP(e){try{let t=JSON.stringify(e);if(t===void 0)return null;let r=Qe(JSON.parse(t));return r.trim()===""?null:r}catch{return null}}function Qy(e,t){return!Hy(e)||!Hy(t)||t.ok!==!1?!1:typeof e.id=="string"&&typeof t.id=="string"&&t.id!==e.id}function Hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Xy=new Set;function e_(e){return Xy.has(e)?"json":cP}function t_(e){Xy.add(e)}var gP=108;async function n_(e,t,r="resident server"){let n=e.wire,o=n??e_(e.socketPath),i=await r_(e,t,r,o);return n||o==="json"||!Qy(t,i)?i:(t_(e.socketPath),await r_(e,t,r,"json"))}async function r_(e,t,r,n){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=pP(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(Yy(t,n))}),a.on("data",f=>{l+=f.toString("utf8");let p=Gy(l);p&&(l=p.rest,d(()=>{try{i(Jy(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 o_(e){await dP(hP(e),{recursive:!0,mode:448});try{return await fP(e,Du.O_CREAT|Du.O_EXCL|Du.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function Nr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function i_(e,t=1e3){if(!Nr(e))return;try{process.kill(e,"SIGTERM")}catch{return}let r=Date.now()+t;for(;Date.now()<r;){if(!Nr(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}function s_(e){let t=e.env??process.env,r=lP("sha256").update(e.key).digest("hex").slice(0,20),n=t.XDG_RUNTIME_DIR;if(n){let i=ju(n,"red-skills",r);if(ju(i,e.socketFileName).length<gP)return i}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return ju(mP(),`red-skills-${o}`,r)}async function Si(e,t){return await n_(e,t,"resident rsp server")}import{existsSync as yP,readdirSync as _P}from"node:fs";import{homedir as wP}from"node:os";import{basename as Lu,dirname as Mu,join as Ze,resolve as Ei}from"node:path";var Ti="rsp-resident-entry-unresolved";function vP(e){return"command"in e}var Ri=class extends Error{code=Ti;searched;callerEntry;constructor(t){super(`${Ti}: no rsp entrypoint found for the resident auto-spawn${t.callerEntry?` (caller entry: ${t.callerEntry})`:""}
57
64
  searched:
58
65
  ${t.searched.map(r=>` ${r}`).join(`
59
- `)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},Xt="rsp.bundle.min.mjs",aP=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Lu=/^rsp-(.+)\.bundle\.min\.mjs$/,cP=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function Jy(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let r=t.env??process.env,n=t.exists??nP,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&&uP(s))return a(Ei(s),"caller-entry");let c=[];for(let[l,u]of dP(s,t.rootDir,r,t.listDir??hP))if(c.push(l),n(l))return a(l,u);return{diagnostic:Ti,searched:c,...s?{callerEntry:Ei(s)}:{}}}function Yy(e={},t={}){let r=Jy(e,t);if(sP(r))return r;throw new Ri(r)}function uP(e){let t=Mu(e);return t===Xt||Lu.test(t)||t==="rsp"||t==="rsp.mjs"||t==="rsp.js"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:lP(Ei(e))}function lP(e){let t=ju(e);for(let r=0;r<4;r++){if(Mu(t)==="rsp")return!0;let n=ju(t);if(n===t)return!1;t=n}return!1}function*dP(e,t,r,n){if(e){let i=ju(Ei(e));yield[Ze(i,Xt),"caller-sibling-bundle"];let s=aP.exec(Mu(e));s&&(yield[Ze(i,`rsp-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Ze(i,"..","dist",Xt),"caller-sibling-bundle"]}for(let i of cP){let s=r[i];s&&(yield[Ze(s,"dist",Xt),"plugin-root-bundle"],yield[Ze(s,"..","..","dist",Xt),"plugin-root-bundle"])}t&&(yield[Ze(t,"dist",Xt),"repo-bundle"],yield[Ze(t,"apps","rsp","dist","cli.js"),"workspace-entry"],yield[Ze(t,"node_modules","@reddb-io","rsp","dist","cli.js"),"node-modules-entry"]);let o=fP(r);yield[Ze(o,Xt),"bundle-cache"];for(let i of pP(o,n))yield[Ze(o,i),"bundle-cache"]}function fP(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Ze(e.HOME||iP(),".cache");return Ze(t,"red-skills","bundles")}function pP(e,t){return t(e).filter(r=>Lu.test(r)).sort((r,n)=>mP(Gy(n),Gy(r)))}function Gy(e){return Lu.exec(e)?.[1]??""}function mP(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 hP(e){try{return oP(e)}catch{return[]}}var vP=1,bP=5e3;function zi(e){let t=NP(e)??Uu(e),r=AP(t),n=Iu(t);return{rootDir:t,socketPath:ht(r,"rsp.sock"),pidPath:ht(r,"rsp.pid"),lockPath:ht(r,"rsp.lock"),wakeLockPath:ht(t,".red","tmp","rsp","wake.lock"),summaryPath:ht(n,"rsp-status-summary.json"),registryPath:ht(n,"rsp-resident.pid.json")}}var Pi=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await xP(this.paths,this.config);let r=await Si(this.paths,{...t,id:Zu()});if(!r.ok)throw new Error(r.error);return r.value}};async function xP(e,t){if(await _P(Fn(e.socketPath),{recursive:!0,mode:448}),await e_(e.socketPath,t))return;await Xy(e,t);let r=await EP(e.lockPath);if(r)try{if(await e_(e.socketPath,t))return;await Xy(e,t),await SP(e.socketPath);let n=TP(e,t);await Qy(e.socketPath,n);return}finally{await r.close(),await Un(e.lockPath,{force:!0})}await Qy(e.socketPath)}async function Vn(e,t=200){try{return await r_(e,t)!=null}catch{return!1}}async function r_(e,t=200){let r=await Si({socketPath:e,timeoutMs:t},{id:Zu(),op:"ping"});return r.ok?o_(r.value)?{version:MP(r.value.version)}:{}:null}async function $P(e){try{let t=zP(await wP(e,"utf8"));return LP(t)?t:null}catch{return null}}async function Qy(e,t){let r=Date.now()+kP(),n;for(;Date.now()<r;){if(await Vn(e))return;if(t){let o=t.spawnError();if(o)throw new Error(qu("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(qu("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?qu("resident rsp server did not start",t):"resident rsp server did not start")}function kP(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:bP}async function SP(e){await Un(e,{force:!0})}var EP=Ky;function TP(e,t){let[r,n]=IP(e,t),o=process.env.RSP_DEBUG==="1",i,s="",a=gP(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=PP(`${s}${c}`,RP)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var RP=8*1024;function qu(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:
66
+ `)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},Xt="rsp.bundle.min.mjs",bP=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,qu=/^rsp-(.+)\.bundle\.min\.mjs$/,xP=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function c_(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let r=t.env??process.env,n=t.exists??yP,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&&$P(s))return a(Ei(s),"caller-entry");let c=[];for(let[l,u]of SP(s,t.rootDir,r,t.listDir??PP))if(c.push(l),n(l))return a(l,u);return{diagnostic:Ti,searched:c,...s?{callerEntry:Ei(s)}:{}}}function u_(e={},t={}){let r=c_(e,t);if(vP(r))return r;throw new Ri(r)}function $P(e){let t=Lu(e);return t===Xt||qu.test(t)||t==="rsp"||t==="rsp.mjs"||t==="rsp.js"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:kP(Ei(e))}function kP(e){let t=Mu(e);for(let r=0;r<4;r++){if(Lu(t)==="rsp")return!0;let n=Mu(t);if(n===t)return!1;t=n}return!1}function*SP(e,t,r,n){if(e){let i=Mu(Ei(e));yield[Ze(i,Xt),"caller-sibling-bundle"];let s=bP.exec(Lu(e));s&&(yield[Ze(i,`rsp-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Ze(i,"..","dist",Xt),"caller-sibling-bundle"]}for(let i of xP){let s=r[i];s&&(yield[Ze(s,"dist",Xt),"plugin-root-bundle"],yield[Ze(s,"..","..","dist",Xt),"plugin-root-bundle"])}t&&(yield[Ze(t,"dist",Xt),"repo-bundle"],yield[Ze(t,"apps","rsp","dist","cli.js"),"workspace-entry"],yield[Ze(t,"node_modules","@reddb-io","rsp","dist","cli.js"),"node-modules-entry"]);let o=EP(r);yield[Ze(o,Xt),"bundle-cache"];for(let i of TP(o,n))yield[Ze(o,i),"bundle-cache"]}function EP(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Ze(e.HOME||wP(),".cache");return Ze(t,"red-skills","bundles")}function TP(e,t){return t(e).filter(r=>qu.test(r)).sort((r,n)=>RP(a_(n),a_(r)))}function a_(e){return qu.exec(e)?.[1]??""}function RP(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 PP(e){try{return _P(e)}catch{return[]}}var NP=1,CP=5e3;function zi(e){let t=WP(e)??Fu(e),r=HP(t),n=Iu(t);return{rootDir:t,socketPath:ht(r,"rsp.sock"),pidPath:ht(r,"rsp.pid"),lockPath:ht(r,"rsp.lock"),wakeLockPath:ht(t,".red","tmp","rsp","wake.lock"),summaryPath:ht(n,"rsp-status-summary.json"),registryPath:ht(n,"rsp-resident.pid.json")}}var Pi=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await DP(this.paths,this.config);let r=await Si(this.paths,{...t,id:Uu()});if(!r.ok)throw new Error(r.error);return r.value}};async function DP(e,t){if(await IP(Fn(e.socketPath),{recursive:!0,mode:448}),await f_(e.socketPath,t))return;await d_(e,t);let r=await qP(e.lockPath);if(r)try{if(await f_(e.socketPath,t))return;await d_(e,t),await LP(e.socketPath);let n=BP(e,t);await l_(e.socketPath,n);return}finally{await r.close(),await Un(e.lockPath,{force:!0})}await l_(e.socketPath)}async function Vn(e,t=200){try{return await m_(e,t)!=null}catch{return!1}}async function m_(e,t=200){let r=await Si({socketPath:e,timeoutMs:t},{id:Uu(),op:"ping"});return r.ok?g_(r.value)?{version:QP(r.value.version)}:{}:null}async function jP(e){try{let t=FP(await AP(e,"utf8"));return XP(t)?t:null}catch{return null}}async function l_(e,t){let r=Date.now()+MP(),n;for(;Date.now()<r;){if(await Vn(e))return;if(t){let o=t.spawnError();if(o)throw new Error(Bu("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(Bu("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?Bu("resident rsp server did not start",t):"resident rsp server did not start")}function MP(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:CP}async function LP(e){await Un(e,{force:!0})}var qP=o_;function BP(e,t){let[r,n]=KP(e,t),o=process.env.RSP_DEBUG==="1",i,s="",a=zP(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=UP(`${s}${c}`,ZP)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var ZP=8*1024;function Bu(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:
60
67
  ${o}`),n.join(`
61
- `)}function PP(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function zP(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return pt(t)}}async function Xy(e,t){try{let r=await $P(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!Nr(r.pid)){await Un(e.registryPath,{force:!0});return}if(await Vn(r.socket_path,100))return;if(n_(t.clientVersion,r.resident_version)&&(await OP(r.pid,1500),!Nr(r.pid))){await Un(e.registryPath,{force:!0});return}await Hy(r.pid),await Un(e.registryPath,{force:!0})}catch{}}async function OP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!Nr(e))return;await new Promise(n=>setTimeout(n,50))}}function IP(e,t){let r=Yy(t,{rootDir:e.rootDir});return[r.command,r.args]}function AP(e){return Wy({key:e,socketFileName:"rsp.sock"})}function NP(e){let t=Uu(e);for(let r=0;r<32;r++){try{let o=Bu(ht(t,".git"));if(o!=null)return CP(t,o)??t;if(Bu(ht(t,".git","HEAD"))!=null||Bu(ht(t,".red","config.yaml"))!=null)return t}catch{}let n=Fn(t);if(n===t)return null;t=n}return null}function CP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Uu(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?Fn(Fn(Fn(n))):null}function Bu(e){try{return yP(e,"utf8")}catch{return null}}async function e_(e,t){let r=await r_(e).catch(()=>null);return r?n_(t.clientVersion,r.version)?(await DP(e,t.clientVersion),await qP(e),!1):!0:!1}async function DP(e,t){try{await Si({socketPath:e,timeoutMs:200},{id:Zu(),op:"handover",clientVersion:t})}catch{}}function n_(e,t){return!e||!t?!1:jP(e,t)>0}function jP(e,t){let r=t_(e),n=t_(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function t_(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 o_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function MP(e){return typeof e=="string"&&e.length>0?e:void 0}function LP(e){return o_(e)&&e.version===vP&&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 qP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Vn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as BP}from"node:child_process";var Vu=["supports","contradicts","related_to"];function Ku(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 Hu(e){return typeof e=="string"&&Vu.includes(e)}function Cr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function i_(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
62
- `)}function ZP(e){return{deriveConnections(t){return FP(e,t)}}}function s_(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return ZP({command:t,args:VP(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:KP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function UP(e){let t=JSON.parse(HP(e));return(Array.isArray(t)?t:Fu(t)&&Array.isArray(t.connections)?t.connections:[]).filter(WP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Fu(n.metadata)?n.metadata:void 0}))}async function FP(e,t){let r=BP(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 UP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function VP(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 KP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function HP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function WP(e){return Fu(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Hu(e.kind)}function Fu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as Oi}from"node:fs";import{mkdir as GP,readFile as Wu,writeFile as JP}from"node:fs/promises";import{dirname as Gu,isAbsolute as YP,join as Dr,resolve as It}from"node:path";var Ii="file://./.red/brain/brain.rdb",QP="RED_BRAIN_ROOT",XP="brain.root";async function ez(e=process.cwd(),t={}){let n=(t.env??process.env)[QP];if(n)return It(e,n);let o=await tz(e);if(o)return o;let i=It(e),s=null;for(;;){let a=Dr(i,".red");if(Oi(a)&&(s??=i,Oi(Dr(a,"brain"))||Oi(Dr(a,XP))))return i;let c=Gu(i);if(c===i)return s??It(e);i=c}}async function tz(e){let t=It(e);for(;;){let r=Dr(t,".red","config.yaml");try{let o=await Wu(r,"utf8"),i=rz(o);if(i)return It(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Gu(t);if(n===t)return null;t=n}}function rz(e){let t=nz(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 nz(e){let t={},r=[],n=[];for(let o of e.split(`
63
- `)){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 a_(e){return Dr(It(e),".red","brain","config.yaml")}function oz(e){return Dr(It(e),".env")}async function iz(e){let t=a_(e);return Oi(t)||(await GP(Gu(t),{recursive:!0}),await JP(t,`connection_string: ${Ii}
64
- `,"utf8")),t}async function sz(e){let t=a_(e);try{let r=await Wu(t,"utf8");return az(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function az(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:Ii};let r=t.slice(18).trim();return{connection_string:c_(r)||Ii}}function c_(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function u_(e=process.cwd()){let t=await ez(e),r=await iz(t),n=await sz(t)??{connection_string:Ii},o=await cz(t),i=n.connection_string,s=uz(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:lz(t,s)}}async function cz(e){let t={...process.env};try{let r=await Wu(oz(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=c_(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function uz(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 lz(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return YP(r)?t:`file://${It(e,r)}`}import{existsSync as dz}from"node:fs";import{resolve as fz}from"node:path";var pz=7,mz=64*1024*1024;function d_(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(Fy(e.rootDir,t))throw Nu();return t===Au(e.rootDir)}async function f_(e){let t=zi(e.rootDir),r=new Pi(t,gz(e.rootDir));return await r.request({op:"ping"}),new Ju(r)}function hz(e){return`file://${Uy(fz(e),dz)}`}function gz(e){return{storeUri:hz(e),ttlDays:pz,byteBudget:mz}}var Ju=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return yz(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:l_(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:l_(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 l_(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function yz(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var _z=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",wz=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function p_(e,t){return _z?bz(e,t):wz?$z(e,t):vz(e,t)}async function vz(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 bz(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:xz(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*xz(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 $z(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:kz(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*kz(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 Tz}from"node:url";import{dirname as Rz,resolve as Pz,join as PB}from"node:path";import{existsSync as Sz}from"node:fs";import{join as Ez}from"node:path";function m_(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=Ez(r,"bin",t);if(Sz(i))return i;throw new Error(`reddb: binary "${t}" not found.
68
+ `)}function UP(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function FP(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return Ye(t)}}async function d_(e,t){try{let r=await jP(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!Nr(r.pid)){await Un(e.registryPath,{force:!0});return}if(await Vn(r.socket_path,100))return;if(h_(t.clientVersion,r.resident_version)&&(await VP(r.pid,1500),!Nr(r.pid))){await Un(e.registryPath,{force:!0});return}await i_(r.pid),await Un(e.registryPath,{force:!0})}catch{}}async function VP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!Nr(e))return;await new Promise(n=>setTimeout(n,50))}}function KP(e,t){let r=u_(t,{rootDir:e.rootDir});return[r.command,r.args]}function HP(e){return s_({key:e,socketFileName:"rsp.sock"})}function WP(e){let t=Fu(e);for(let r=0;r<32;r++){try{let o=Zu(ht(t,".git"));if(o!=null)return GP(t,o)??t;if(Zu(ht(t,".git","HEAD"))!=null||Zu(ht(t,".red","config.yaml"))!=null)return t}catch{}let n=Fn(t);if(n===t)return null;t=n}return null}function GP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Fu(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?Fn(Fn(Fn(n))):null}function Zu(e){try{return OP(e,"utf8")}catch{return null}}async function f_(e,t){let r=await m_(e).catch(()=>null);return r?h_(t.clientVersion,r.version)?(await JP(e,t.clientVersion),await ez(e),!1):!0:!1}async function JP(e,t){try{await Si({socketPath:e,timeoutMs:200},{id:Uu(),op:"handover",clientVersion:t})}catch{}}function h_(e,t){return!e||!t?!1:YP(e,t)>0}function YP(e,t){let r=p_(e),n=p_(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function p_(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 g_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QP(e){return typeof e=="string"&&e.length>0?e:void 0}function XP(e){return g_(e)&&e.version===NP&&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 ez(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Vn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as tz}from"node:child_process";var Ku=["supports","contradicts","related_to"];function Hu(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 Wu(e){return typeof e=="string"&&Ku.includes(e)}function Cr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function y_(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
69
+ `)}function rz(e){return{deriveConnections(t){return oz(e,t)}}}function __(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return rz({command:t,args:iz(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:sz(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function nz(e){let t=JSON.parse(az(e));return(Array.isArray(t)?t:Vu(t)&&Array.isArray(t.connections)?t.connections:[]).filter(cz).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Vu(n.metadata)?n.metadata:void 0}))}async function oz(e,t){let r=tz(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 nz(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function iz(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 sz(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function az(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function cz(e){return Vu(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Wu(e.kind)}function Vu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as Oi}from"node:fs";import{mkdir as uz,readFile as Gu,writeFile as lz}from"node:fs/promises";import{dirname as Ju,isAbsolute as dz,join as Dr,resolve as It}from"node:path";var Ii="file://./.red/brain/brain.rdb",fz="RED_BRAIN_ROOT",pz="brain.root";async function mz(e=process.cwd(),t={}){let n=(t.env??process.env)[fz];if(n)return It(e,n);let o=await hz(e);if(o)return o;let i=It(e),s=null;for(;;){let a=Dr(i,".red");if(Oi(a)&&(s??=i,Oi(Dr(a,"brain"))||Oi(Dr(a,pz))))return i;let c=Ju(i);if(c===i)return s??It(e);i=c}}async function hz(e){let t=It(e);for(;;){let r=Dr(t,".red","config.yaml");try{let o=await Gu(r,"utf8"),i=gz(o);if(i)return It(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Ju(t);if(n===t)return null;t=n}}function gz(e){let t=yz(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 yz(e){let t={},r=[],n=[];for(let o of e.split(`
70
+ `)){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 w_(e){return Dr(It(e),".red","brain","config.yaml")}function _z(e){return Dr(It(e),".env")}async function wz(e){let t=w_(e);return Oi(t)||(await uz(Ju(t),{recursive:!0}),await lz(t,`connection_string: ${Ii}
71
+ `,"utf8")),t}async function vz(e){let t=w_(e);try{let r=await Gu(t,"utf8");return bz(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function bz(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:Ii};let r=t.slice(18).trim();return{connection_string:v_(r)||Ii}}function v_(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function b_(e=process.cwd()){let t=await mz(e),r=await wz(t),n=await vz(t)??{connection_string:Ii},o=await xz(t),i=n.connection_string,s=$z(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:kz(t,s)}}async function xz(e){let t={...process.env};try{let r=await Gu(_z(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=v_(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function $z(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 kz(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return dz(r)?t:`file://${It(e,r)}`}import{existsSync as Sz}from"node:fs";import{resolve as Ez}from"node:path";var Tz=7,Rz=64*1024*1024;function $_(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(Vy(e.rootDir,t))throw Nu();return t===Au(e.rootDir)}async function k_(e){let t=zi(e.rootDir),r=new Pi(t,zz(e.rootDir));return await r.request({op:"ping"}),new Yu(r)}function Pz(e){return`file://${Fy(Ez(e),Sz)}`}function zz(e){return{storeUri:Pz(e),ttlDays:Tz,byteBudget:Rz}}var Yu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return Oz(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:x_(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:x_(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 x_(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function Oz(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Iz=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",Az=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function S_(e,t){return Iz?Cz(e,t):Az?jz(e,t):Nz(e,t)}async function Nz(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 Cz(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:Dz(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*Dz(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 jz(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:Mz(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*Mz(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 Bz}from"node:url";import{dirname as Zz,resolve as Uz,join as KB}from"node:path";import{existsSync as Lz}from"node:fs";import{join as qz}from"node:path";function E_(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=qz(r,"bin",t);if(Lz(i))return i;throw new Error(`reddb: binary "${t}" not found.
65
72
  expected at: ${i}
66
73
  override: set ${n}=/path/to/${t}
67
74
  fix: re-run \`pnpm install\` (the postinstall script downloads it),
68
- or check the postinstall log for a download error.`)}var zz=Rz(Tz(import.meta.url)),Oz=Pz(zz,"..");function Iz(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function h_(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:m_({name:Iz(),packageRoot:Oz,envVar:"REDDB_BIN"})}var Az=new TextEncoder,Nz=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Ai=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(Az.encode(o+`
69
- `)).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(Nz.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 Qu(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:/"?Cz(e):Dz(e)}function Cz(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=jz(o),a=r.port?Number(r.port):Yu(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 Dz(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):Yu(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):Yu(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 jz(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 Yu(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 Mz=new Set(["embedded"]),Kn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&Mz.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:qz(n.value)}async put(t,r,n,o={}){this._guard("put");let i=Lz(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 Lz(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return g_(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return g_(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function g_(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 qz(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 jr=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(y_).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Xu(o,t)} = ${Zz(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 ${Xu(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 ${Xu(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 ${el(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(y_).join(", ")}] FROM ${el(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(`
75
+ or check the postinstall log for a download error.`)}var Fz=Zz(Bz(import.meta.url)),Vz=Uz(Fz,"..");function Kz(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function T_(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:E_({name:Kz(),packageRoot:Vz,envVar:"REDDB_BIN"})}var Hz=new TextEncoder,Wz=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Ai=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(Hz.encode(o+`
76
+ `)).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(Wz.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 Xu(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:/"?Gz(e):Jz(e)}function Gz(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=Yz(o),a=r.port?Number(r.port):Qu(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 Jz(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):Qu(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):Qu(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 Yz(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 Qu(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 Qz=new Set(["embedded"]),Kn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&Qz.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:eO(n.value)}async put(t,r,n,o={}){this._guard("put");let i=Xz(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 Xz(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return R_(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return R_(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function R_(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 eO(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 jr=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(P_).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${el(o,t)} = ${rO(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 ${el(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 ${el(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 ${tl(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(P_).join(", ")}] FROM ${tl(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(`
70
77
 
71
78
  `)){let u=l.split(`
72
- `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function Xu(e,t){return`${el(e)}.${Bz(t)}`}function el(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 Bz(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function Zz(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 y_(e){return`'${String(e).replace(/'/g,"''")}'`}var Hn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${gt(t)}`})}push(t,r,n={}){let o=Vz(n);return this.client.call("query",{sql:`QUEUE PUSH ${gt(t)} ${Kz(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${gt(t)}${rl(r)}`});return tl(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${gt(t)}${rl(r)}`});return tl(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${gt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${gt(t)}`})}async readWait(t,r,n={}){let o=Uz(t,r,n),i=await this.client.call("query",{sql:o});return tl(i)}};function Uz(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=gt(e),a=gt(t),c=o!=null?` GROUP ${gt(o)}`:"",l=i!=null?rl(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function gt(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 rl(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 Fz(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Vz(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 ${Fz(e.priority)}`),e.key!=null&&(t+=` KEY ${nl(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${nl(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Kz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?nl(e):JSON.stringify(e)}function nl(e){return`'${String(e).replace(/'/g,"''")}'`}function tl(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Wn=class{constructor(t){this.db=t}async insert(t,r){__(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ni(t)} DOCUMENT VALUES (${Gz(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=Hz(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 ${Ni(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){__(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])=>`${w_(c)} = ${Jz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ni(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 ${Ni(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function __(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function Hz(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 Ni(e){return String(e).split(".").map(w_).join(".")}function w_(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 Wz(e){return v_(JSON.stringify(e))}function Gz(e){return JSON.stringify(e)}function Jz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?Wz(e):v_(e)}function v_(e){return`'${String(e).replace(/'/g,"''")}'`}var Gn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){Qz(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(b_).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${At(o)} ${At(t)} = ${Yz(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${At(n)} ${At(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${At(n)} ${At(t)}`})}};function Yz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${At(r)}.${At(n)})`}return Xz(e)}function Qz(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 At(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 Xz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):b_(e)}function b_(e){return`'${String(e).replace(/'/g,"''")}'`}var Jn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){eO(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(x_).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Mr(o)}.${Mr(t)} = ${tO(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Mr(n)}.${Mr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Mr(n)}.${Mr(t)}`})}};function eO(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 Mr(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 tO(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):x_(e)}function x_(e){return`'${String(e).replace(/'/g,"''")}'`}async function k_(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(rO)}async function S_(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${oO(t)}`)).rows??[]).some(n=>n.name===String(t))}var Yn=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($_).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${$_(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 rO(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function $_(e){return String(e).split(".").map(nO).join(".")}function nO(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 oO(e){return`'${String(e).replace(/'/g,"''")}'`}var iO="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",sO="1.0",R_="1.0.9",E_="NESTED_TX_NOT_SUPPORTED";async function P_(e,t={}){let r=Qu(e);if(mO(r),r.kind==="embedded"){let n=pO(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=fO(r),i=t.binary??h_(),s=await p_(i,o),a=new Ai(s);return await a.call("version",{}),new il(a,{transport:"embedded"})}}function T_(e){return aO(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:uO(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&dO(e)?{$uuid:e}:e}function aO(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 cO(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(T_):e.map(T_)}function uO(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 lO(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 dO(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ci(e){if(Array.isArray(e))return e.map(Ci);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return lO(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]=Ci(o);return r}return e}function fO(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function pO(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 mO(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",iO)}var Di=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 sl()}},ol=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw sl();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 Di(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){z_(r,n)}throw r}}},il=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=sO,this.cache=new Kn(t,this.transport),this.queue=new Hn(t),this.queues=this.queue,this.documents=new Wn(this);let n=new jr(t);this.kv=Object.assign((o="kv_default")=>new jr(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 Gn(t,o),this.vault=(o="red.vault")=>new Jn(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=cO(r);return n==null?this.client.call("query",{sql:t}).then(Ci):this.client.call("query",{sql:t,params:n}).then(Ci)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return hO(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 gO(n,r.length)}tx(){return new ol(this)}async transaction(t){if(this.inTransaction)throw sl();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 Di(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){z_(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return S_(this,t)}list(){return k_(this)}from(t){return new Yn(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 sl(){return new z(E_,`${E_}: nested transactions are not supported on one connection`)}function z_(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function hO(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${R_} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function gO(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 >= ${R_} 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 Qn(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"&&yO(t.chosenOption)&&_O(t.outcome)&&wO(t.cost)}function yO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function _O(e){return e==="success"||e==="failure"||e==="escalated"}function wO(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 vO}from"node:crypto";function al(e){return vO("sha256").update(e).digest("hex")}function O_(e){return al(JSON.stringify(e))}function I_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var cl="unknown",ji=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=dl(t.from),i=dl(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>bO(p,n)).filter(p=>p!=null).filter(p=>$O(p,t)).filter(p=>kO(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=TO(c,l,r),f=[A_(null,s,u,r)];if(t.groupBy){let m=[...SO(s,t.groupBy).entries()].map(([h,_])=>A_(h,_,u,r)).sort((h,_)=>_.total-h.total||PO(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function bO(e,t){let r=e.properties.metadata??{},n=xO(e,r,t);return n==null?null:{ts:n,platform:ul(r,"platform")??cl,eventType:ul(r,"event_type")??cl,target:ul(r,"target")??cl}}function xO(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:dl(t.timestamp)??n}function ul(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function $O(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 kO(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function SO(e,t){let r=new Map;for(let n of e){let o=EO(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function EO(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function A_(e,t,r,n){let o=new Map;for(let s of t){let a=ll(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 TO(e,t,r){if(e==null||t==null)return[];let n=[],o=ll(e,r),i=ll(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=RO(o,r),s++;return n}function ll(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 RO(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 dl(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 PO(e,t){return String(e??"").localeCompare(String(t??""))}var zO=["validate","simple","complex","think"];var OO={validate:1,simple:.85,complex:.65,think:.45};function IO(){return{schemaVersion:1,buckets:{}}}function C_(e,t={}){let r=MO(t.initial??IO());for(let n of e)AO(r,n,t);return r}function AO(e,t,r={}){let n=(r.tierForEvent??NO)(t);if(!n)return e;let i=DO(e,t.taskClass).arms[n],s=CO(t,n);return i.posterior.alpha=N_(i.posterior.alpha+s),i.posterior.beta=N_(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 NO(e){let t=e.chosenOption.kind;if(LO(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 CO(e,t){return e.outcome!=="success"?0:OO[t]}function DO(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=jO(),e.buckets[r]}function jO(){return{arms:{validate:Mi(),simple:Mi(),complex:Mi(),think:Mi()}}}function Mi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function MO(e){return JSON.parse(JSON.stringify(e))}function LO(e){return zO.includes(e)}function N_(e){return Math.round(e*1e3)/1e3}var Li=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],D_={contact:"person"},qi=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ye={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Zi=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 P_(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 ${Ye.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ye.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ye.outcomeEvents}`)}kv(){return this.db.kv(Ye.kv)}async capture(t){let r=U_(t.kind??"note"),n=Date.now(),o=UO(t.tags??[]),i=O_([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=`${I_(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 ${Ye.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(M_(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 ${Ye.artifacts}`);this.artifactCache=t.rows.map(qO).filter(Bi)}return this.artifactCache}async search(t,r=10,n={}){let o=FO(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=V_(u,o),f=K_({...d,connections:VO(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:HO(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=F_(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 ${Ye.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(L_(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 ${Ye.connections}`);this.connectionCache=t.rows.map(BO).filter(Bi)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:eI(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new ji(r).events(t)}async appendOutcomeEvent(t){if(!Qn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ye.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 ${Ye.outcomeEvents}`);this.outcomeEventCache=t.rows.map(ZO).filter(Bi).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(q_());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return B_(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!B_(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(q_(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=C_(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=>!Cr(i.artifact)).slice(0,r);return WO(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(M_(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(L_(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||Cr(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=i_(t),i=new Set([t.rid]);for(let d of r)Cr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Cr(d.artifact)).map(d=>({artifact:Ku(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Ku(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Vu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!Hu(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 U_(e){let r=D_[e]??e;if(Li.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function F_(e){if(qi.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function qO(e){let t=Number(e.red_entity_id??e.rid),r=fl(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:U_(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 BO(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:F_(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:fl(e.properties??e.PROPERTIES)}}function ZO(e){let t=Number(e.red_entity_id??e.rid),r=fl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Qn(r)?null:{rid:t,event:r}}function fl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function Bi(e){return e!=null}function UO(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function FO(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function j_(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function V_(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+j_(r,a)*3+j_(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 VO(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||Cr(a))continue;let c=K_({...V_(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*KO(i.kind))}return er(o*.35)}function KO(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 K_(e){return{...e,lexical:er(e.lexical),tags:er(e.tags),kind:er(e.kind),connections:er(e.connections),vector:er(e.vector),total:er(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function er(e){return Math.round(e*1e3)/1e3}function HO(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 WO(e,t){let r=t.map(GO),n=JO(t),o=YO(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:QO(e,r,n,o)}}function GO(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 JO(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 YO(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 QO(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
73
- `);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}]`:""}; ${XO(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(`
74
- `)}function XO(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(Bi);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function M_(e){return`artifact.hash.${e}`}function L_(e,t,r){return`connection.${e}.${r}.${t}`}function q_(){return`model-tier-bandit.v${1}`}function B_(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function eI(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function tI(e=process.cwd()){let t=await u_(e);if(d_(t))try{return{config:t,store:await f_(t),project:H_(t.rootDir)}}catch(n){let o=zi(t.rootDir);if(await Vn(o.socketPath,50))throw n}let r=await Zi.open({uri:t.connectionString,autoLinker:s_()});return{config:t,store:r,project:H_(t.rootDir)}}async function be(e,t=process.cwd()){let r=await tI(t);try{return await e(r)}finally{await r.store.close()}}function oI(e){return mt(e)}async function G_(e,t){if(e!=="SessionStart")return{};let r=await be(async({config:o,store:i})=>(await i.status(),o)),n=W_(r.rootDir,".red","brain","sessions");return await rI(n,{recursive:!0}),await nI(W_(n,"last-session.json"),oI({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()}),"utf8"),{}}var Ui=class{map({event:t,sourceAgent:r}){return{title:iI(t),content:sI(t),kind:"event",tags:aI(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:J_(t),metadata:cI(t)}}};function J_(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${al(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function iI(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 sI(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(`
75
- `)||JSON.stringify(e.raw)}function aI(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function cI(e){let t={event_key:J_(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 Fi(e){let t=new Ui,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 tr=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Q_(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new tr("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new tr("brain_act requires a non-empty message");let o=t.connect??(a=>Yt.connect(a)),i=t.process??uI(t.env??process.env),s;try{s=await o(i)}catch(a){throw new tr(`brain_act could not reach the channel bridge: ${Y_(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new tr(`brain_act could not send to "${r}": ${Y_(c)}`,{cause:c})}if(!a.ok)throw new tr(`brain_act could not send to "${r}": ${lI(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function uI(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 lI(e){return dI(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function dI(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 Y_(e){return e instanceof Error?e.message:String(e)}import{createServer as fI}from"node:http";async function tw(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:pl(n,"supports"),contradicts:pl(n,"contradicts"),depends_on:pl(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=>pI(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=>mI(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 rw(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:hI(e)}}async function nw(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=fI((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
76
- `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function pI(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:_I(e.properties.content)}}function mI(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 hI(e){return`<!doctype html>
79
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function el(e,t){return`${tl(e)}.${tO(t)}`}function tl(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 tO(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function rO(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 P_(e){return`'${String(e).replace(/'/g,"''")}'`}var Hn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${gt(t)}`})}push(t,r,n={}){let o=iO(n);return this.client.call("query",{sql:`QUEUE PUSH ${gt(t)} ${sO(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${gt(t)}${nl(r)}`});return rl(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${gt(t)}${nl(r)}`});return rl(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${gt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${gt(t)}`})}async readWait(t,r,n={}){let o=nO(t,r,n),i=await this.client.call("query",{sql:o});return rl(i)}};function nO(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=gt(e),a=gt(t),c=o!=null?` GROUP ${gt(o)}`:"",l=i!=null?nl(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function gt(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 nl(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 oO(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function iO(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 ${oO(e.priority)}`),e.key!=null&&(t+=` KEY ${ol(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${ol(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function sO(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?ol(e):JSON.stringify(e)}function ol(e){return`'${String(e).replace(/'/g,"''")}'`}function rl(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Wn=class{constructor(t){this.db=t}async insert(t,r){z_(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ni(t)} DOCUMENT VALUES (${uO(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=aO(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 ${Ni(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){z_(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])=>`${O_(c)} = ${lO(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ni(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 ${Ni(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function z_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function aO(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 Ni(e){return String(e).split(".").map(O_).join(".")}function O_(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 cO(e){return I_(JSON.stringify(e))}function uO(e){return JSON.stringify(e)}function lO(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?cO(e):I_(e)}function I_(e){return`'${String(e).replace(/'/g,"''")}'`}var Gn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){fO(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(A_).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${At(o)} ${At(t)} = ${dO(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${At(n)} ${At(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${At(n)} ${At(t)}`})}};function dO(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${At(r)}.${At(n)})`}return pO(e)}function fO(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 At(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 pO(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):A_(e)}function A_(e){return`'${String(e).replace(/'/g,"''")}'`}var Jn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){mO(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(N_).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Mr(o)}.${Mr(t)} = ${hO(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Mr(n)}.${Mr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Mr(n)}.${Mr(t)}`})}};function mO(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 Mr(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 hO(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):N_(e)}function N_(e){return`'${String(e).replace(/'/g,"''")}'`}async function D_(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(gO)}async function j_(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${_O(t)}`)).rows??[]).some(n=>n.name===String(t))}var Yn=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(C_).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${C_(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 gO(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function C_(e){return String(e).split(".").map(yO).join(".")}function yO(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 _O(e){return`'${String(e).replace(/'/g,"''")}'`}var wO="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",vO="1.0",q_="1.0.9",M_="NESTED_TX_NOT_SUPPORTED";async function B_(e,t={}){let r=Xu(e);if(RO(r),r.kind==="embedded"){let n=TO(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=EO(r),i=t.binary??T_(),s=await S_(i,o),a=new Ai(s);return await a.call("version",{}),new sl(a,{transport:"embedded"})}}function L_(e){return bO(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:$O(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&SO(e)?{$uuid:e}:e}function bO(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 xO(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(L_):e.map(L_)}function $O(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 kO(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 SO(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ci(e){if(Array.isArray(e))return e.map(Ci);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return kO(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]=Ci(o);return r}return e}function EO(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function TO(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 RO(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",wO)}var Di=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 al()}},il=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw al();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 Di(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){Z_(r,n)}throw r}}},sl=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=vO,this.cache=new Kn(t,this.transport),this.queue=new Hn(t),this.queues=this.queue,this.documents=new Wn(this);let n=new jr(t);this.kv=Object.assign((o="kv_default")=>new jr(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 Gn(t,o),this.vault=(o="red.vault")=>new Jn(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=xO(r);return n==null?this.client.call("query",{sql:t}).then(Ci):this.client.call("query",{sql:t,params:n}).then(Ci)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return PO(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 zO(n,r.length)}tx(){return new il(this)}async transaction(t){if(this.inTransaction)throw al();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 Di(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){Z_(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return j_(this,t)}list(){return D_(this)}from(t){return new Yn(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 al(){return new z(M_,`${M_}: nested transactions are not supported on one connection`)}function Z_(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function PO(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${q_} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function zO(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 >= ${q_} 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 Qn(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"&&OO(t.chosenOption)&&IO(t.outcome)&&AO(t.cost)}function OO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function IO(e){return e==="success"||e==="failure"||e==="escalated"}function AO(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 NO}from"node:crypto";function cl(e){return NO("sha256").update(e).digest("hex")}function U_(e){return cl(JSON.stringify(e))}function F_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var ul="unknown",ji=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=fl(t.from),i=fl(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>CO(p,n)).filter(p=>p!=null).filter(p=>jO(p,t)).filter(p=>MO(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=BO(c,l,r),f=[V_(null,s,u,r)];if(t.groupBy){let m=[...LO(s,t.groupBy).entries()].map(([h,_])=>V_(h,_,u,r)).sort((h,_)=>_.total-h.total||UO(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function CO(e,t){let r=e.properties.metadata??{},n=DO(e,r,t);return n==null?null:{ts:n,platform:ll(r,"platform")??ul,eventType:ll(r,"event_type")??ul,target:ll(r,"target")??ul}}function DO(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:fl(t.timestamp)??n}function ll(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function jO(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 MO(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function LO(e,t){let r=new Map;for(let n of e){let o=qO(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function qO(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function V_(e,t,r,n){let o=new Map;for(let s of t){let a=dl(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 BO(e,t,r){if(e==null||t==null)return[];let n=[],o=dl(e,r),i=dl(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=ZO(o,r),s++;return n}function dl(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 ZO(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 fl(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 UO(e,t){return String(e??"").localeCompare(String(t??""))}var FO=["validate","simple","complex","think"];var VO={validate:1,simple:.85,complex:.65,think:.45};function KO(){return{schemaVersion:1,buckets:{}}}function H_(e,t={}){let r=QO(t.initial??KO());for(let n of e)HO(r,n,t);return r}function HO(e,t,r={}){let n=(r.tierForEvent??WO)(t);if(!n)return e;let i=JO(e,t.taskClass).arms[n],s=GO(t,n);return i.posterior.alpha=K_(i.posterior.alpha+s),i.posterior.beta=K_(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 WO(e){let t=e.chosenOption.kind;if(XO(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 GO(e,t){return e.outcome!=="success"?0:VO[t]}function JO(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=YO(),e.buckets[r]}function YO(){return{arms:{validate:Mi(),simple:Mi(),complex:Mi(),think:Mi()}}}function Mi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function QO(e){return JSON.parse(JSON.stringify(e))}function XO(e){return FO.includes(e)}function K_(e){return Math.round(e*1e3)/1e3}var Li=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],W_={contact:"person"},qi=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Xe={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Zi=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 B_(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 ${Xe.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Xe.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Xe.outcomeEvents}`)}kv(){return this.db.kv(Xe.kv)}async capture(t){let r=tw(t.kind??"note"),n=Date.now(),o=nI(t.tags??[]),i=U_([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=`${F_(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 ${Xe.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(J_(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 ${Xe.artifacts}`);this.artifactCache=t.rows.map(eI).filter(Bi)}return this.artifactCache}async search(t,r=10,n={}){let o=oI(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=nw(u,o),f=ow({...d,connections:iI(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:aI(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=rw(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 ${Xe.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(Y_(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 ${Xe.connections}`);this.connectionCache=t.rows.map(tI).filter(Bi)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:mI(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new ji(r).events(t)}async appendOutcomeEvent(t){if(!Qn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Xe.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 ${Xe.outcomeEvents}`);this.outcomeEventCache=t.rows.map(rI).filter(Bi).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(Q_());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return X_(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!X_(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(Q_(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=H_(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=>!Cr(i.artifact)).slice(0,r);return cI(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(J_(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Y_(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||Cr(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=y_(t),i=new Set([t.rid]);for(let d of r)Cr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Cr(d.artifact)).map(d=>({artifact:Hu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Hu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Ku},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!Wu(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 tw(e){let r=W_[e]??e;if(Li.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function rw(e){if(qi.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function eI(e){let t=Number(e.red_entity_id??e.rid),r=pl(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:tw(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 tI(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:rw(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:pl(e.properties??e.PROPERTIES)}}function rI(e){let t=Number(e.red_entity_id??e.rid),r=pl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Qn(r)?null:{rid:t,event:r}}function pl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function Bi(e){return e!=null}function nI(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function oI(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function G_(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function nw(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+G_(r,a)*3+G_(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 iI(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||Cr(a))continue;let c=ow({...nw(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*sI(i.kind))}return er(o*.35)}function sI(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 ow(e){return{...e,lexical:er(e.lexical),tags:er(e.tags),kind:er(e.kind),connections:er(e.connections),vector:er(e.vector),total:er(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function er(e){return Math.round(e*1e3)/1e3}function aI(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 cI(e,t){let r=t.map(uI),n=lI(t),o=dI(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:fI(e,r,n,o)}}function uI(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 lI(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 dI(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 fI(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
80
+ `);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}]`:""}; ${pI(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(`
81
+ `)}function pI(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(Bi);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function J_(e){return`artifact.hash.${e}`}function Y_(e,t,r){return`connection.${e}.${r}.${t}`}function Q_(){return`model-tier-bandit.v${1}`}function X_(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function mI(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function hI(e=process.cwd()){let t=await b_(e);if($_(t))try{return{config:t,store:await k_(t),project:iw(t.rootDir)}}catch(n){let o=zi(t.rootDir);if(await Vn(o.socketPath,50))throw n}let r=await Zi.open({uri:t.connectionString,autoLinker:__()});return{config:t,store:r,project:iw(t.rootDir)}}async function be(e,t=process.cwd()){let r=await hI(t);try{return await e(r)}finally{await r.store.close()}}function _I(e){return Qe(e)}async function aw(e,t){if(e!=="SessionStart")return{};let r=await be(async({config:o,store:i})=>(await i.status(),o)),n=sw(r.rootDir,".red","brain","sessions");return await gI(n,{recursive:!0}),await yI(sw(n,"last-session.json"),_I({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()}),"utf8"),{}}var Ui=class{map({event:t,sourceAgent:r}){return{title:wI(t),content:vI(t),kind:"event",tags:bI(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:cw(t),metadata:xI(t)}}};function cw(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${cl(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function wI(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 vI(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(`
82
+ `)||JSON.stringify(e.raw)}function bI(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function xI(e){let t={event_key:cw(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 Fi(e){let t=new Ui,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 tr=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function lw(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new tr("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new tr("brain_act requires a non-empty message");let o=t.connect??(a=>Yt.connect(a)),i=t.process??$I(t.env??process.env),s;try{s=await o(i)}catch(a){throw new tr(`brain_act could not reach the channel bridge: ${uw(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new tr(`brain_act could not send to "${r}": ${uw(c)}`,{cause:c})}if(!a.ok)throw new tr(`brain_act could not send to "${r}": ${kI(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function $I(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 kI(e){return SI(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function SI(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 uw(e){return e instanceof Error?e.message:String(e)}import{createServer as EI}from"node:http";async function pw(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:ml(n,"supports"),contradicts:ml(n,"contradicts"),depends_on:ml(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=>TI(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=>RI(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 mw(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:PI(e)}}async function hw(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=EI((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
83
+ `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function TI(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:II(e.properties.content)}}function RI(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 PI(e){return`<!doctype html>
77
84
  <html lang="en">
78
85
  <head>
79
86
  <meta charset="utf-8">
@@ -265,44 +272,44 @@ ${o}`),n.join(`
265
272
  <section>
266
273
  <h2>Event KPIs</h2>
267
274
  <div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
268
- ${X_(e.kpis.events_by_platform,"Platform")}
269
- ${X_(e.kpis.events_by_type,"Event type")}
275
+ ${dw(e.kpis.events_by_platform,"Platform")}
276
+ ${dw(e.kpis.events_by_type,"Event type")}
270
277
  </section>
271
278
  <section>
272
279
  <h2>Recent Decisions</h2>
273
280
  <div class="feed">
274
- ${e.recent_decisions.length===0?ew("No decision artifacts captured yet."):e.recent_decisions.map(gI).join("")}
281
+ ${e.recent_decisions.length===0?fw("No decision artifacts captured yet."):e.recent_decisions.map(zI).join("")}
275
282
  </div>
276
283
  </section>
277
284
  </div>
278
285
  <section>
279
286
  <h2>Recent Connections</h2>
280
287
  <div class="feed">
281
- ${e.recent_connections.length===0?ew("No graph connections captured yet."):e.recent_connections.map(yI).join("")}
288
+ ${e.recent_connections.length===0?fw("No graph connections captured yet."):e.recent_connections.map(OI).join("")}
282
289
  </div>
283
290
  </section>
284
291
  </main>
285
292
  <footer class="meta">${ae(e.attribution.red_hermes)}</footer>
286
- <script id="brain-dashboard-data" type="application/json">${wI(e)}</script>
293
+ <script id="brain-dashboard-data" type="application/json">${AI(e)}</script>
287
294
  </body>
288
- </html>`}function Lr(e,t,r){return`<div class="metric"><span>${ae(e)}</span><strong>${t}</strong><div class="meta">${ae(r)}</div></div>`}function X_(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 gI(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">
295
+ </html>`}function Lr(e,t,r){return`<div class="metric"><span>${ae(e)}</span><strong>${t}</strong><div class="meta">${ae(r)}</div></div>`}function dw(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 zI(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">
289
296
  <h3>${ae(e.title)}</h3>
290
297
  <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>
291
298
  <p class="meta">${ae(e.excerpt)}</p>
292
299
  ${r}
293
- </article>`}function yI(e){return`<article class="item">
300
+ </article>`}function OI(e){return`<article class="item">
294
301
  <h3><span class="edge ${ae(e.kind)}">${ae(e.kind)}</span> ${ae(e.from.title)} -> ${ae(e.to.title)}</h3>
295
302
  <div class="meta">#${e.rid} - ${ae(e.created_at)}${e.reason?` - ${ae(e.reason)}`:""}</div>
296
- </article>`}function ew(e){return`<div class="empty">${ae(e)}</div>`}function pl(e,t){return e.filter(r=>r.kind===t).length}function _I(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"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function wI(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as xI,readFile as $I,writeFile as kI}from"node:fs/promises";import{dirname as SI}from"node:path";function ow(e){return mt(e,{keyedMapCollapse:!0})}var vI=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],bI=[{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"}],JZ=[...vI,...bI];async function iw(e){let t=await Fi({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 sw(e){try{let r=(await $I(e,"utf8")).trim();if(!r)return{};try{return JSON.parse(r)}catch{return pt(r)}}catch(t){if(t.code==="ENOENT")return{};throw t}}async function aw(e,t){await xI(SI(e),{recursive:!0}),await kI(e,`${ow(t)}
297
- `,"utf8")}var cw={"=":"data",":=":{to:"data",typed:!0},":":"meta"},EI=/^[a-z][a-z0-9+.-]*:\/\//i;function TI(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 RI(e=cw){return Object.entries(e).map(([t,r])=>TI(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function PI(e){return/^-\d+(\.\d+)?$/.test(e)}function Xn(e){return!(!e||e.startsWith("-")&&!PI(e))}function Vi(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 uw(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=>uw(r.trim())):e}function rr(e,t){switch(t){case"boolean":return zI(e);case"number":return OI(e);case"array":return e.split(",").map(r=>Vi(r.trim()));case"string":default:return e}}function zI(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function OI(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 Nt(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function II(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 AI(e){let t=[],r=CI(e);if(t.push(Y("section-header","Usage:"),Y("text"," "),Y("usage-text",r),Y("newline",`
303
+ </article>`}function fw(e){return`<div class="empty">${ae(e)}</div>`}function ml(e,t){return e.filter(r=>r.kind===t).length}function II(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"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function AI(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as DI,readFile as jI,writeFile as MI}from"node:fs/promises";import{dirname as LI}from"node:path";function gw(e){return Qe(e,{keyedMapCollapse:!0})}var NI=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],CI=[{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"}],pU=[...NI,...CI];async function yw(e){let t=await Fi({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 _w(e){try{let r=(await jI(e,"utf8")).trim();if(!r)return{};try{return JSON.parse(r)}catch{return Ye(r)}}catch(t){if(t.code==="ENOENT")return{};throw t}}async function ww(e,t){await DI(LI(e),{recursive:!0}),await MI(e,`${gw(t)}
304
+ `,"utf8")}var vw={"=":"data",":=":{to:"data",typed:!0},":":"meta"},qI=/^[a-z][a-z0-9+.-]*:\/\//i;function BI(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 ZI(e=vw){return Object.entries(e).map(([t,r])=>BI(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function UI(e){return/^-\d+(\.\d+)?$/.test(e)}function Xn(e){return!(!e||e.startsWith("-")&&!UI(e))}function Vi(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 bw(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=>bw(r.trim())):e}function rr(e,t){switch(t){case"boolean":return FI(e);case"number":return VI(e);case"array":return e.split(",").map(r=>Vi(r.trim()));case"string":default:return e}}function FI(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function VI(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 Nt(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function KI(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 HI(e){let t=[],r=GI(e);if(t.push(Y("section-header","Usage:"),Y("text"," "),Y("usage-text",r),Y("newline",`
298
305
  `),Y("newline",`
299
306
  `)),e.positional&&e.positional.length>0){t.push(Y("section-header","Arguments:"),Y("newline",`
300
307
  `));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",`
301
308
  `),Y("indent"," "),Y("option-description",n.description),Y("newline",`
302
309
  `))}t.push(Y("newline",`
303
310
  `))}if(e.options&&Object.keys(e.options).length>0){t.push(Y("section-header","Options:"),Y("newline",`
304
- `));let n=DI(e.options);t.push(...n)}return t}function NI(e,t){let r=AI(e);return II(r,t)}function CI(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 DI(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",`
305
- `))}return r}function lw(e){let t=UI(e.options??{},e.autoShort??!1),r=RI(e.separators??cw);return{schema:e,parse(n){return jI(n,e,t,r)},help(){return NI(e,e.formatter)}}}function jI(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?rr(m,f.type):m),c++}o.positional[f.name]=p,s++}else{let p=f.type?rr(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=BI(u,c,e,o,r,t);continue}if(u.startsWith("-")&&u.length>1&&!WI(u)){c=ZI(u,c,e,o,r,t);continue}let d=MI(u,n);if(d){let{key:f,value:p,config:m}=d,h=o,_=h[m.to]??(h[m.to]={});_[f]=m.typed?uw(p):Nt(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?rr(h,f.type):h),c++}o.positional[f.name]=m,s++;continue}let p=f.type?rr(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 VI(o,t,r),KI(o,t,a),HI(o,t,r),o}function MI(e,t){if(EI.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(LI(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(qI(o,i,r))return{key:o,value:i,config:r}}}return null}function LI(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function qI(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 BI(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 Ki(l,u,t+1,n,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let c=r[t+1];return Xn(c)?Ki(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 ZI(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=ml(c,o);return u?Ki(u.name,l,t+1,n,o,i):(i.strict?n.errors.push(`Unknown option: -${c}`):i.allowUnknown!==!1&&(n.options[c]=Vi(Nt(l))),t+1)}if(s.length===1){let a=ml(s,o);if(a){if(a.type!=="boolean"){let c=r[t+1];return Xn(c)?Ki(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(Xn(c))return n.options[s]=Vi(Nt(c)),t+2;n.options[s]=!0}return t+1}for(let a of s){let c=ml(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 Ki(e,t,r,n,o,i){let s=o.get(e);if(s){if(s.choices){let c=s.type?rr(Nt(t),s.type):Nt(t);if(!s.choices.includes(c))return n.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${s.choices.join(", ")}`),r}let a=s.type?rr(Nt(t),s.type):Nt(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]=Vi(Nt(t)));return r}function UI(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=FI(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 FI(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 ml(e,t){for(let r of t.values())if(r.short===e||r.aliases.includes(e))return r}function VI(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?rr(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 KI(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 HI(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 WI(e){return/^-\d+(\.\d+)?$/.test(e)}var eo=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 GI(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 JI(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&&Xn(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 dw(e,t,r={}){let o=lw({options:GI(t),separators:{},allowUnknown:!0}).parse([...e]),i={},s=JI(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 eo(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 to=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 fw(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 to(r,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:n}}var F=e=>e;function ro(e){return t=>{let r=Number(t);if(!Number.isFinite(r))throw new Error(`--${e} must be a number`);return r}}var pw={version:{kind:"boolean",aliases:["v"]},help:{kind:"boolean",aliases:["h"]},json:{kind:"boolean"}},no={},mw={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}},hw={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:ro("limit")}},gw={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:ro("limit")},json:{kind:"boolean"}},yw={from:{kind:"value",coerce:F},to:{kind:"value",coerce:F},kind:{kind:"value",coerce:F},reason:{kind:"value",coerce:F}},_w={target:{kind:"value",coerce:F},message:{kind:"value",coerce:F}},ww={runner:{kind:"value",coerce:F}},vw={"after-cursor":{kind:"value",aliases:["cursor"],coerce:F},"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:ro("limit")}},bw={"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:ro("limit")},state:{kind:"value",coerce:F}},xw={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}},$w={out:{kind:"value",coerce:F},host:{kind:"value",coerce:F},port:{kind:"value",coerce:ro("port")},json:{kind:"boolean"},serve:{kind:"boolean"}},kw={root:{kind:"value",coerce:F}},YI={help:{},version:{},init:{},status:{},capture:{},search:{},think:{aliases:["query"]},get:{},link:{},backlinks:{},act:{},hook:{},"ingest-events":{},"schedule-ingest":{},kpi:{aliases:["kpis"]},dashboard:{},"outcome-event":{}},QI={commands:YI,default:"help",keepArgvOnDefault:!0,errorOnUnknownCommand:!0};function Sw(e){try{return fw(e,QI)}catch(t){throw t instanceof to?new Error(`unknown brain command: ${t.token} \u2014 run \`brain help\` for the command list`):t}}function he(e,t){try{return dw(e,t,{unknownFlags:"error"})}catch(r){throw r instanceof eo?new Error(`unknown brain flag: ${r.flag} \u2014 run \`brain help\` for usage`):r}}var Ew=`brain commands:
311
+ `));let n=JI(e.options);t.push(...n)}return t}function WI(e,t){let r=HI(e);return KI(r,t)}function GI(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 JI(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",`
312
+ `))}return r}function xw(e){let t=nA(e.options??{},e.autoShort??!1),r=ZI(e.separators??vw);return{schema:e,parse(n){return YI(n,e,t,r)},help(){return WI(e,e.formatter)}}}function YI(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?rr(m,f.type):m),c++}o.positional[f.name]=p,s++}else{let p=f.type?rr(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=tA(u,c,e,o,r,t);continue}if(u.startsWith("-")&&u.length>1&&!cA(u)){c=rA(u,c,e,o,r,t);continue}let d=QI(u,n);if(d){let{key:f,value:p,config:m}=d,h=o,_=h[m.to]??(h[m.to]={});_[f]=m.typed?bw(p):Nt(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?rr(h,f.type):h),c++}o.positional[f.name]=m,s++;continue}let p=f.type?rr(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 iA(o,t,r),sA(o,t,a),aA(o,t,r),o}function QI(e,t){if(qI.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(XI(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(eA(o,i,r))return{key:o,value:i,config:r}}}return null}function XI(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function eA(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 tA(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 Ki(l,u,t+1,n,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let c=r[t+1];return Xn(c)?Ki(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 rA(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=hl(c,o);return u?Ki(u.name,l,t+1,n,o,i):(i.strict?n.errors.push(`Unknown option: -${c}`):i.allowUnknown!==!1&&(n.options[c]=Vi(Nt(l))),t+1)}if(s.length===1){let a=hl(s,o);if(a){if(a.type!=="boolean"){let c=r[t+1];return Xn(c)?Ki(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(Xn(c))return n.options[s]=Vi(Nt(c)),t+2;n.options[s]=!0}return t+1}for(let a of s){let c=hl(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 Ki(e,t,r,n,o,i){let s=o.get(e);if(s){if(s.choices){let c=s.type?rr(Nt(t),s.type):Nt(t);if(!s.choices.includes(c))return n.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${s.choices.join(", ")}`),r}let a=s.type?rr(Nt(t),s.type):Nt(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]=Vi(Nt(t)));return r}function nA(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=oA(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 oA(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 hl(e,t){for(let r of t.values())if(r.short===e||r.aliases.includes(e))return r}function iA(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?rr(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 sA(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 aA(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 cA(e){return/^-\d+(\.\d+)?$/.test(e)}var eo=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 uA(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 lA(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&&Xn(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 $w(e,t,r={}){let o=xw({options:uA(t),separators:{},allowUnknown:!0}).parse([...e]),i={},s=lA(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 eo(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 to=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 kw(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 to(r,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:n}}var F=e=>e;function ro(e){return t=>{let r=Number(t);if(!Number.isFinite(r))throw new Error(`--${e} must be a number`);return r}}var Sw={version:{kind:"boolean",aliases:["v"]},help:{kind:"boolean",aliases:["h"]},json:{kind:"boolean"}},no={},Ew={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}},Tw={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:ro("limit")}},Rw={query:{kind:"value",coerce:F},limit:{kind:"value",coerce:ro("limit")},json:{kind:"boolean"}},Pw={from:{kind:"value",coerce:F},to:{kind:"value",coerce:F},kind:{kind:"value",coerce:F},reason:{kind:"value",coerce:F}},zw={target:{kind:"value",coerce:F},message:{kind:"value",coerce:F}},Ow={runner:{kind:"value",coerce:F}},Iw={"after-cursor":{kind:"value",aliases:["cursor"],coerce:F},"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:ro("limit")}},Aw={"session-key":{kind:"value",aliases:["session"],coerce:F},limit:{kind:"value",coerce:ro("limit")},state:{kind:"value",coerce:F}},Nw={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}},Cw={out:{kind:"value",coerce:F},host:{kind:"value",coerce:F},port:{kind:"value",coerce:ro("port")},json:{kind:"boolean"},serve:{kind:"boolean"}},Dw={root:{kind:"value",coerce:F}},dA={help:{},version:{},init:{},status:{},capture:{},search:{},think:{aliases:["query"]},get:{},link:{},backlinks:{},act:{},hook:{},"ingest-events":{},"schedule-ingest":{},kpi:{aliases:["kpis"]},dashboard:{},"outcome-event":{}},fA={commands:dA,default:"help",keepArgvOnDefault:!0,errorOnUnknownCommand:!0};function jw(e){try{return kw(e,fA)}catch(t){throw t instanceof to?new Error(`unknown brain command: ${t.token} \u2014 run \`brain help\` for the command list`):t}}function he(e,t){try{return $w(e,t,{unknownFlags:"error"})}catch(r){throw r instanceof eo?new Error(`unknown brain flag: ${r.flag} \u2014 run \`brain help\` for usage`):r}}var Mw=`brain commands:
306
313
  init
307
314
  status
308
315
  capture [text] --title <title> --kind <${Li.join("|")}> --tag <tag>
@@ -322,6 +329,6 @@ brain flags (answered before any command, and before config or the store):
322
329
  -v, --version print the build version
323
330
  --json with --version: print the structured build info
324
331
  -h, --help show this help
325
- `;async function nA(){let{command:e,args:t}=Sw(process.argv.slice(2));switch(e){case"help":case"version":{let{values:r}=he(t,pw);if(e==="version"||r.version===!0){oA(r.json===!0);return}console.log(Ew);return}case"init":he(t,no),await be(async({config:r,store:n})=>{let o=await n.status();Ee({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":he(t,no),await be(async({config:r,store:n})=>{Ee({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await sA(t);return;case"search":await aA(t);return;case"think":await cA(t);return;case"get":await uA(t);return;case"link":await lA(t);return;case"backlinks":await dA(t);return;case"act":await gA(t);return;case"hook":await yA(t);return;case"ingest-events":await pA(t);return;case"schedule-ingest":await fA(t);return;case"kpi":await mA(t);return;case"dashboard":await hA(t);return;case"outcome-event":await iA(t);return}}function oA(e){let t=_l("brain");process.stdout.write(e?`${JSON.stringify(t)}
326
- `:`${wl(t)}
327
- `)}async function iA(e){let{values:t,positionals:r}=he(e,kw);if(r[0]!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=await _A(),o=JSON.parse(n);if(!Qn(o))throw new Error("invalid brain outcome event");await be(async({store:i})=>{Ee(await i.appendOutcomeEvent(o))},t.root??process.cwd())}async function sA(e){let{values:t,positionals:r}=he(e,mw),n=(t.title??r.join(" ").slice(0,80))||"Untitled artifact",o=t.content??(t.file?await XI(t.file,"utf8"):r.join(" "));if(!o.trim())throw new Error("brain capture requires content, --content, or --file");await be(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()});Ee(s)})}async function aA(e){let{values:t,positionals:r}=he(e,hw),n=t.query??r.join(" ");if(!n)throw new Error("brain search requires a query");let o=t.limit??10;await be(async({store:i})=>Ee(await i.search(n,o)))}async function cA(e){let{values:t,positionals:r}=he(e,gw),n=t.query??r.join(" ");if(!n)throw new Error("brain think requires a query");let o=t.limit??8;await be(async({store:i})=>{let s=await i.think(n,o);t.json===!0?Ee(s):console.log(s.answer)})}async function uA(e){let{positionals:t}=he(e,no),r=t[0];if(!r)throw new Error("brain get requires a rid or artifact id");await be(async({store:n})=>{let o=await n.getArtifact(Hi(r));if(!o)throw new Error(`Brain artifact not found: ${r}`);Ee(o)})}async function lA(e){let{values:t}=he(e,yw),r=t.from,n=t.to;if(!r||!n)throw new Error("brain link requires --from and --to");await be(async({store:o})=>{Ee(await o.link({from:Hi(r),to:Hi(n),kind:t.kind??"related_to",reason:t.reason}))})}async function dA(e){let{positionals:t}=he(e,no),r=t[0];if(!r)throw new Error("brain backlinks requires a rid or artifact id");await be(async({store:n})=>Ee(await n.backlinks(Hi(r))))}async function fA(e){let{values:t}=he(e,bw),r=await Yt.connect();try{await be(async({config:n,store:o})=>{let i=t.state??Tw(n.rootDir,".red","brain","ingestion-state.json"),s=await sw(i),a=await iw({bridge:r,store:o,state:s,sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.schedule-ingest"});await aw(i,a.state),Ee(a)})}finally{await r.close().catch(()=>{})}}async function pA(e){let{values:t}=he(e,vw),r=await Yt.connect();try{await be(async({store:n})=>{let o=await Fi({bridge:r,store:n,afterCursor:t["after-cursor"],sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.ingest-events"});Ee(o)})}finally{await r.close().catch(()=>{})}}async function mA(e){let{values:t}=he(e,xw);await be(async({store:r})=>{Ee(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 hA(e){let{values:t}=he(e,$w),r=await be(async({config:o,store:i,project:s})=>{let a=await tw(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:rw(a),defaultOut:Tw(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){Ee(r.dashboard);return}if(t.serve===!0){let o=t.host??"127.0.0.1",i=t.port??4738,s=await nw(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 eA(rA(n),{recursive:!0}),await tA(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function gA(e){let{values:t,positionals:r}=he(e,_w),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>");Ee(await Q_({target:n,message:o}))}async function yA(e){let{values:t,positionals:r}=he(e,ww),n=r[0]??"SessionStart",o=t.runner??"unknown";Ee(await G_(n,o))}function Hi(e){return/^\d+$/.test(e)?Number(e):e}function Ee(e){console.log(JSON.stringify(e,null,2))}async function _A(){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")}nA().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
332
+ `;async function yA(){let{command:e,args:t}=jw(process.argv.slice(2));switch(e){case"help":case"version":{let{values:r}=he(t,Sw);if(e==="version"||r.version===!0){_A(r.json===!0);return}console.log(Mw);return}case"init":he(t,no),await be(async({config:r,store:n})=>{let o=await n.status();Ee({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":he(t,no),await be(async({config:r,store:n})=>{Ee({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await vA(t);return;case"search":await bA(t);return;case"think":await xA(t);return;case"get":await $A(t);return;case"link":await kA(t);return;case"backlinks":await SA(t);return;case"act":await zA(t);return;case"hook":await OA(t);return;case"ingest-events":await TA(t);return;case"schedule-ingest":await EA(t);return;case"kpi":await RA(t);return;case"dashboard":await PA(t);return;case"outcome-event":await wA(t);return}}function _A(e){let t=wl("brain");process.stdout.write(e?`${JSON.stringify(t)}
333
+ `:`${vl(t)}
334
+ `)}async function wA(e){let{values:t,positionals:r}=he(e,Dw);if(r[0]!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=await IA(),o=JSON.parse(n);if(!Qn(o))throw new Error("invalid brain outcome event");await be(async({store:i})=>{Ee(await i.appendOutcomeEvent(o))},t.root??process.cwd())}async function vA(e){let{values:t,positionals:r}=he(e,Ew),n=(t.title??r.join(" ").slice(0,80))||"Untitled artifact",o=t.content??(t.file?await pA(t.file,"utf8"):r.join(" "));if(!o.trim())throw new Error("brain capture requires content, --content, or --file");await be(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()});Ee(s)})}async function bA(e){let{values:t,positionals:r}=he(e,Tw),n=t.query??r.join(" ");if(!n)throw new Error("brain search requires a query");let o=t.limit??10;await be(async({store:i})=>Ee(await i.search(n,o)))}async function xA(e){let{values:t,positionals:r}=he(e,Rw),n=t.query??r.join(" ");if(!n)throw new Error("brain think requires a query");let o=t.limit??8;await be(async({store:i})=>{let s=await i.think(n,o);t.json===!0?Ee(s):console.log(s.answer)})}async function $A(e){let{positionals:t}=he(e,no),r=t[0];if(!r)throw new Error("brain get requires a rid or artifact id");await be(async({store:n})=>{let o=await n.getArtifact(Hi(r));if(!o)throw new Error(`Brain artifact not found: ${r}`);Ee(o)})}async function kA(e){let{values:t}=he(e,Pw),r=t.from,n=t.to;if(!r||!n)throw new Error("brain link requires --from and --to");await be(async({store:o})=>{Ee(await o.link({from:Hi(r),to:Hi(n),kind:t.kind??"related_to",reason:t.reason}))})}async function SA(e){let{positionals:t}=he(e,no),r=t[0];if(!r)throw new Error("brain backlinks requires a rid or artifact id");await be(async({store:n})=>Ee(await n.backlinks(Hi(r))))}async function EA(e){let{values:t}=he(e,Aw),r=await Yt.connect();try{await be(async({config:n,store:o})=>{let i=t.state??Lw(n.rootDir,".red","brain","ingestion-state.json"),s=await _w(i),a=await yw({bridge:r,store:o,state:s,sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.schedule-ingest"});await ww(i,a.state),Ee(a)})}finally{await r.close().catch(()=>{})}}async function TA(e){let{values:t}=he(e,Iw),r=await Yt.connect();try{await be(async({store:n})=>{let o=await Fi({bridge:r,store:n,afterCursor:t["after-cursor"],sessionKey:t["session-key"],limit:t.limit,sourceAgent:"brain.ingest-events"});Ee(o)})}finally{await r.close().catch(()=>{})}}async function RA(e){let{values:t}=he(e,Nw);await be(async({store:r})=>{Ee(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 PA(e){let{values:t}=he(e,Cw),r=await be(async({config:o,store:i,project:s})=>{let a=await pw(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:mw(a),defaultOut:Lw(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){Ee(r.dashboard);return}if(t.serve===!0){let o=t.host??"127.0.0.1",i=t.port??4738,s=await hw(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 mA(gA(n),{recursive:!0}),await hA(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function zA(e){let{values:t,positionals:r}=he(e,zw),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>");Ee(await lw({target:n,message:o}))}async function OA(e){let{values:t,positionals:r}=he(e,Ow),n=r[0]??"SessionStart",o=t.runner??"unknown";Ee(await aw(n,o))}function Hi(e){return/^\d+$/.test(e)?Number(e):e}function Ee(e){console.log(JSON.stringify(e,null,2))}async function IA(){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")}yA().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});