@reddb-io/red-skills 2.65.1 → 2.65.3

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 __=Object.create;var Ii=Object.defineProperty;var w_=Object.getOwnPropertyDescriptor;var b_=Object.getOwnPropertyNames;var v_=Object.getPrototypeOf,x_=Object.prototype.hasOwnProperty;var dt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Lu=(e,t)=>{for(var r in t)Ii(e,r,{get:t[r],enumerable:!0})},$_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of b_(t))!x_.call(e,o)&&o!==r&&Ii(e,o,{get:()=>t[o],enumerable:!(n=w_(t,o))||n.enumerable});return e};var Oi=(e,t,r)=>(r=e!=null?__(v_(e)):{},$_(t||!e||!e.__esModule?Ii(r,"default",{value:e,enumerable:!0}):r,e));var Xr=b(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Qr=class{};U._CodeOrName=Qr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ot=class extends Qr{constructor(t){if(super(),!U.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};U.Name=Ot;var Ce=class extends Qr{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 Ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Ce;U.nil=new Ce("");function fp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ys(r,t[n]),r.push(e[++n]);return new Ce(r)}U._=fp;var Qs=new Ce("+");function pp(e,...t){let r=[Yr(e[0])],n=0;for(;n<t.length;)r.push(Qs),Ys(r,t[n]),r.push(Qs,Yr(e[++n]));return Sv(r),new Ce(r)}U.str=pp;function Ys(e,t){t instanceof Ce?e.push(...t._items):t instanceof Ot?e.push(t):e.push(Pv(t))}U.addCodeArg=Ys;function Sv(e){let t=1;for(;t<e.length-1;){if(e[t]===Qs){let r=Ev(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Ev(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ot||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 Ot))return`"${e}${t.slice(1)}`}function Tv(e,t){return t.emptyStr()?e:e.emptyStr()?t:pp`${e}${t}`}U.strConcat=Tv;function Pv(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Yr(Array.isArray(e)?e.join(","):e)}function Rv(e){return new Ce(Yr(e))}U.stringify=Rv;function Yr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Yr;function zv(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new Ce(`.${e}`):fp`[${e}]`}U.getProperty=zv;function Iv(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new Ce(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=Iv;function Ov(e){return new Ce(e.toString())}U.regexpCode=Ov});var ta=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.ValueScope=Ee.ValueScopeName=Ee.Scope=Ee.varKinds=Ee.UsedValueState=void 0;var Se=Xr(),Xs=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},wo;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(wo||(Ee.UsedValueState=wo={}));Ee.varKinds={const:new Se.Name("const"),let:new Se.Name("let"),var:new Se.Name("var")};var bo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Se.Name?t:this.name(t)}name(t){return new Se.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ee.Scope=bo;var vo=class extends Se.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Se._)`.${new Se.Name(r)}[${n}]`}};Ee.ValueScopeName=vo;var Av=(0,Se._)`\n`,ea=class extends bo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Av:Se.nil}}get(){return this._scope}name(t){return new vo(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Se._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=Se.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,wo.Started);let u=r(l);if(u){let d=this.opts.es5?Ee.varKinds.var:Ee.varKinds.const;i=(0,Se._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Se._)`${i}${u}${this.opts._n}`;else throw new Xs(l);c.set(l,wo.Completed)})}return i}};Ee.ValueScope=ea});var C=b(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=Xr(),Ze=ta(),gt=Xr();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return gt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return gt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return gt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return gt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return gt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return gt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return gt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return gt.Name}});var So=ta();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return So.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return So.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return So.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return So.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 st=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ra=class extends st{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ze.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=tr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},xo=class extends st{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=tr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return ko(t,this.rhs)}},na=class extends xo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},oa=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ia=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},sa=class extends st{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},aa=class extends st{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=tr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},en=class extends st{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(Nv(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Ct(t,r.names),{})}},at=class extends en{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ca=class extends en{},er=class extends at{};er.kind="else";var At=class e extends at{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new er(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(mp(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=tr(this.condition,t,r),this}get names(){let t=super.names;return ko(t,this.condition),this.else&&Ct(t,this.else.names),t}};At.kind="if";var Nt=class extends at{};Nt.kind="for";var ua=class extends Nt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=tr(this.iteration,t,r),this}get names(){return Ct(super.names,this.iteration.names)}},la=class extends Nt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ze.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=ko(super.names,this.from);return ko(t,this.to)}},$o=class extends Nt{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=tr(this.iterable,t,r),this}get names(){return Ct(super.names,this.iterable.names)}},tn=class extends at{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};tn.kind="func";var rn=class extends en{render(t){return"return "+super.render(t)}};rn.kind="return";var da=class extends at{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Ct(t,this.catch.names),this.finally&&Ct(t,this.finally.names),t}},nn=class extends at{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};nn.kind="catch";var on=class extends at{render(t){return"finally"+super.render(t)}};on.kind="finally";var fa=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new Ze.Scope({parent:t}),this._nodes=[new ca]}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 ra(t,i,n)),i}const(t,r,n){return this._def(Ze.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ze.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ze.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new xo(t,r,n))}add(t,r){return this._leafNode(new na(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new aa(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 At(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new At(t))}else(){return this._elseNode(new er)}endIf(){return this._endBlockNode(At,er)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new ua(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ze.varKinds.var:Ze.varKinds.let){let s=this._scope.toName(t);return this._for(new la(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ze.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 $o("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ze.varKinds.var:Ze.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 $o("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Nt)}label(t){return this._leafNode(new oa(t))}break(t){return this._leafNode(new ia(t))}return(t){let r=new rn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(rn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new da;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new nn(i),r(i)}return n&&(this._currNode=o.finally=new on,this.code(n)),this._endBlockNode(nn,on)}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 tn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(tn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof At))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};D.CodeGen=fa;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ko(e,t){return t instanceof L._CodeOrName?Ct(e,t.names):e}function tr(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 Nv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function mp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${pa(e)}`}D.not=mp;var Cv=hp(D.operators.AND);function Dv(...e){return e.reduce(Cv)}D.and=Dv;var jv=hp(D.operators.OR);function Mv(...e){return e.reduce(jv)}D.or=Mv;function hp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${pa(t)} ${e} ${pa(r)}`}function pa(e){return e instanceof L.Name?e:(0,L._)`(${e})`}});var B=b(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(),qv=Xr();function Lv(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=Lv;function Bv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(_p(e,t),!wp(t,e.self.RULES.all))}j.alwaysValidSchema=Bv;function _p(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]||xp(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=_p;function wp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=wp;function Zv(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=Zv;function Uv({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=Uv;function Fv(e){return bp(decodeURIComponent(e))}j.unescapeFragment=Fv;function Vv(e){return encodeURIComponent(ha(e))}j.escapeFragment=Vv;function ha(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=ha;function bp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=bp;function Kv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=Kv;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} || {}`),ga(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:vp}),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 vp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&ga(e,r,t),r}j.evaluatedPropsToName=vp;function ga(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=ga;var yp={};function Hv(e,t){return e.scopeValue("func",{ref:t,code:yp[t.code]||(yp[t.code]=new qv._Code(t.code))})}j.useFunc=Hv;var ma;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ma||(j.Type=ma={}));function Wv(e,t,r){if(e instanceof H.Name){let n=t===ma.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():"/"+ha(e)}j.getErrorPath=Wv;function xp(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=xp});var ct=b(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var he=C(),Gv={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};ya.default=Gv});var sn=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=C(),Eo=B(),ve=ct();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Jv(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Sp(e,t,r);n??(s||a)?$p(i,c):kp(o,(0,Z._)`[${c}]`)}ge.reportError=Jv;function Qv(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Sp(e,t,r);$p(o,a),i||s||kp(n,ve.default.vErrors)}ge.reportExtraError=Qv;function Yv(e,t){e.assign(ve.default.errors,t),e.if((0,Z._)`${ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${ve.default.vErrors}.length`,t),()=>e.assign(ve.default.vErrors,null)))}ge.resetErrorsCount=Yv;function Xv({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,ve.default.errors,a=>{e.const(s,(0,Z._)`${ve.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(ve.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=Xv;function $p(e,t){let r=e.const("err",t);e.if((0,Z._)`${ve.default.vErrors} === null`,()=>e.assign(ve.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${ve.default.vErrors}.push(${r})`),e.code((0,Z._)`${ve.default.errors}++`)}function kp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Dt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Sp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:e0(e,t,r)}function e0(e,t,r={}){let{gen:n,it:o}=e,i=[t0(o,r),r0(e,r)];return n0(e,t,i),n.object(...i)}function t0({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,Eo.getErrorPath)(t,Eo.Type.Str)}`:e;return[ve.default.instancePath,(0,Z.strConcat)(ve.default.instancePath,r)]}function r0({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,Eo.getErrorPath)(r,Eo.Type.Str)}`),[Dt.schemaPath,o]}function n0(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([Dt.keyword,o],[Dt.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Dt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Dt.schema,s],[Dt.parentSchema,(0,Z._)`${u}${d}`],[ve.default.data,i]),l&&n.push([Dt.propertyName,l])}});var Tp=b(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.boolOrEmptySchema=rr.topBoolOrEmptySchema=void 0;var o0=sn(),i0=C(),s0=ct(),a0={message:"boolean schema is false"};function c0(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Ep(e,!1):typeof r=="object"&&r.$async===!0?t.return(s0.default.data):(t.assign((0,i0._)`${n}.errors`,null),t.return(!0))}rr.topBoolOrEmptySchema=c0;function u0(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Ep(e)):r.var(t,!0)}rr.boolOrEmptySchema=u0;function Ep(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,o0.reportError)(o,a0,void 0,t)}});var _a=b(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.getRules=nr.isJSONType=void 0;var l0=["string","number","integer","boolean","null","object","array"],d0=new Set(l0);function f0(e){return typeof e=="string"&&d0.has(e)}nr.isJSONType=f0;function p0(){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:{}}}nr.getRules=p0});var wa=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function m0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pp(e,n)}yt.schemaHasRulesForType=m0;function Pp(e,t){return t.rules.some(r=>Rp(e,r))}yt.shouldUseGroup=Pp;function Rp(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}yt.shouldUseRule=Rp});var an=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var h0=_a(),g0=wa(),y0=sn(),N=C(),zp=B(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ye.DataType=or={}));function _0(e){let t=Ip(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ye.getSchemaTypes=_0;function Ip(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(h0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=Ip;function w0(e,t){let{gen:r,data:n,opts:o}=e,i=b0(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,g0.schemaHasRulesForType)(e,t[0]));if(s){let a=va(t,n,o.strictNumbers,or.Wrong);r.if(a,()=>{i.length?v0(e,t,i):xa(e)})}return s}ye.coerceAndCheckDataType=w0;var Op=new Set(["string","number","integer","boolean","null"]);function b0(e,t){return t?e.filter(r=>Op.has(r)||t==="array"&&r==="array"):[]}function v0(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(va(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(Op.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),xa(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),x0(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 b_=Object.create;var Ii=Object.defineProperty;var v_=Object.getOwnPropertyDescriptor;var x_=Object.getOwnPropertyNames;var $_=Object.getPrototypeOf,k_=Object.prototype.hasOwnProperty;var dt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Lu=(e,t)=>{for(var r in t)Ii(e,r,{get:t[r],enumerable:!0})},S_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of x_(t))!k_.call(e,o)&&o!==r&&Ii(e,o,{get:()=>t[o],enumerable:!(n=v_(t,o))||n.enumerable});return e};var Oi=(e,t,r)=>(r=e!=null?b_($_(e)):{},S_(t||!e||!e.__esModule?Ii(r,"default",{value:e,enumerable:!0}):r,e));var Xr=b(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Qr=class{};U._CodeOrName=Qr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ot=class extends Qr{constructor(t){if(super(),!U.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};U.Name=Ot;var Ce=class extends Qr{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 Ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Ce;U.nil=new Ce("");function fp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ys(r,t[n]),r.push(e[++n]);return new Ce(r)}U._=fp;var Qs=new Ce("+");function pp(e,...t){let r=[Yr(e[0])],n=0;for(;n<t.length;)r.push(Qs),Ys(r,t[n]),r.push(Qs,Yr(e[++n]));return Tv(r),new Ce(r)}U.str=pp;function Ys(e,t){t instanceof Ce?e.push(...t._items):t instanceof Ot?e.push(t):e.push(zv(t))}U.addCodeArg=Ys;function Tv(e){let t=1;for(;t<e.length-1;){if(e[t]===Qs){let r=Pv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Pv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ot||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 Ot))return`"${e}${t.slice(1)}`}function Rv(e,t){return t.emptyStr()?e:e.emptyStr()?t:pp`${e}${t}`}U.strConcat=Rv;function zv(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Yr(Array.isArray(e)?e.join(","):e)}function Iv(e){return new Ce(Yr(e))}U.stringify=Iv;function Yr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Yr;function Ov(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new Ce(`.${e}`):fp`[${e}]`}U.getProperty=Ov;function Av(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new Ce(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=Av;function Nv(e){return new Ce(e.toString())}U.regexpCode=Nv});var ta=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.ValueScope=Ee.ValueScopeName=Ee.Scope=Ee.varKinds=Ee.UsedValueState=void 0;var Se=Xr(),Xs=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},wo;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(wo||(Ee.UsedValueState=wo={}));Ee.varKinds={const:new Se.Name("const"),let:new Se.Name("let"),var:new Se.Name("var")};var bo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Se.Name?t:this.name(t)}name(t){return new Se.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ee.Scope=bo;var vo=class extends Se.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Se._)`.${new Se.Name(r)}[${n}]`}};Ee.ValueScopeName=vo;var Cv=(0,Se._)`\n`,ea=class extends bo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Cv:Se.nil}}get(){return this._scope}name(t){return new vo(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Se._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=Se.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,wo.Started);let u=r(l);if(u){let d=this.opts.es5?Ee.varKinds.var:Ee.varKinds.const;i=(0,Se._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Se._)`${i}${u}${this.opts._n}`;else throw new Xs(l);c.set(l,wo.Completed)})}return i}};Ee.ValueScope=ea});var C=b(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=Xr(),Ze=ta(),gt=Xr();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return gt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return gt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return gt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return gt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return gt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return gt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return gt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return gt.Name}});var So=ta();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return So.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return So.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return So.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return So.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 st=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ra=class extends st{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ze.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=tr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},xo=class extends st{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=tr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return ko(t,this.rhs)}},na=class extends xo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},oa=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ia=class extends st{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},sa=class extends st{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},aa=class extends st{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=tr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},en=class extends st{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(Dv(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Ct(t,r.names),{})}},at=class extends en{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ca=class extends en{},er=class extends at{};er.kind="else";var At=class e extends at{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new er(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(mp(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=tr(this.condition,t,r),this}get names(){let t=super.names;return ko(t,this.condition),this.else&&Ct(t,this.else.names),t}};At.kind="if";var Nt=class extends at{};Nt.kind="for";var ua=class extends Nt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=tr(this.iteration,t,r),this}get names(){return Ct(super.names,this.iteration.names)}},la=class extends Nt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ze.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=ko(super.names,this.from);return ko(t,this.to)}},$o=class extends Nt{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=tr(this.iterable,t,r),this}get names(){return Ct(super.names,this.iterable.names)}},tn=class extends at{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};tn.kind="func";var rn=class extends en{render(t){return"return "+super.render(t)}};rn.kind="return";var da=class extends at{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Ct(t,this.catch.names),this.finally&&Ct(t,this.finally.names),t}},nn=class extends at{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};nn.kind="catch";var on=class extends at{render(t){return"finally"+super.render(t)}};on.kind="finally";var fa=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Ze.Scope({parent:t}),this._nodes=[new ca]}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 ra(t,i,n)),i}const(t,r,n){return this._def(Ze.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ze.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ze.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new xo(t,r,n))}add(t,r){return this._leafNode(new na(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new aa(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 At(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new At(t))}else(){return this._elseNode(new er)}endIf(){return this._endBlockNode(At,er)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new ua(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ze.varKinds.var:Ze.varKinds.let){let s=this._scope.toName(t);return this._for(new la(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ze.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 $o("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ze.varKinds.var:Ze.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 $o("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Nt)}label(t){return this._leafNode(new oa(t))}break(t){return this._leafNode(new ia(t))}return(t){let r=new rn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(rn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new da;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new nn(i),r(i)}return n&&(this._currNode=o.finally=new on,this.code(n)),this._endBlockNode(nn,on)}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 tn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(tn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof At))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};D.CodeGen=fa;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ko(e,t){return t instanceof L._CodeOrName?Ct(e,t.names):e}function tr(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 Dv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function mp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${pa(e)}`}D.not=mp;var jv=hp(D.operators.AND);function Mv(...e){return e.reduce(jv)}D.and=Mv;var qv=hp(D.operators.OR);function Lv(...e){return e.reduce(qv)}D.or=Lv;function hp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${pa(t)} ${e} ${pa(r)}`}function pa(e){return e instanceof L.Name?e:(0,L._)`(${e})`}});var B=b(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(),Bv=Xr();function Zv(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=Zv;function Uv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(_p(e,t),!wp(t,e.self.RULES.all))}j.alwaysValidSchema=Uv;function _p(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]||xp(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=_p;function wp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=wp;function Fv(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=Fv;function Vv({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=Vv;function Kv(e){return bp(decodeURIComponent(e))}j.unescapeFragment=Kv;function Hv(e){return encodeURIComponent(ha(e))}j.escapeFragment=Hv;function ha(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=ha;function bp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=bp;function Wv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=Wv;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} || {}`),ga(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:vp}),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 vp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&ga(e,r,t),r}j.evaluatedPropsToName=vp;function ga(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=ga;var yp={};function Gv(e,t){return e.scopeValue("func",{ref:t,code:yp[t.code]||(yp[t.code]=new Bv._Code(t.code))})}j.useFunc=Gv;var ma;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ma||(j.Type=ma={}));function Jv(e,t,r){if(e instanceof H.Name){let n=t===ma.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():"/"+ha(e)}j.getErrorPath=Jv;function xp(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=xp});var ct=b(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var he=C(),Qv={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};ya.default=Qv});var sn=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=C(),Eo=B(),ve=ct();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Yv(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Sp(e,t,r);n??(s||a)?$p(i,c):kp(o,(0,Z._)`[${c}]`)}ge.reportError=Yv;function Xv(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Sp(e,t,r);$p(o,a),i||s||kp(n,ve.default.vErrors)}ge.reportExtraError=Xv;function e0(e,t){e.assign(ve.default.errors,t),e.if((0,Z._)`${ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${ve.default.vErrors}.length`,t),()=>e.assign(ve.default.vErrors,null)))}ge.resetErrorsCount=e0;function t0({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,ve.default.errors,a=>{e.const(s,(0,Z._)`${ve.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(ve.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=t0;function $p(e,t){let r=e.const("err",t);e.if((0,Z._)`${ve.default.vErrors} === null`,()=>e.assign(ve.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${ve.default.vErrors}.push(${r})`),e.code((0,Z._)`${ve.default.errors}++`)}function kp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Dt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Sp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:r0(e,t,r)}function r0(e,t,r={}){let{gen:n,it:o}=e,i=[n0(o,r),o0(e,r)];return i0(e,t,i),n.object(...i)}function n0({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,Eo.getErrorPath)(t,Eo.Type.Str)}`:e;return[ve.default.instancePath,(0,Z.strConcat)(ve.default.instancePath,r)]}function o0({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,Eo.getErrorPath)(r,Eo.Type.Str)}`),[Dt.schemaPath,o]}function i0(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([Dt.keyword,o],[Dt.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Dt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Dt.schema,s],[Dt.parentSchema,(0,Z._)`${u}${d}`],[ve.default.data,i]),l&&n.push([Dt.propertyName,l])}});var Tp=b(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.boolOrEmptySchema=rr.topBoolOrEmptySchema=void 0;var s0=sn(),a0=C(),c0=ct(),u0={message:"boolean schema is false"};function l0(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Ep(e,!1):typeof r=="object"&&r.$async===!0?t.return(c0.default.data):(t.assign((0,a0._)`${n}.errors`,null),t.return(!0))}rr.topBoolOrEmptySchema=l0;function d0(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Ep(e)):r.var(t,!0)}rr.boolOrEmptySchema=d0;function Ep(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,s0.reportError)(o,u0,void 0,t)}});var _a=b(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.getRules=nr.isJSONType=void 0;var f0=["string","number","integer","boolean","null","object","array"],p0=new Set(f0);function m0(e){return typeof e=="string"&&p0.has(e)}nr.isJSONType=m0;function h0(){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:{}}}nr.getRules=h0});var wa=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function g0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pp(e,n)}yt.schemaHasRulesForType=g0;function Pp(e,t){return t.rules.some(r=>Rp(e,r))}yt.shouldUseGroup=Pp;function Rp(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}yt.shouldUseRule=Rp});var an=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var y0=_a(),_0=wa(),w0=sn(),N=C(),zp=B(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ye.DataType=or={}));function b0(e){let t=Ip(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ye.getSchemaTypes=b0;function Ip(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(y0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=Ip;function v0(e,t){let{gen:r,data:n,opts:o}=e,i=x0(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,_0.schemaHasRulesForType)(e,t[0]));if(s){let a=va(t,n,o.strictNumbers,or.Wrong);r.if(a,()=>{i.length?$0(e,t,i):xa(e)})}return s}ye.coerceAndCheckDataType=v0;var Op=new Set(["string","number","integer","boolean","null"]);function x0(e,t){return t?e.filter(r=>Op.has(r)||t==="array"&&r==="array"):[]}function $0(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(va(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(Op.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),xa(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),k0(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 x0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function ba(e,t,r,n=or.Correct){let o=n===or.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===or.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)}}ye.checkDataType=ba;function va(e,t,r,n){if(e.length===1)return ba(e[0],t,r,n);let o,i=(0,zp.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,ba(s,t,r,n));return o}ye.checkDataTypes=va;var $0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function xa(e){let t=k0(e);(0,y0.reportError)(t,$0)}ye.reportTypeError=xa;function k0(e){let{gen:t,data:r,schema:n}=e,o=(0,zp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Np=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.assignDefaults=void 0;var ir=C(),S0=B();function E0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Ap(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Ap(e,i,o.default))}To.assignDefaults=E0;function Ap(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,ir._)`${i}${(0,ir.getProperty)(t)}`;if(o){(0,S0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,ir._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,ir._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ir._)`${a} = ${(0,ir.stringify)(r)}`)}});var De=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=C(),$a=B(),_t=ct(),T0=B();function P0(e,t){let{gen:r,data:n,it:o}=e;r.if(Sa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}K.checkReportMissingProp=P0;function R0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)(Sa(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}K.checkMissingProp=R0;function z0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=z0;function Cp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Cp;function ka(e,t,r){return(0,X._)`${Cp(e)}.call(${t}, ${r})`}K.isOwnProperty=ka;function I0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${ka(e,t,r)}`:o}K.propertyInData=I0;function Sa(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(ka(e,t,r))):o}K.noPropertyInData=Sa;function Dp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=Dp;function O0(e,t){return Dp(t).filter(r=>!(0,$a.alwaysValidSchema)(e,t[r]))}K.schemaProperties=O0;function A0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[_t.default.instancePath,(0,X.strConcat)(_t.default.instancePath,i)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];s.opts.dynamicRef&&d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}K.callValidateCode=A0;var N0=(0,X._)`new RegExp`;function C0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?N0:(0,T0.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=C0;function D0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:$a.Type.Num},i),t.if((0,X.not)(i),a)})}}K.validateArray=D0;function j0(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,$a.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=j0});var qp=b(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var xe=C(),jt=ct(),M0=De(),q0=sn();function L0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Mp(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:xe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Ye.macroKeywordCode=L0;function B0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;U0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Mp(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&&jp(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&jp(e),_(()=>Z0(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,xe._)`await `),v=>n.assign(d,!1).if((0,xe._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,xe._)`${v}.errors`),()=>n.throw(v))),w}function m(){let w=(0,xe._)`${u}.errors`;return n.assign(w,null),h(xe.nil),w}function h(w=t.async?(0,xe._)`await `:xe.nil){let v=c.opts.passContext?jt.default.this:jt.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,xe._)`${w}${(0,M0.callValidateCode)(e,u,v,x)}`,t.modifying)}function _(w){var v;n.if((0,xe.not)((v=t.valid)!==null&&v!==void 0?v:d),w)}}Ye.funcKeywordCode=B0;function jp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,xe._)`${n.parentData}[${n.parentDataProperty}]`))}function Z0(e,t){let{gen:r}=e;r.if((0,xe._)`Array.isArray(${t})`,()=>{r.assign(jt.default.vErrors,(0,xe._)`${jt.default.vErrors} === null ? ${t} : ${jt.default.vErrors}.concat(${t})`).assign(jt.default.errors,(0,xe._)`${jt.default.vErrors}.length`),(0,q0.extendErrors)(e)},()=>e.error())}function U0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Mp(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,xe.stringify)(r)})}function F0(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Ye.validSchemaType=F0;function V0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ye.validateKeywordUsage=V0});var Bp=b(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.extendSubschemaMode=wt.extendSubschemaData=wt.getSubschema=void 0;var Xe=C(),Lp=B();function K0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}${(0,Xe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Lp.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}wt.getSubschema=K0;function H0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,Xe._)`${t.data}${(0,Xe.getProperty)(r)}`,!0);c(f),e.errorPath=(0,Xe.str)`${l}${(0,Lp.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Xe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Xe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}wt.extendSubschemaData=H0;function W0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}wt.extendSubschemaMode=W0});var Ea=b((nD,Zp)=>{"use strict";Zp.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 Fp=b((oD,Up)=>{"use strict";var bt=Up.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(){};Po(t,n,o,e,"",e)};bt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Po(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in bt.arrayKeywords)for(var f=0;f<d.length;f++)Po(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in bt.propsKeywords){if(d&&typeof d=="object")for(var p in d)Po(e,t,r,d[p],o+"/"+u+"/"+G0(p),i,o,u,n,p)}else(u in bt.keywords||e.allKeys&&!(u in bt.skipKeywords))&&Po(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function G0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var cn=b(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var J0=B(),Q0=Ea(),Y0=Fp(),X0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ex(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ta(e):t?Vp(e)<=t:!1}Te.inlineRef=ex;var tx=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ta(e){for(let t in e){if(tx.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ta)||typeof r=="object"&&Ta(r))return!0}return!1}function Vp(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!X0.has(r)&&(typeof e[r]=="object"&&(0,J0.eachItem)(e[r],n=>t+=Vp(n)),t===1/0))return 1/0}return t}function Kp(e,t="",r){r!==!1&&(t=sr(t));let n=e.parse(t);return Hp(e,n)}Te.getFullPath=Kp;function Hp(e,t){return e.serialize(t).split("#")[0]+"#"}Te._getFullPath=Hp;var rx=/#\/?$/;function sr(e){return e?e.replace(rx,""):""}Te.normalizeId=sr;function nx(e,t,r){return r=sr(r),e.resolve(t,r)}Te.resolveUrl=nx;var ox=/^[a-z_][-a-z0-9._]*$/i;function ix(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=sr(e[r]||t),i={"":o},s=Kp(n,o,!1),a={},c=new Set;return Y0(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])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let P=this.opts.uriResolver.resolve;if(x=sr(_?P(_,x):x),c.has(x))throw u(x);c.add(x);let I=this.refs[x];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?l(d,I.schema,x):x!==sr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function v(x){if(typeof x=="string"){if(!ox.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Q0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=ix});var dn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getData=vt.KeywordCxt=vt.validateFunctionCode=void 0;var Yp=Tp(),Wp=an(),Ra=wa(),Ro=an(),sx=Np(),ln=qp(),Pa=Bp(),S=C(),A=ct(),ax=cn(),ut=B(),un=sn();function cx(e){if(tm(e)&&(rm(e),em(e))){dx(e);return}Xp(e,()=>(0,Yp.topBoolOrEmptySchema)(e))}vt.validateFunctionCode=cx;function Xp({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"; ${Gp(r,o)}`),lx(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${ux(o)}`,n.$async,()=>e.code(Gp(r,o)).code(i))}function ux(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 lx(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 dx(e){let{schema:t,opts:r,gen:n}=e;Xp(e,()=>{r.$comment&&t.$comment&&om(e),gx(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&fx(e),nm(e),wx(e)})}function fx(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 Gp(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 px(e,t){if(tm(e)&&(rm(e),em(e))){mx(e,t);return}(0,Yp.boolOrEmptySchema)(e,t)}function em({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 tm(e){return typeof e.schema!="boolean"}function mx(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&om(e),yx(e),_x(e);let i=n.const("_errs",A.default.errors);nm(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function rm(e){(0,ut.checkUnknownRules)(e),hx(e)}function nm(e,t){if(e.opts.jtd)return Jp(e,[],!1,t);let r=(0,Wp.getSchemaTypes)(e.schema),n=(0,Wp.coerceAndCheckDataType)(e,r);Jp(e,r,!n,t)}function hx(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function gx(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function yx(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,ax.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function _x(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function om({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 wx(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&&bx(e),t.return((0,S._)`${A.default.errors} === 0`))}function bx({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 Jp(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(i,u))){o.block(()=>sm(e,"$ref",u.all.$ref.definition));return}c.jtd||vx(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ra.shouldUseGroup)(i,f)&&(f.type?(o.if((0,Ro.checkDataType)(f.type,s,c.strictNumbers)),Qp(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,Ro.reportTypeError)(e)),o.endIf()):Qp(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Qp(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,sx.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ra.shouldUseRule)(n,i)&&sm(e,i.keyword,i.definition,t.type)})}function vx(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(xx(e,t),e.opts.allowUnionTypes||$x(e,t),kx(e,e.dataTypes))}function xx(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{im(e.dataTypes,r)||za(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),Ex(e,t)}}function $x(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&za(e,"use allowUnionTypes to allow union type keyword")}function kx(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ra.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Sx(t,s))&&za(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Sx(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function im(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Ex(e,t){let r=[];for(let n of e.dataTypes)im(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function za(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}var zo=class{constructor(t,r,n){if((0,ln.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ut.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",am(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,ln.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?un.reportExtraError:un.reportError)(this,this.def.error,r)}$dataError(){(0,un.reportError)(this,this.def.$dataError||un.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,un.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,Ro.checkDataTypes)(c,r,i.opts.strictNumbers,Ro.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,Pa.getSubschema)(this.it,t);(0,Pa.extendSubschemaData)(n,this.it,t),(0,Pa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return px(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ut.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ut.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};vt.KeywordCxt=zo;function sm(e,t,r,n){let o=new zo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ln.funcKeywordCode)(o,r):"macro"in r?(0,ln.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ln.funcKeywordCode)(o,r)}var Tx=/^\/(?:[^~]|~0|~1)*$/,Px=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function am(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!Tx.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=Px.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ut.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}vt.getData=am});var Io=b(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Ia=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Oa.default=Ia});var fn=b(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var Aa=cn(),Na=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Aa.resolveUrl)(t,r,n),this.missingSchema=(0,Aa.normalizeId)((0,Aa.getFullPath)(t,this.missingRef))}};Ca.default=Na});var Ao=b(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Ue=C(),Rx=Io(),Mt=ct(),Fe=cn(),cm=B(),zx=dn(),ar=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,Fe.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};je.SchemaEnv=ar;function ja(e){let t=um.call(this,e);if(t)return t;let r=(0,Fe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ue.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:Rx.default,code:(0,Ue._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Mt.default.data,parentData:Mt.default.parentData,parentDataProperty:Mt.default.parentDataProperty,dataNames:[Mt.default.data],dataPathArr:[Ue.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ue.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ue.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ue._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,zx.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Mt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Mt.default.self}`,`${Mt.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 Ue.Name?void 0:m,items:h instanceof Ue.Name?void 0:h,dynamicProps:m instanceof Ue.Name,dynamicItems:h instanceof Ue.Name},p.source&&(p.source.evaluated=(0,Ue.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)}}je.compileSchema=ja;function Ix(e,t,r){var n;r=(0,Fe.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=Nx.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 ar({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=Ox.call(this,i)}je.resolveRef=Ix;function Ox(e){return(0,Fe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ja.call(this,e)}function um(e){for(let t of this._compilations)if(Ax(t,e))return t}je.getCompilingSchema=um;function Ax(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Nx(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Oo.call(this,e,t)}function Oo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Fe._getFullPath)(this.opts.uriResolver,r),o=(0,Fe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Da.call(this,r,e);let i=(0,Fe.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Oo.call(this,e,s);return typeof a?.schema!="object"?void 0:Da.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||ja.call(this,s),i===(0,Fe.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new ar({schema:a,schemaId:c,root:e,baseId:o})}return Da.call(this,r,s)}}je.resolveSchema=Oo;var Cx=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Da(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,cm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Cx.has(a)&&l&&(t=(0,Fe.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,cm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Oo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new ar({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var lm=b((lD,Dx)=>{Dx.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 La=b((dD,gm)=>{"use strict";var jx=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),fm=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),Ma=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),pm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Mx=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function qa(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 qx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function dm(e){return e.length=0,!0}function Lx(e,t,r){if(e.length){let n=qa(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Bx(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=Lx;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=dm}else{o.push(l);continue}}return o.length&&(a===dm?r.zone=o.join(""):s?n.push(o.join("")):n.push(qa(o))),r.address=n.join(""),r}function mm(e){if(Zx(e,":")<2)return{host:e,isIPV6:!1};let t=Bx(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 Zx(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Ux(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 Fx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Vx=/[@/?#:]/g,Kx=/[@/?#]/g;function hm(e,t){let r=t?Kx:Vx;return r.lastIndex=0,e.replace(r,n=>Fx[n])}function Hx(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(Ma(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&pm(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function Wx(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(Ma(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&pm(i)?t+=i:t+="%"+o,r+=2;continue}}Mx(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Gx(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(Ma(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Jx(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!fm(r)){let n=mm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=hm(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:qx,recomposeAuthority:Jx,reescapeHostDelimiters:hm,normalizePercentEncoding:Hx,normalizePathEncoding:Wx,escapePreservingEscapes:Gx,removeDotSegments:Ux,isIPv4:fm,isUUID:jx,normalizeIPv6:mm,stringArrayToHexStripped:qa}});var vm=b((fD,bm)=>{"use strict";var{isUUID:Qx}=La(),Yx=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Xx=["http","https","ws","wss","urn","urn:uuid"];function e$(e){return Xx.indexOf(e)!==-1}function Ba(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 _m(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 t$(e){return e.secure=Ba(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function r$(e){if((e.port===(Ba(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 n$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Yx);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=Za(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function o$(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=Za(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 i$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Qx(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function s$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var wm={scheme:"http",domainHost:!0,parse:ym,serialize:_m},a$={scheme:"https",domainHost:wm.domainHost,parse:ym,serialize:_m},No={scheme:"ws",domainHost:!0,parse:t$,serialize:r$},c$={scheme:"wss",domainHost:No.domainHost,parse:No.parse,serialize:No.serialize},u$={scheme:"urn",parse:n$,serialize:o$,skipNormalize:!0},l$={scheme:"urn:uuid",parse:i$,serialize:s$,skipNormalize:!0},Co={http:wm,https:a$,ws:No,wss:c$,urn:u$,"urn:uuid":l$};Object.setPrototypeOf(Co,null);function Za(e){return e&&(Co[e]||Co[e.toLowerCase()])||void 0}bm.exports={wsIsSecure:Ba,SCHEMES:Co,isValidSchemeName:e$,getSchemeHandler:Za}});var Tm=b((pD,Do)=>{"use strict";var{normalizeIPv6:d$,removeDotSegments:pn,recomposeAuthority:f$,normalizePercentEncoding:p$,normalizePathEncoding:m$,escapePreservingEscapes:h$,reescapeHostDelimiters:g$,isIPv4:y$,nonSimpleDomain:_$}=La(),{SCHEMES:w$,getSchemeHandler:$m}=vm();function b$(e,t){return typeof e=="string"?e=S$(e,t):typeof e=="object"&&(e=cr(qt(e,t),t)),e}function v$(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=km(cr(e,n),cr(t,n),n,!0);return n.skipEscape=!0,qt(o,n)}function km(e,t,r,n){let o={};return n||(e=cr(qt(e,r),r),t=cr(qt(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=pn(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=pn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=pn(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=pn(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 x$(e,t,r){let n=xm(e,r),o=xm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function qt(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=$m(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=p$(r.path):(r.path=h$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=f$(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=pn(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 $$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function k$(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 Sm(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($$);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=k$(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(y$(n.host)===!1){let u=d$(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=$m(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&_$(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=g$(unescape(n.host),i))),n.path&&(n.path=m$(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 cr(e,t){return Sm(e,t).parsed}function S$(e,t){return Em(e,t).normalized}function Em(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Sm(e,t);return{normalized:n?e:qt(r,t),malformedAuthorityOrPort:n}}function xm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Em(e,t);return n?void 0:r}if(typeof e=="object")return qt(e,t)}var Ua={SCHEMES:w$,normalize:b$,resolve:v$,resolveComponent:km,equal:x$,serialize:qt,parse:cr};Do.exports=Ua;Do.exports.default=Ua;Do.exports.fastUri=Ua});var Rm=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Pm=Tm();Pm.code='require("ajv/dist/runtime/uri").default';Fa.default=Pm});var jm=b(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var E$=dn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return E$.KeywordCxt}});var ur=C();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var T$=Io(),Nm=fn(),P$=_a(),mn=Ao(),R$=C(),hn=cn(),jo=an(),Ka=B(),zm=lm(),z$=Rm(),Cm=(e,t)=>new RegExp(e,t);Cm.code="new RegExp";var I$=["removeAdditional","useDefaults","coerceTypes"],O$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),A$={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."},N$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Im=200;function C$(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,v,x,P,I,we,Ie,Ht,Ri;let Pr=e.strict,zi=(t=e.code)===null||t===void 0?void 0:t.optimize,Mu=zi===!0||zi===void 0?1:zi||0,qu=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Cm,y_=(o=e.uriResolver)!==null&&o!==void 0?o:z$.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Pr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Pr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Pr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Pr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Pr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Mu,regExp:qu}:{optimize:Mu,regExp:qu},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Im,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Im,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(we=e.validateSchema)!==null&&we!==void 0?we:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(Ht=e.unicodeRegExp)!==null&&Ht!==void 0?Ht:!0,int32range:(Ri=e.int32range)!==null&&Ri!==void 0?Ri:!0,uriResolver:y_}}var gn=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,...C$(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new R$.ValueScope({scope:{},prefixes:O$,es5:r,lines:n}),this.logger=B$(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,P$.getRules)(),Om.call(this,A$,t,"NOT SUPPORTED"),Om.call(this,N$,t,"DEPRECATED","warn"),this._metaOpts=q$.call(this),t.formats&&j$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&M$.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),D$.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=zm;n==="id"&&(o={...zm},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 Nm.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,hn.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=Am.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new mn.SchemaEnv({schema:{},schemaId:n});if(r=mn.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Am.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,hn.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(U$.call(this,n,r),!r)return(0,Ka.eachItem)(n,i=>Va.call(this,i)),this;V$.call(this,r);let o={...r,type:(0,jo.getJSONTypes)(r.type),schemaType:(0,jo.getJSONTypes)(r.schemaType)};return(0,Ka.eachItem)(n,o.type.length===0?i=>Va.call(this,i,o):i=>o.type.forEach(s=>Va.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]=Dm(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,hn.normalizeId)(s||n);let l=hn.getSchemaRefs.call(this,t,n);return c=new mn.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):mn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{mn.compileSchema.call(this,t)}finally{this.opts=r}}};gn.ValidationError=T$.default;gn.MissingRefError=Nm.default;fe.default=gn;function Om(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 Am(e){return e=(0,hn.normalizeId)(e),this.schemas[e]||this.refs[e]}function D$(){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 j$(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function M$(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 q$(){let e={...this.opts};for(let t of I$)delete e[t];return e}var L$={log(){},warn(){},error(){}};function B$(e){if(e===!1)return L$;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 Z$=/^[a-z_$][a-z0-9_$:-]*$/i;function U$(e,t){let{RULES:r}=this;if((0,Ka.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Z$.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 Va(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,jo.getJSONTypes)(t.type),schemaType:(0,jo.getJSONTypes)(t.schemaType)}};t.before?F$.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 F$(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 V$(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Dm(t)),e.validateSchema=this.compile(t,!0))}var K$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Dm(e){return{anyOf:[e,K$]}}});var Mm=b(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var H$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ha.default=H$});var Zm=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.callRef=Lt.getValidate=void 0;var W$=fn(),qm=De(),Pe=C(),lr=ct(),Lm=Ao(),Mo=B(),G$={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=Lm.resolveRef.call(c,l,o,r);if(u===void 0)throw new W$.default(n.opts.uriResolver,o,r);if(u instanceof Lm.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return qo(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return qo(e,(0,Pe._)`${m}.validate`,l,l.$async)}function f(m){let h=Bm(e,m);qo(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pe.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Bm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Lt.getValidate=Bm;function qo(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?lr.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,qm.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Pe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,qm.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Pe._)`${m}.errors`;o.assign(lr.default.vErrors,(0,Pe._)`${lr.default.vErrors} === null ? ${h} : ${lr.default.vErrors}.concat(${h})`),o.assign(lr.default.errors,(0,Pe._)`${lr.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=Mo.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Pe._)`${m}.evaluated.props`);i.props=Mo.mergeEvaluated.props(o,w,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Mo.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Pe._)`${m}.evaluated.items`);i.items=Mo.mergeEvaluated.items(o,w,i.items,Pe.Name)}}}Lt.callRef=qo;Lt.default=G$});var Um=b(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var J$=Mm(),Q$=Zm(),Y$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",J$.default,Q$.default];Wa.default=Y$});var Fm=b(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Lo=C(),xt=Lo.operators,Bo={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},X$={message:({keyword:e,schemaCode:t})=>(0,Lo.str)`must be ${Bo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Lo._)`{comparison: ${Bo[e].okStr}, limit: ${t}}`},ek={keyword:Object.keys(Bo),type:"number",schemaType:"number",$data:!0,error:X$,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Lo._)`${r} ${Bo[t].fail} ${n} || isNaN(${r})`)}};Ga.default=ek});var Vm=b(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var yn=C(),tk={message:({schemaCode:e})=>(0,yn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,yn._)`{multipleOf: ${e}}`},rk={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tk,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,yn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,yn._)`${s} !== parseInt(${s})`;e.fail$data((0,yn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ja.default=rk});var Hm=b(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});function Km(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}Qa.default=Km;Km.code='require("ajv/dist/runtime/ucs2length").default'});var Wm=b(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Bt=C(),nk=B(),ok=Hm(),ik={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Bt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Bt._)`{limit: ${e}}`},sk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ik,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Bt.operators.GT:Bt.operators.LT,s=o.opts.unicode===!1?(0,Bt._)`${r}.length`:(0,Bt._)`${(0,nk.useFunc)(e.gen,ok.default)}(${r})`;e.fail$data((0,Bt._)`${s} ${i} ${n}`)}};Ya.default=sk});var Gm=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var ak=De(),ck=B(),dr=C(),uk={message:({schemaCode:e})=>(0,dr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,dr._)`{pattern: ${e}}`},lk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:uk,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,dr._)`new RegExp`:(0,ck.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,dr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,dr._)`!${u}`)}else{let c=(0,ak.usePattern)(e,o);e.fail$data((0,dr._)`!${c}.test(${r})`)}}};Xa.default=lk});var Jm=b(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var _n=C(),dk={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,_n.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,_n._)`{limit: ${e}}`},fk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:dk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?_n.operators.GT:_n.operators.LT;e.fail$data((0,_n._)`Object.keys(${r}).length ${o} ${n}`)}};ec.default=fk});var Qm=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var wn=De(),bn=C(),pk=B(),mk={message:({params:{missingProperty:e}})=>(0,bn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,bn._)`{missingProperty: ${e}}`},hk={keyword:"required",type:"object",schemaType:"array",$data:!0,error:mk,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,pk.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(bn.nil,d);else for(let p of r)(0,wn.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,wn.checkMissingProp)(e,r,p)),(0,wn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,wn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,wn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,bn.not)(m),()=>{e.error(),t.break()})},bn.nil)}}};tc.default=hk});var Ym=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var vn=C(),gk={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,vn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,vn._)`{limit: ${e}}`},yk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:gk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?vn.operators.GT:vn.operators.LT;e.fail$data((0,vn._)`${r}.length ${o} ${n}`)}};rc.default=yk});var Zo=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var Xm=Ea();Xm.code='require("ajv/dist/runtime/equal").default';nc.default=Xm});var eh=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var oc=an(),pe=C(),_k=B(),wk=Zo(),bk={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},vk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bk,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,oc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),w=(0,oc.checkDataTypes)(l,_,a.opts.strictNumbers,oc.DataType.Wrong),v=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${v}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${v}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${v}[${_}] = ${m}`)})}function p(m,h){let _=(0,_k.useFunc)(t,wk.default),w=t.name("outer");t.label(w).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};ic.default=vk});var th=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var sc=C(),xk=B(),$k=Zo(),kk={message:"must be equal to constant",params:({schemaCode:e})=>(0,sc._)`{allowedValue: ${e}}`},Sk={keyword:"const",$data:!0,error:kk,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,xk.useFunc)(t,$k.default)}(${r}, ${o})`):e.fail((0,sc._)`${i} !== ${r}`)}};ac.default=Sk});var rh=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var xn=C(),Ek=B(),Tk=Zo(),Pk={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,xn._)`{allowedValues: ${e}}`},Rk={keyword:"enum",schemaType:"array",$data:!0,error:Pk,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,Ek.useFunc)(t,Tk.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,xn.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,xn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,xn._)`${l()}(${r}, ${p}[${m}])`:(0,xn._)`${r} === ${h}`}}};cc.default=Rk});var nh=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var zk=Fm(),Ik=Vm(),Ok=Wm(),Ak=Gm(),Nk=Jm(),Ck=Qm(),Dk=Ym(),jk=eh(),Mk=th(),qk=rh(),Lk=[zk.default,Ik.default,Ok.default,Ak.default,Nk.default,Ck.default,Dk.default,jk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Mk.default,qk.default];uc.default=Lk});var dc=b($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.validateAdditionalItems=void 0;var Zt=C(),lc=B(),Bk={message:({params:{len:e}})=>(0,Zt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zt._)`{limit: ${e}}`},Zk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Bk,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,lc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}oh(e,n)}};function oh(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Zt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Zt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,lc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Zt._)`${a} <= ${t.length}`);r.if((0,Zt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:lc.Type.Num},l),s.allErrors||r.if((0,Zt.not)(l),()=>r.break())})}}$n.validateAdditionalItems=oh;$n.default=Zk});var fc=b(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.validateTuple=void 0;var ih=C(),Uo=B(),Uk=De(),Fk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return sh(e,"additionalItems",t);r.items=!0,!(0,Uo.alwaysValidSchema)(r,t)&&e.ok((0,Uk.validateArray)(e))}};function sh(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=Uo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ih._)`${i}.length`);r.forEach((d,f)=>{(0,Uo.alwaysValidSchema)(a,d)||(n.if((0,ih._)`${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,Uo.checkStrictMode)(a,_,f.strictTuples)}}}kn.validateTuple=sh;kn.default=Fk});var ah=b(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Vk=fc(),Kk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Vk.validateTuple)(e,"items")};pc.default=Kk});var uh=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ch=C(),Hk=B(),Wk=De(),Gk=dc(),Jk={message:({params:{len:e}})=>(0,ch.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ch._)`{limit: ${e}}`},Qk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Jk,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,Hk.alwaysValidSchema)(n,t)&&(o?(0,Gk.validateAdditionalItems)(e,o):e.ok((0,Wk.validateArray)(e)))}};mc.default=Qk});var lh=b(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Me=C(),Fo=B(),Yk={message:({params:{min:e,max:t}})=>t===void 0?(0,Me.str)`must contain at least ${e} valid item(s)`:(0,Me.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Me._)`{minContains: ${e}}`:(0,Me._)`{minContains: ${e}, maxContains: ${t}}`},Xk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Yk,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,Me._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Fo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Fo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Fo.alwaysValidSchema)(i,r)){let h=(0,Me._)`${u} >= ${s}`;a!==void 0&&(h=(0,Me._)`${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,Me._)`${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:Fo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Me._)`${h}++`),a===void 0?t.if((0,Me._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Me._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Me._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};hc.default=Xk});var ph=b(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateSchemaDeps=et.validatePropertyDeps=et.error=void 0;var gc=C(),eS=B(),Sn=De();et.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,gc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,gc._)`{property: ${e},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function k0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function ba(e,t,r,n=or.Correct){let o=n===or.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===or.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)}}ye.checkDataType=ba;function va(e,t,r,n){if(e.length===1)return ba(e[0],t,r,n);let o,i=(0,zp.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,ba(s,t,r,n));return o}ye.checkDataTypes=va;var S0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function xa(e){let t=E0(e);(0,w0.reportError)(t,S0)}ye.reportTypeError=xa;function E0(e){let{gen:t,data:r,schema:n}=e,o=(0,zp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Np=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.assignDefaults=void 0;var ir=C(),T0=B();function P0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Ap(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Ap(e,i,o.default))}To.assignDefaults=P0;function Ap(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,ir._)`${i}${(0,ir.getProperty)(t)}`;if(o){(0,T0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,ir._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,ir._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ir._)`${a} = ${(0,ir.stringify)(r)}`)}});var De=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=C(),$a=B(),_t=ct(),R0=B();function z0(e,t){let{gen:r,data:n,it:o}=e;r.if(Sa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}K.checkReportMissingProp=z0;function I0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)(Sa(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}K.checkMissingProp=I0;function O0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=O0;function Cp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Cp;function ka(e,t,r){return(0,X._)`${Cp(e)}.call(${t}, ${r})`}K.isOwnProperty=ka;function A0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${ka(e,t,r)}`:o}K.propertyInData=A0;function Sa(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(ka(e,t,r))):o}K.noPropertyInData=Sa;function Dp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=Dp;function N0(e,t){return Dp(t).filter(r=>!(0,$a.alwaysValidSchema)(e,t[r]))}K.schemaProperties=N0;function C0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[_t.default.instancePath,(0,X.strConcat)(_t.default.instancePath,i)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];s.opts.dynamicRef&&d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}K.callValidateCode=C0;var D0=(0,X._)`new RegExp`;function j0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?D0:(0,R0.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=j0;function M0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:$a.Type.Num},i),t.if((0,X.not)(i),a)})}}K.validateArray=M0;function q0(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,$a.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=q0});var qp=b(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var xe=C(),jt=ct(),L0=De(),B0=sn();function Z0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Mp(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:xe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Ye.macroKeywordCode=Z0;function U0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;V0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Mp(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&&jp(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&jp(e),_(()=>F0(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,xe._)`await `),v=>n.assign(d,!1).if((0,xe._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,xe._)`${v}.errors`),()=>n.throw(v))),w}function m(){let w=(0,xe._)`${u}.errors`;return n.assign(w,null),h(xe.nil),w}function h(w=t.async?(0,xe._)`await `:xe.nil){let v=c.opts.passContext?jt.default.this:jt.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,xe._)`${w}${(0,L0.callValidateCode)(e,u,v,x)}`,t.modifying)}function _(w){var v;n.if((0,xe.not)((v=t.valid)!==null&&v!==void 0?v:d),w)}}Ye.funcKeywordCode=U0;function jp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,xe._)`${n.parentData}[${n.parentDataProperty}]`))}function F0(e,t){let{gen:r}=e;r.if((0,xe._)`Array.isArray(${t})`,()=>{r.assign(jt.default.vErrors,(0,xe._)`${jt.default.vErrors} === null ? ${t} : ${jt.default.vErrors}.concat(${t})`).assign(jt.default.errors,(0,xe._)`${jt.default.vErrors}.length`),(0,B0.extendErrors)(e)},()=>e.error())}function V0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Mp(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,xe.stringify)(r)})}function K0(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Ye.validSchemaType=K0;function H0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ye.validateKeywordUsage=H0});var Bp=b(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.extendSubschemaMode=wt.extendSubschemaData=wt.getSubschema=void 0;var Xe=C(),Lp=B();function W0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Xe._)`${e.schemaPath}${(0,Xe.getProperty)(t)}${(0,Xe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Lp.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}wt.getSubschema=W0;function G0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,Xe._)`${t.data}${(0,Xe.getProperty)(r)}`,!0);c(f),e.errorPath=(0,Xe.str)`${l}${(0,Lp.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Xe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Xe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}wt.extendSubschemaData=G0;function J0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}wt.extendSubschemaMode=J0});var Ea=b((aD,Zp)=>{"use strict";Zp.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 Fp=b((cD,Up)=>{"use strict";var bt=Up.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(){};Po(t,n,o,e,"",e)};bt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Po(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in bt.arrayKeywords)for(var f=0;f<d.length;f++)Po(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in bt.propsKeywords){if(d&&typeof d=="object")for(var p in d)Po(e,t,r,d[p],o+"/"+u+"/"+Q0(p),i,o,u,n,p)}else(u in bt.keywords||e.allKeys&&!(u in bt.skipKeywords))&&Po(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function Q0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var cn=b(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var Y0=B(),X0=Ea(),ex=Fp(),tx=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function rx(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ta(e):t?Vp(e)<=t:!1}Te.inlineRef=rx;var nx=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ta(e){for(let t in e){if(nx.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ta)||typeof r=="object"&&Ta(r))return!0}return!1}function Vp(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!tx.has(r)&&(typeof e[r]=="object"&&(0,Y0.eachItem)(e[r],n=>t+=Vp(n)),t===1/0))return 1/0}return t}function Kp(e,t="",r){r!==!1&&(t=sr(t));let n=e.parse(t);return Hp(e,n)}Te.getFullPath=Kp;function Hp(e,t){return e.serialize(t).split("#")[0]+"#"}Te._getFullPath=Hp;var ox=/#\/?$/;function sr(e){return e?e.replace(ox,""):""}Te.normalizeId=sr;function ix(e,t,r){return r=sr(r),e.resolve(t,r)}Te.resolveUrl=ix;var sx=/^[a-z_][-a-z0-9._]*$/i;function ax(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=sr(e[r]||t),i={"":o},s=Kp(n,o,!1),a={},c=new Set;return ex(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])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let P=this.opts.uriResolver.resolve;if(x=sr(_?P(_,x):x),c.has(x))throw u(x);c.add(x);let I=this.refs[x];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?l(d,I.schema,x):x!==sr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function v(x){if(typeof x=="string"){if(!sx.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!X0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=ax});var dn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getData=vt.KeywordCxt=vt.validateFunctionCode=void 0;var Yp=Tp(),Wp=an(),Ra=wa(),Ro=an(),cx=Np(),ln=qp(),Pa=Bp(),S=C(),A=ct(),ux=cn(),ut=B(),un=sn();function lx(e){if(tm(e)&&(rm(e),em(e))){px(e);return}Xp(e,()=>(0,Yp.topBoolOrEmptySchema)(e))}vt.validateFunctionCode=lx;function Xp({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"; ${Gp(r,o)}`),fx(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${dx(o)}`,n.$async,()=>e.code(Gp(r,o)).code(i))}function dx(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 fx(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 px(e){let{schema:t,opts:r,gen:n}=e;Xp(e,()=>{r.$comment&&t.$comment&&om(e),_x(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&mx(e),nm(e),vx(e)})}function mx(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 Gp(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 hx(e,t){if(tm(e)&&(rm(e),em(e))){gx(e,t);return}(0,Yp.boolOrEmptySchema)(e,t)}function em({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 tm(e){return typeof e.schema!="boolean"}function gx(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&om(e),wx(e),bx(e);let i=n.const("_errs",A.default.errors);nm(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function rm(e){(0,ut.checkUnknownRules)(e),yx(e)}function nm(e,t){if(e.opts.jtd)return Jp(e,[],!1,t);let r=(0,Wp.getSchemaTypes)(e.schema),n=(0,Wp.coerceAndCheckDataType)(e,r);Jp(e,r,!n,t)}function yx(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function _x(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function wx(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,ux.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function bx(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function om({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 vx(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&&xx(e),t.return((0,S._)`${A.default.errors} === 0`))}function xx({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 Jp(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(i,u))){o.block(()=>sm(e,"$ref",u.all.$ref.definition));return}c.jtd||$x(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ra.shouldUseGroup)(i,f)&&(f.type?(o.if((0,Ro.checkDataType)(f.type,s,c.strictNumbers)),Qp(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,Ro.reportTypeError)(e)),o.endIf()):Qp(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Qp(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,cx.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ra.shouldUseRule)(n,i)&&sm(e,i.keyword,i.definition,t.type)})}function $x(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(kx(e,t),e.opts.allowUnionTypes||Sx(e,t),Ex(e,e.dataTypes))}function kx(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{im(e.dataTypes,r)||za(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),Px(e,t)}}function Sx(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&za(e,"use allowUnionTypes to allow union type keyword")}function Ex(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ra.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Tx(t,s))&&za(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Tx(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function im(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Px(e,t){let r=[];for(let n of e.dataTypes)im(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function za(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}var zo=class{constructor(t,r,n){if((0,ln.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ut.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",am(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,ln.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?un.reportExtraError:un.reportError)(this,this.def.error,r)}$dataError(){(0,un.reportError)(this,this.def.$dataError||un.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,un.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,Ro.checkDataTypes)(c,r,i.opts.strictNumbers,Ro.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,Pa.getSubschema)(this.it,t);(0,Pa.extendSubschemaData)(n,this.it,t),(0,Pa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return hx(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ut.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ut.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};vt.KeywordCxt=zo;function sm(e,t,r,n){let o=new zo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ln.funcKeywordCode)(o,r):"macro"in r?(0,ln.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ln.funcKeywordCode)(o,r)}var Rx=/^\/(?:[^~]|~0|~1)*$/,zx=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function am(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!Rx.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=zx.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ut.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}vt.getData=am});var Io=b(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Ia=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Oa.default=Ia});var fn=b(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var Aa=cn(),Na=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Aa.resolveUrl)(t,r,n),this.missingSchema=(0,Aa.normalizeId)((0,Aa.getFullPath)(t,this.missingRef))}};Ca.default=Na});var Ao=b(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Ue=C(),Ix=Io(),Mt=ct(),Fe=cn(),cm=B(),Ox=dn(),ar=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,Fe.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};je.SchemaEnv=ar;function ja(e){let t=um.call(this,e);if(t)return t;let r=(0,Fe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ue.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:Ix.default,code:(0,Ue._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Mt.default.data,parentData:Mt.default.parentData,parentDataProperty:Mt.default.parentDataProperty,dataNames:[Mt.default.data],dataPathArr:[Ue.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ue.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ue.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ue._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,Ox.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Mt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Mt.default.self}`,`${Mt.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 Ue.Name?void 0:m,items:h instanceof Ue.Name?void 0:h,dynamicProps:m instanceof Ue.Name,dynamicItems:h instanceof Ue.Name},p.source&&(p.source.evaluated=(0,Ue.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)}}je.compileSchema=ja;function Ax(e,t,r){var n;r=(0,Fe.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=Dx.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 ar({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=Nx.call(this,i)}je.resolveRef=Ax;function Nx(e){return(0,Fe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ja.call(this,e)}function um(e){for(let t of this._compilations)if(Cx(t,e))return t}je.getCompilingSchema=um;function Cx(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Dx(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Oo.call(this,e,t)}function Oo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Fe._getFullPath)(this.opts.uriResolver,r),o=(0,Fe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Da.call(this,r,e);let i=(0,Fe.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Oo.call(this,e,s);return typeof a?.schema!="object"?void 0:Da.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||ja.call(this,s),i===(0,Fe.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new ar({schema:a,schemaId:c,root:e,baseId:o})}return Da.call(this,r,s)}}je.resolveSchema=Oo;var jx=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Da(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,cm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!jx.has(a)&&l&&(t=(0,Fe.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,cm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Oo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new ar({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var lm=b((mD,Mx)=>{Mx.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 La=b((hD,gm)=>{"use strict";var qx=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),fm=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),Ma=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),pm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Lx=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function qa(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 Bx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function dm(e){return e.length=0,!0}function Zx(e,t,r){if(e.length){let n=qa(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Ux(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=Zx;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=dm}else{o.push(l);continue}}return o.length&&(a===dm?r.zone=o.join(""):s?n.push(o.join("")):n.push(qa(o))),r.address=n.join(""),r}function mm(e){if(Fx(e,":")<2)return{host:e,isIPV6:!1};let t=Ux(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 Fx(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Vx(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 Kx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Hx=/[@/?#:]/g,Wx=/[@/?#]/g;function hm(e,t){let r=t?Wx:Hx;return r.lastIndex=0,e.replace(r,n=>Kx[n])}function Gx(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(Ma(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&pm(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function Jx(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(Ma(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&pm(i)?t+=i:t+="%"+o,r+=2;continue}}Lx(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Qx(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(Ma(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Yx(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!fm(r)){let n=mm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=hm(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:Bx,recomposeAuthority:Yx,reescapeHostDelimiters:hm,normalizePercentEncoding:Gx,normalizePathEncoding:Jx,escapePreservingEscapes:Qx,removeDotSegments:Vx,isIPv4:fm,isUUID:qx,normalizeIPv6:mm,stringArrayToHexStripped:qa}});var vm=b((gD,bm)=>{"use strict";var{isUUID:Xx}=La(),e$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,t$=["http","https","ws","wss","urn","urn:uuid"];function r$(e){return t$.indexOf(e)!==-1}function Ba(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 _m(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 n$(e){return e.secure=Ba(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function o$(e){if((e.port===(Ba(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 i$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(e$);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=Za(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function s$(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=Za(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 a$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Xx(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function c$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var wm={scheme:"http",domainHost:!0,parse:ym,serialize:_m},u$={scheme:"https",domainHost:wm.domainHost,parse:ym,serialize:_m},No={scheme:"ws",domainHost:!0,parse:n$,serialize:o$},l$={scheme:"wss",domainHost:No.domainHost,parse:No.parse,serialize:No.serialize},d$={scheme:"urn",parse:i$,serialize:s$,skipNormalize:!0},f$={scheme:"urn:uuid",parse:a$,serialize:c$,skipNormalize:!0},Co={http:wm,https:u$,ws:No,wss:l$,urn:d$,"urn:uuid":f$};Object.setPrototypeOf(Co,null);function Za(e){return e&&(Co[e]||Co[e.toLowerCase()])||void 0}bm.exports={wsIsSecure:Ba,SCHEMES:Co,isValidSchemeName:r$,getSchemeHandler:Za}});var Tm=b((yD,Do)=>{"use strict";var{normalizeIPv6:p$,removeDotSegments:pn,recomposeAuthority:m$,normalizePercentEncoding:h$,normalizePathEncoding:g$,escapePreservingEscapes:y$,reescapeHostDelimiters:_$,isIPv4:w$,nonSimpleDomain:b$}=La(),{SCHEMES:v$,getSchemeHandler:$m}=vm();function x$(e,t){return typeof e=="string"?e=T$(e,t):typeof e=="object"&&(e=cr(qt(e,t),t)),e}function $$(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=km(cr(e,n),cr(t,n),n,!0);return n.skipEscape=!0,qt(o,n)}function km(e,t,r,n){let o={};return n||(e=cr(qt(e,r),r),t=cr(qt(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=pn(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=pn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=pn(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=pn(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 k$(e,t,r){let n=xm(e,r),o=xm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function qt(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=$m(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=h$(r.path):(r.path=y$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=m$(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=pn(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 S$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function E$(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 Sm(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(S$);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=E$(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(w$(n.host)===!1){let u=p$(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=$m(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&b$(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=_$(unescape(n.host),i))),n.path&&(n.path=g$(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 cr(e,t){return Sm(e,t).parsed}function T$(e,t){return Em(e,t).normalized}function Em(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Sm(e,t);return{normalized:n?e:qt(r,t),malformedAuthorityOrPort:n}}function xm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Em(e,t);return n?void 0:r}if(typeof e=="object")return qt(e,t)}var Ua={SCHEMES:v$,normalize:x$,resolve:$$,resolveComponent:km,equal:k$,serialize:qt,parse:cr};Do.exports=Ua;Do.exports.default=Ua;Do.exports.fastUri=Ua});var Rm=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Pm=Tm();Pm.code='require("ajv/dist/runtime/uri").default';Fa.default=Pm});var jm=b(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var P$=dn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return P$.KeywordCxt}});var ur=C();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var R$=Io(),Nm=fn(),z$=_a(),mn=Ao(),I$=C(),hn=cn(),jo=an(),Ka=B(),zm=lm(),O$=Rm(),Cm=(e,t)=>new RegExp(e,t);Cm.code="new RegExp";var A$=["removeAdditional","useDefaults","coerceTypes"],N$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),C$={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."},D$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Im=200;function j$(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,v,x,P,I,we,Ie,Ht,Ri;let Pr=e.strict,zi=(t=e.code)===null||t===void 0?void 0:t.optimize,Mu=zi===!0||zi===void 0?1:zi||0,qu=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Cm,w_=(o=e.uriResolver)!==null&&o!==void 0?o:O$.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Pr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Pr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Pr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Pr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Pr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Mu,regExp:qu}:{optimize:Mu,regExp:qu},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Im,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Im,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(we=e.validateSchema)!==null&&we!==void 0?we:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(Ht=e.unicodeRegExp)!==null&&Ht!==void 0?Ht:!0,int32range:(Ri=e.int32range)!==null&&Ri!==void 0?Ri:!0,uriResolver:w_}}var gn=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,...j$(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new I$.ValueScope({scope:{},prefixes:N$,es5:r,lines:n}),this.logger=U$(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,z$.getRules)(),Om.call(this,C$,t,"NOT SUPPORTED"),Om.call(this,D$,t,"DEPRECATED","warn"),this._metaOpts=B$.call(this),t.formats&&q$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&L$.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),M$.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=zm;n==="id"&&(o={...zm},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 Nm.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,hn.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=Am.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new mn.SchemaEnv({schema:{},schemaId:n});if(r=mn.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Am.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,hn.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(V$.call(this,n,r),!r)return(0,Ka.eachItem)(n,i=>Va.call(this,i)),this;H$.call(this,r);let o={...r,type:(0,jo.getJSONTypes)(r.type),schemaType:(0,jo.getJSONTypes)(r.schemaType)};return(0,Ka.eachItem)(n,o.type.length===0?i=>Va.call(this,i,o):i=>o.type.forEach(s=>Va.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]=Dm(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,hn.normalizeId)(s||n);let l=hn.getSchemaRefs.call(this,t,n);return c=new mn.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):mn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{mn.compileSchema.call(this,t)}finally{this.opts=r}}};gn.ValidationError=R$.default;gn.MissingRefError=Nm.default;fe.default=gn;function Om(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 Am(e){return e=(0,hn.normalizeId)(e),this.schemas[e]||this.refs[e]}function M$(){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 q$(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function L$(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 B$(){let e={...this.opts};for(let t of A$)delete e[t];return e}var Z$={log(){},warn(){},error(){}};function U$(e){if(e===!1)return Z$;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 F$=/^[a-z_$][a-z0-9_$:-]*$/i;function V$(e,t){let{RULES:r}=this;if((0,Ka.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!F$.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 Va(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,jo.getJSONTypes)(t.type),schemaType:(0,jo.getJSONTypes)(t.schemaType)}};t.before?K$.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 K$(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 H$(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Dm(t)),e.validateSchema=this.compile(t,!0))}var W$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Dm(e){return{anyOf:[e,W$]}}});var Mm=b(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var G$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ha.default=G$});var Zm=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.callRef=Lt.getValidate=void 0;var J$=fn(),qm=De(),Pe=C(),lr=ct(),Lm=Ao(),Mo=B(),Q$={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=Lm.resolveRef.call(c,l,o,r);if(u===void 0)throw new J$.default(n.opts.uriResolver,o,r);if(u instanceof Lm.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return qo(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return qo(e,(0,Pe._)`${m}.validate`,l,l.$async)}function f(m){let h=Bm(e,m);qo(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pe.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Bm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Lt.getValidate=Bm;function qo(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?lr.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,qm.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Pe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,qm.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Pe._)`${m}.errors`;o.assign(lr.default.vErrors,(0,Pe._)`${lr.default.vErrors} === null ? ${h} : ${lr.default.vErrors}.concat(${h})`),o.assign(lr.default.errors,(0,Pe._)`${lr.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=Mo.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Pe._)`${m}.evaluated.props`);i.props=Mo.mergeEvaluated.props(o,w,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Mo.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Pe._)`${m}.evaluated.items`);i.items=Mo.mergeEvaluated.items(o,w,i.items,Pe.Name)}}}Lt.callRef=qo;Lt.default=Q$});var Um=b(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var Y$=Mm(),X$=Zm(),ek=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Y$.default,X$.default];Wa.default=ek});var Fm=b(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Lo=C(),xt=Lo.operators,Bo={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},tk={message:({keyword:e,schemaCode:t})=>(0,Lo.str)`must be ${Bo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Lo._)`{comparison: ${Bo[e].okStr}, limit: ${t}}`},rk={keyword:Object.keys(Bo),type:"number",schemaType:"number",$data:!0,error:tk,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Lo._)`${r} ${Bo[t].fail} ${n} || isNaN(${r})`)}};Ga.default=rk});var Vm=b(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var yn=C(),nk={message:({schemaCode:e})=>(0,yn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,yn._)`{multipleOf: ${e}}`},ok={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nk,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,yn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,yn._)`${s} !== parseInt(${s})`;e.fail$data((0,yn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ja.default=ok});var Hm=b(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});function Km(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}Qa.default=Km;Km.code='require("ajv/dist/runtime/ucs2length").default'});var Wm=b(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Bt=C(),ik=B(),sk=Hm(),ak={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Bt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Bt._)`{limit: ${e}}`},ck={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ak,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Bt.operators.GT:Bt.operators.LT,s=o.opts.unicode===!1?(0,Bt._)`${r}.length`:(0,Bt._)`${(0,ik.useFunc)(e.gen,sk.default)}(${r})`;e.fail$data((0,Bt._)`${s} ${i} ${n}`)}};Ya.default=ck});var Gm=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var uk=De(),lk=B(),dr=C(),dk={message:({schemaCode:e})=>(0,dr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,dr._)`{pattern: ${e}}`},fk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:dk,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,dr._)`new RegExp`:(0,lk.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,dr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,dr._)`!${u}`)}else{let c=(0,uk.usePattern)(e,o);e.fail$data((0,dr._)`!${c}.test(${r})`)}}};Xa.default=fk});var Jm=b(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var _n=C(),pk={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,_n.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,_n._)`{limit: ${e}}`},mk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:pk,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?_n.operators.GT:_n.operators.LT;e.fail$data((0,_n._)`Object.keys(${r}).length ${o} ${n}`)}};ec.default=mk});var Qm=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var wn=De(),bn=C(),hk=B(),gk={message:({params:{missingProperty:e}})=>(0,bn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,bn._)`{missingProperty: ${e}}`},yk={keyword:"required",type:"object",schemaType:"array",$data:!0,error:gk,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,hk.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(bn.nil,d);else for(let p of r)(0,wn.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,wn.checkMissingProp)(e,r,p)),(0,wn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,wn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,wn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,bn.not)(m),()=>{e.error(),t.break()})},bn.nil)}}};tc.default=yk});var Ym=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var vn=C(),_k={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,vn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,vn._)`{limit: ${e}}`},wk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:_k,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?vn.operators.GT:vn.operators.LT;e.fail$data((0,vn._)`${r}.length ${o} ${n}`)}};rc.default=wk});var Zo=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var Xm=Ea();Xm.code='require("ajv/dist/runtime/equal").default';nc.default=Xm});var eh=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var oc=an(),pe=C(),bk=B(),vk=Zo(),xk={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},$k={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xk,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,oc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),w=(0,oc.checkDataTypes)(l,_,a.opts.strictNumbers,oc.DataType.Wrong),v=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${v}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${v}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${v}[${_}] = ${m}`)})}function p(m,h){let _=(0,bk.useFunc)(t,vk.default),w=t.name("outer");t.label(w).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};ic.default=$k});var th=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var sc=C(),kk=B(),Sk=Zo(),Ek={message:"must be equal to constant",params:({schemaCode:e})=>(0,sc._)`{allowedValue: ${e}}`},Tk={keyword:"const",$data:!0,error:Ek,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,kk.useFunc)(t,Sk.default)}(${r}, ${o})`):e.fail((0,sc._)`${i} !== ${r}`)}};ac.default=Tk});var rh=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var xn=C(),Pk=B(),Rk=Zo(),zk={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,xn._)`{allowedValues: ${e}}`},Ik={keyword:"enum",schemaType:"array",$data:!0,error:zk,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,Pk.useFunc)(t,Rk.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,xn.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,xn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,xn._)`${l()}(${r}, ${p}[${m}])`:(0,xn._)`${r} === ${h}`}}};cc.default=Ik});var nh=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Ok=Fm(),Ak=Vm(),Nk=Wm(),Ck=Gm(),Dk=Jm(),jk=Qm(),Mk=Ym(),qk=eh(),Lk=th(),Bk=rh(),Zk=[Ok.default,Ak.default,Nk.default,Ck.default,Dk.default,jk.default,Mk.default,qk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Lk.default,Bk.default];uc.default=Zk});var dc=b($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.validateAdditionalItems=void 0;var Zt=C(),lc=B(),Uk={message:({params:{len:e}})=>(0,Zt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zt._)`{limit: ${e}}`},Fk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Uk,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,lc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}oh(e,n)}};function oh(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Zt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Zt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,lc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Zt._)`${a} <= ${t.length}`);r.if((0,Zt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:lc.Type.Num},l),s.allErrors||r.if((0,Zt.not)(l),()=>r.break())})}}$n.validateAdditionalItems=oh;$n.default=Fk});var fc=b(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.validateTuple=void 0;var ih=C(),Uo=B(),Vk=De(),Kk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return sh(e,"additionalItems",t);r.items=!0,!(0,Uo.alwaysValidSchema)(r,t)&&e.ok((0,Vk.validateArray)(e))}};function sh(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=Uo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ih._)`${i}.length`);r.forEach((d,f)=>{(0,Uo.alwaysValidSchema)(a,d)||(n.if((0,ih._)`${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,Uo.checkStrictMode)(a,_,f.strictTuples)}}}kn.validateTuple=sh;kn.default=Kk});var ah=b(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Hk=fc(),Wk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Hk.validateTuple)(e,"items")};pc.default=Wk});var uh=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ch=C(),Gk=B(),Jk=De(),Qk=dc(),Yk={message:({params:{len:e}})=>(0,ch.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ch._)`{limit: ${e}}`},Xk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Yk,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,Gk.alwaysValidSchema)(n,t)&&(o?(0,Qk.validateAdditionalItems)(e,o):e.ok((0,Jk.validateArray)(e)))}};mc.default=Xk});var lh=b(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Me=C(),Fo=B(),eS={message:({params:{min:e,max:t}})=>t===void 0?(0,Me.str)`must contain at least ${e} valid item(s)`:(0,Me.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Me._)`{minContains: ${e}}`:(0,Me._)`{minContains: ${e}, maxContains: ${t}}`},tS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:eS,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,Me._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Fo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Fo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Fo.alwaysValidSchema)(i,r)){let h=(0,Me._)`${u} >= ${s}`;a!==void 0&&(h=(0,Me._)`${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,Me._)`${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:Fo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,Me._)`${h}++`),a===void 0?t.if((0,Me._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,Me._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,Me._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};hc.default=tS});var ph=b(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateSchemaDeps=et.validatePropertyDeps=et.error=void 0;var gc=C(),rS=B(),Sn=De();et.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,gc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,gc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var tS={keyword:"dependencies",type:"object",schemaType:"object",error:et.error,code(e){let[t,r]=rS(e);dh(e,t),fh(e,r)}};function rS({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 dh(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,Sn.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,Sn.checkReportMissingProp)(e,l)}):(r.if((0,gc._)`${c} && (${(0,Sn.checkMissingProp)(e,a,i)})`),(0,Sn.reportMissingProp)(e,i),r.else())}}et.validatePropertyDeps=dh;function fh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,eS.alwaysValidSchema)(i,t[a])||(r.if((0,Sn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}et.validateSchemaDeps=fh;et.default=tS});var hh=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var mh=C(),nS=B(),oS={message:"property name must be valid",params:({params:e})=>(0,mh._)`{propertyName: ${e.propertyName}}`},iS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:oS,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,nS.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,mh.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};yc.default=iS});var wc=b(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Vo=De(),Ve=C(),sS=ct(),Ko=B(),aS={message:"must NOT have additional properties",params:({params:e})=>(0,Ve._)`{additionalProperty: ${e.additionalProperty}}`},cS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aS,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,Ko.alwaysValidSchema)(s,r))return;let l=(0,Vo.allSchemaProperties)(n.properties),u=(0,Vo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Ve._)`${i} === ${sS.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 v=(0,Ko.schemaRefOrVal)(s,n.properties,"properties");w=(0,Vo.isOwnProperty)(t,v,_)}else l.length?w=(0,Ve.or)(...l.map(v=>(0,Ve._)`${_} === ${v}`)):w=Ve.nil;return u.length&&(w=(0,Ve.or)(w,...u.map(v=>(0,Ve._)`${(0,Vo.usePattern)(e,v)}.test(${_})`))),(0,Ve.not)(w)}function p(_){t.code((0,Ve._)`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,Ko.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,Ve.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,Ve.not)(w),()=>t.break()))}}function h(_,w,v){let x={keyword:"additionalProperties",dataProp:_,dataPropType:Ko.Type.Str};v===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};_c.default=cS});var _h=b(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var uS=dn(),gh=De(),bc=B(),yh=wc(),lS={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 uS.KeywordCxt(i,yh.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=bc.mergeEvaluated.props(t,(0,bc.toHash)(s),i.props));let a=s.filter(d=>!(0,bc.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)}}};vc.default=lS});var xh=b(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var wh=De(),Ho=C(),bh=B(),vh=B(),dS={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,wh.allSchemaProperties)(r),c=a.filter(h=>(0,bh.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 Ho.Name)&&(i.props=(0,vh.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,bh.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,Ho._)`${(0,wh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:vh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,Ho._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,Ho.not)(u),()=>t.break())})})}}};xc.default=dS});var $h=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var fS=B(),pS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,fS.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"}};$c.default=pS});var kh=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var mS=De(),hS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mS.validateUnion,error:{message:"must match a schema in anyOf"}};kc.default=hS});var Sh=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Wo=C(),gS=B(),yS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Wo._)`{passingSchemas: ${e.passing}}`},_S={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yS,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,gS.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Wo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Wo._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,Wo.Name)})})}}};Sc.default=_S});var Eh=b(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var wS=B(),bS={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,wS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Ec.default=bS});var Rh=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Go=C(),Ph=B(),vS={message:({params:e})=>(0,Go.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Go._)`{failingKeyword: ${e.ifClause}}`},xS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vS,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Ph.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Th(n,"then"),i=Th(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,Go.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,Go._)`${u}`):e.setParams({ifClause:u})}}}};function Th(e,t){let r=e.schema[t];return r!==void 0&&!(0,Ph.alwaysValidSchema)(e,r)}Tc.default=xS});var zh=b(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var $S=B(),kS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,$S.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Pc.default=kS});var Ih=b(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var SS=dc(),ES=ah(),TS=fc(),PS=uh(),RS=lh(),zS=ph(),IS=hh(),OS=wc(),AS=_h(),NS=xh(),CS=$h(),DS=kh(),jS=Sh(),MS=Eh(),qS=Rh(),LS=zh();function BS(e=!1){let t=[CS.default,DS.default,jS.default,MS.default,qS.default,LS.default,IS.default,OS.default,zS.default,AS.default,NS.default];return e?t.push(ES.default,PS.default):t.push(SS.default,TS.default),t.push(RS.default),t}Rc.default=BS});var Oh=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var ie=C(),ZS={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},US={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ZS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(w,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(w,h)),e.fail$data((0,ie.or)(v(),x()));function v(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${w}`}function x(){let P=u.$async?(0,ie._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ie._)`${w}(${n})`,I=(0,ie._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,ie._)`${w} && ${w} !== true && ${_} === ${t} && !${I}`}}function p(){let m=d.formats[i];if(!m){v();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(P());function v(){if(c.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function x(I){let we=I instanceof RegExp?(0,ie.regexpCode)(I):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Ie=r.scopeValue("formats",{key:i,ref:I,code:we});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,ie._)`${Ie}.validate`]:["string",I,Ie]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${w}(${n})`}return typeof _=="function"?(0,ie._)`${w}(${n})`:(0,ie._)`${w}.test(${n})`}}}};zc.default=US});var Ah=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var FS=Oh(),VS=[FS.default];Ic.default=VS});var Nh=b(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Dh=b(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var KS=Um(),HS=nh(),WS=Ih(),GS=Ah(),Ch=Nh(),JS=[KS.default,HS.default,(0,WS.default)(),GS.default,Ch.metadataVocabulary,Ch.contentVocabulary];Oc.default=JS});var Mh=b(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.DiscrError=void 0;var jh;(function(e){e.Tag="tag",e.Mapping="mapping"})(jh||(Jo.DiscrError=jh={}))});var Lh=b(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var pr=C(),Ac=Mh(),qh=Ao(),QS=fn(),YS=B(),XS={message:({params:{discrError:e,tagName:t}})=>e===Ac.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,pr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},eE={keyword:"discriminator",type:"object",schemaType:"object",error:XS,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,pr._)`${r}${(0,pr.getProperty)(a)}`);t.if((0,pr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Ac.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,pr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Ac.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,pr.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let P=0;P<s.length;P++){let I=s[P];if(I?.$ref&&!(0,YS.schemaHasRulesButRef)(I,i.self.RULES)){let Ie=I.$ref;if(I=qh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ie),I instanceof qh.SchemaEnv&&(I=I.schema),I===void 0)throw new QS.default(i.opts.uriResolver,i.baseId,Ie)}let we=(p=I?.properties)===null||p===void 0?void 0:p[a];if(typeof we!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(I)),v(we,P)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function v(P,I){if(P.const)x(P.const,I);else if(P.enum)for(let we of P.enum)x(we,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(P,I){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=I}}}};Nc.default=eE});var Bh=b((tj,tE)=>{tE.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 Dc=b((ee,Cc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var rE=jm(),nE=Dh(),oE=Lh(),Zh=Bh(),iE=["/properties"],Qo="http://json-schema.org/draft-07/schema",mr=class extends rE.default{_addVocabularies(){super._addVocabularies(),nE.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(oE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Zh,iE):Zh;this.addMetaSchema(t,Qo,!1),this.refs["http://json-schema.org/schema"]=Qo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Qo)?Qo:void 0)}};ee.Ajv=mr;Cc.exports=ee=mr;Cc.exports.Ajv=mr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=mr;var sE=dn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return sE.KeywordCxt}});var hr=C();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var aE=Io();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return aE.default}});var cE=fn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return cE.default}})});var Jh=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.formatNames=rt.fastFormats=rt.fullFormats=void 0;function tt(e,t){return{validate:e,compare:t}}rt.fullFormats={date:tt(Kh,Lc),time:tt(Mc(!0),Bc),"date-time":tt(Uh(!0),Wh),"iso-time":tt(Mc(),Hh),"iso-date-time":tt(Uh(),Gh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:mE,"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:vE,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:hE,int32:{type:"number",validate:_E},int64:{type:"number",validate:wE},float:{type:"number",validate:Vh},double:{type:"number",validate:Vh},password:!0,binary:!0};rt.fastFormats={...rt.fullFormats,date:tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Lc),time:tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bc),"date-time":tt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wh),"iso-time":tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hh),"iso-date-time":tt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Gh),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rt.formatNames=Object.keys(rt.fullFormats);function uE(e){return e%4===0&&(e%100!==0||e%400===0)}var lE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Kh(e){let t=lE.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&&uE(r)?29:dE[n])}function Lc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var jc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Mc(e){return function(r){let n=jc.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 Bc(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 Hh(e,t){if(!(e&&t))return;let r=jc.exec(e),n=jc.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 qc=/t|\s/i;function Uh(e){let t=Mc(e);return function(n){let o=n.split(qc);return o.length===2&&Kh(o[0])&&t(o[1])}}function Wh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Gh(e,t){if(!(e&&t))return;let[r,n]=e.split(qc),[o,i]=t.split(qc),s=Lc(r,o);if(s!==void 0)return s||Bc(n,i)}var fE=/\/|:/,pE=/^(?:[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 mE(e){return fE.test(e)&&pE.test(e)}var Fh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hE(e){return Fh.lastIndex=0,Fh.test(e)}var gE=-(2**31),yE=2**31-1;function _E(e){return Number.isInteger(e)&&e<=yE&&e>=gE}function wE(e){return Number.isInteger(e)}function Vh(){return!0}var bE=/[^\\]\\Z/;function vE(e){if(bE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Qh=b(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.formatLimitDefinition=void 0;var xE=Dc(),Ke=C(),$t=Ke.operators,Yo={formatMaximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},formatMinimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},formatExclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},formatExclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},$E={message:({keyword:e,schemaCode:t})=>(0,Ke.str)`should be ${Yo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ke._)`{comparison: ${Yo[e].okStr}, limit: ${t}}`};gr.formatLimitDefinition={keyword:Object.keys(Yo),type:"string",schemaType:"string",$data:!0,error:$E,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 xE.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,Ke._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ke.or)((0,Ke._)`typeof ${p} != "object"`,(0,Ke._)`${p} instanceof RegExp`,(0,Ke._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Ke._)`${s.code.formats}${(0,Ke.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ke._)`${f}.compare(${r}, ${n}) ${Yo[o].fail} 0`}},dependencies:["format"]};var kE=e=>(e.addKeyword(gr.formatLimitDefinition),e);gr.default=kE});var tg=b((En,eg)=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});var yr=Jh(),SE=Qh(),Zc=C(),Yh=new Zc.Name("fullFormats"),EE=new Zc.Name("fastFormats"),Uc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Xh(e,t,yr.fullFormats,Yh),e;let[r,n]=t.mode==="fast"?[yr.fastFormats,EE]:[yr.fullFormats,Yh],o=t.formats||yr.formatNames;return Xh(e,o,r,n),t.keywords&&(0,SE.default)(e),e};Uc.get=(e,t="full")=>{let n=(t==="fast"?yr.fastFormats:yr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Xh(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Zc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}eg.exports=En=Uc;Object.defineProperty(En,"__esModule",{value:!0});En.default=Uc});var lg=b((hj,ug)=>{ug.exports=cg;cg.sync=zE;var sg=dt("fs");function RE(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 ag(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:RE(t,r)}function cg(e,t,r){sg.stat(e,function(n,o){r(n,n?!1:ag(o,e,t))})}function zE(e,t){return ag(sg.statSync(e),e,t)}});var hg=b((gj,mg)=>{mg.exports=fg;fg.sync=IE;var dg=dt("fs");function fg(e,t,r){dg.stat(e,function(n,o){r(n,n?!1:pg(o,t))})}function IE(e,t){return pg(dg.statSync(e),t)}function pg(e,t){return e.isFile()&&OE(e,t)}function OE(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=b((_j,gg)=>{var yj=dt("fs"),ni;process.platform==="win32"||global.TESTING_WINDOWS?ni=lg():ni=hg();gg.exports=Fc;Fc.sync=AE;function Fc(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){Fc(e,t||{},function(i,s){i?o(i):n(s)})})}ni(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function AE(e,t){try{return ni.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var kg=b((wj,$g)=>{var _r=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",_g=dt("path"),NE=_r?";":":",wg=yg(),bg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),vg=(e,t)=>{let r=t.colon||NE,n=e.match(/\//)||_r&&e.match(/\\/)?[""]:[..._r?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=_r?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=_r?o.split(r):[""];return _r&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},xg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=vg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(bg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=_g.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];wg(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)},CE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=vg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=_g.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(wg.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 bg(e)};$g.exports=xg;xg.sync=CE});var Eg=b((bj,Vc)=>{"use strict";var Sg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Vc.exports=Sg;Vc.exports.default=Sg});var zg=b((vj,Rg)=>{"use strict";var Tg=dt("path"),DE=kg(),jE=Eg();function Pg(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=DE.sync(e.command,{path:r[jE({env:r})],pathExt:t?Tg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Tg.resolve(o?e.options.cwd:"",s)),s}function ME(e){return Pg(e)||Pg(e,!0)}Rg.exports=ME});var Ig=b((xj,Hc)=>{"use strict";var Kc=/([()\][%!^"`<>&|;, *?])/g;function qE(e){return e=e.replace(Kc,"^$1"),e}function LE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Kc,"^$1"),t&&(e=e.replace(Kc,"^$1")),e}Hc.exports.command=qE;Hc.exports.argument=LE});var Ag=b(($j,Og)=>{"use strict";Og.exports=/^#!(.*)/});var Cg=b((kj,Ng)=>{"use strict";var BE=Ag();Ng.exports=(e="")=>{let t=e.match(BE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var jg=b((Sj,Dg)=>{"use strict";var Wc=dt("fs"),ZE=Cg();function UE(e){let r=Buffer.alloc(150),n;try{n=Wc.openSync(e,"r"),Wc.readSync(n,r,0,150,0),Wc.closeSync(n)}catch{}return ZE(r.toString())}Dg.exports=UE});var Bg=b((Ej,Lg)=>{"use strict";var FE=dt("path"),Mg=zg(),qg=Ig(),VE=jg(),KE=process.platform==="win32",HE=/\.(?:com|exe)$/i,WE=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function GE(e){e.file=Mg(e);let t=e.file&&VE(e.file);return t?(e.args.unshift(e.file),e.command=t,Mg(e)):e.file}function JE(e){if(!KE)return e;let t=GE(e),r=!HE.test(t);if(e.options.forceShell||r){let n=WE.test(t);e.command=FE.normalize(e.command),e.command=qg.command(e.command),e.args=e.args.map(i=>qg.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 QE(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:JE(n)}Lg.exports=QE});var Fg=b((Tj,Ug)=>{"use strict";var Gc=process.platform==="win32";function Jc(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 YE(e,t){if(!Gc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Zg(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Zg(e,t){return Gc&&e===1&&!t.file?Jc(t.original,"spawn"):null}function XE(e,t){return Gc&&e===1&&!t.file?Jc(t.original,"spawnSync"):null}Ug.exports={hookChildProcess:YE,verifyENOENT:Zg,verifyENOENTSync:XE,notFoundError:Jc}});var Hg=b((Pj,wr)=>{"use strict";var Vg=dt("child_process"),Qc=Bg(),Yc=Fg();function Kg(e,t,r){let n=Qc(e,t,r),o=Vg.spawn(n.command,n.args,n.options);return Yc.hookChildProcess(o,n),o}function eT(e,t,r){let n=Qc(e,t,r),o=Vg.spawnSync(n.command,n.args,n.options);return o.error=o.error||Yc.verifyENOENTSync(o.status,n),o}wr.exports=Kg;wr.exports.spawn=Kg;wr.exports.sync=eT;wr.exports._parse=Qc;wr.exports._enoent=Yc});import{readFile as Kz,mkdir as Hz,writeFile as Wz}from"node:fs/promises";import{dirname as Gz,join as g_}from"node:path";var mI=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 hI=Symbol("zod_brand"),ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Zn={};function Oe(e){return e&&Object.assign(Zn,e),Zn}var F={};Lu(F,{BIGINT_FORMAT_RANGES:()=>Zu,Class:()=>Ni,NUMBER_FORMAT_RANGES:()=>Zi,aborted:()=>Pt,allowsEval:()=>qi,assert:()=>P_,assertEqual:()=>k_,assertIs:()=>E_,assertNever:()=>T_,assertNotEqual:()=>S_,assignProp:()=>Mi,cached:()=>zr,captureStackTrace:()=>Fn,cleanEnum:()=>B_,cleanRegex:()=>Or,clone:()=>Je,createTransparentProxy:()=>N_,defineLazy:()=>W,esc:()=>Tt,escapeRegex:()=>ft,extend:()=>j_,finalizeIssue:()=>Le,floatSafeRemainder:()=>ji,getElementAtPath:()=>R_,getEnumValues:()=>Ci,getLengthableOrigin:()=>Ar,getParsedType:()=>A_,getSizableOrigin:()=>Uu,isObject:()=>Wt,isPlainObject:()=>Gt,issue:()=>Ui,joinValues:()=>Un,jsonStringifyReplacer:()=>Di,merge:()=>M_,normalizeParams:()=>R,nullish:()=>Ir,numKeys:()=>O_,omit:()=>D_,optionalKeys:()=>Bi,partial:()=>q_,pick:()=>C_,prefixIssues:()=>Qe,primitiveTypes:()=>Bu,promiseAllObject:()=>z_,propertyKeyTypes:()=>Li,randomString:()=>I_,required:()=>L_,stringifyPrimitive:()=>Vn,unwrapMessage:()=>Rr});function k_(e){return e}function S_(e){return e}function E_(e){}function T_(e){throw new Error}function P_(e){}function Ci(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 Un(e,t="|"){return e.map(r=>Vn(r)).join(t)}function Di(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 Ir(e){return e==null}function Or(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ji(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 Mi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function R_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function z_(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 I_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Tt(e){return JSON.stringify(e)}var Fn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qi=zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Gt(e){if(Wt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Wt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function O_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var A_=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}`)}},Li=new Set(["string","number","symbol"]),Bu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function R(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 N_(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 Vn(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Bi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zi={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]},Zu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function C_(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Je(e,{...e._zod.def,shape:r,checks:[]})}function D_(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Je(e,{...e._zod.def,shape:r,checks:[]})}function j_(e,t){if(!Gt(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Mi(this,"shape",n),n},checks:[]};return Je(e,r)}function M_(e,t){return Je(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Mi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function q_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Je(t,{...t._zod.def,shape:o,checks:[]})}function L_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Je(t,{...t._zod.def,shape:o,checks:[]})}function Pt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Qe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Rr(e){return typeof e=="string"?e:e?.message}function Le(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Rr(e.inst?._zod.def?.error?.(e))??Rr(t?.error?.(e))??Rr(r.customError?.(e))??Rr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Uu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ar(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ui(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function B_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ni=class{constructor(...t){}};var Fu=(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,Di,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kn=y("$ZodError",Fu),Fi=y("$ZodError",Fu,{Parent:Error});function Vu(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 Ku(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 Hu=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ot;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Le(c,i,Oe())));throw Fn(a,o?.callee),a}return s.value};var Wu=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=>Le(c,i,Oe())));throw Fn(a,o?.callee),a}return s.value};var Vi=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ot;return i.issues.length?{success:!1,error:new(e??Kn)(i.issues.map(s=>Le(s,o,Oe())))}:{success:!0,data:i.value}},Nr=Vi(Fi),Ki=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=>Le(s,o,Oe())))}:{success:!0,data:i.value}},Hn=Ki(Fi);var Gu=/^[cC][^\s-]{8,}$/,Ju=/^[0-9a-z]+$/,Qu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yu=/^[0-9a-vA-V]{20}$/,Xu=/^[A-Za-z0-9]{27}$/,el=/^[a-zA-Z0-9_-]{21}$/,tl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var rl=/^([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})$/,Hi=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 nl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var U_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ol(){return new RegExp(U_,"u")}var il=/^(?:(?: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])$/,sl=/^(([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})$/,al=/^((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])$/,cl=/^(([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}=))?$/,Wi=/^[A-Za-z0-9_-]*$/,ll=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var dl=/^\+(?:[0-9]){6,14}[0-9]$/,fl="(?:(?:\\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])))",pl=new RegExp(`^${fl}$`);function ml(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 hl(e){return new RegExp(`^${ml(e)}$`)}function gl(e){let t=ml({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(`^${fl}T(?:${n})$`)}var yl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var _l=/^\d+$/,wl=/^-?\d+(?:\.\d+)?/i,bl=/true|false/i,vl=/null/i;var xl=/^[^A-Z]*$/,$l=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),kl={number:"number",bigint:"bigint",object:"date"},Ji=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=kl[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})}}),Qi=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=kl[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})}}),Sl=y("$ZodCheckMultipleOf",(e,t)=>{me.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ji(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})}}),El=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Zi[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=_l)}),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 Tl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Ar(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Pl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Ar(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rl=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Ar(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Cr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),zl=y("$ZodCheckRegex",(e,t)=>{Cr.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})}}),Il=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xl),Cr.init(e,t)}),Ol=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$l),Cr.init(e,t)}),Al=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=ft(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Nl=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${ft(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Cl=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${ft(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Dl=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Wn=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 nS={keyword:"dependencies",type:"object",schemaType:"object",error:et.error,code(e){let[t,r]=oS(e);dh(e,t),fh(e,r)}};function oS({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 dh(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,Sn.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,Sn.checkReportMissingProp)(e,l)}):(r.if((0,gc._)`${c} && (${(0,Sn.checkMissingProp)(e,a,i)})`),(0,Sn.reportMissingProp)(e,i),r.else())}}et.validatePropertyDeps=dh;function fh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,rS.alwaysValidSchema)(i,t[a])||(r.if((0,Sn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}et.validateSchemaDeps=fh;et.default=nS});var hh=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var mh=C(),iS=B(),sS={message:"property name must be valid",params:({params:e})=>(0,mh._)`{propertyName: ${e.propertyName}}`},aS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:sS,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,iS.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,mh.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};yc.default=aS});var wc=b(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Vo=De(),Ve=C(),cS=ct(),Ko=B(),uS={message:"must NOT have additional properties",params:({params:e})=>(0,Ve._)`{additionalProperty: ${e.additionalProperty}}`},lS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:uS,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,Ko.alwaysValidSchema)(s,r))return;let l=(0,Vo.allSchemaProperties)(n.properties),u=(0,Vo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Ve._)`${i} === ${cS.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 v=(0,Ko.schemaRefOrVal)(s,n.properties,"properties");w=(0,Vo.isOwnProperty)(t,v,_)}else l.length?w=(0,Ve.or)(...l.map(v=>(0,Ve._)`${_} === ${v}`)):w=Ve.nil;return u.length&&(w=(0,Ve.or)(w,...u.map(v=>(0,Ve._)`${(0,Vo.usePattern)(e,v)}.test(${_})`))),(0,Ve.not)(w)}function p(_){t.code((0,Ve._)`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,Ko.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,Ve.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,Ve.not)(w),()=>t.break()))}}function h(_,w,v){let x={keyword:"additionalProperties",dataProp:_,dataPropType:Ko.Type.Str};v===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};_c.default=lS});var _h=b(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var dS=dn(),gh=De(),bc=B(),yh=wc(),fS={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 dS.KeywordCxt(i,yh.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=bc.mergeEvaluated.props(t,(0,bc.toHash)(s),i.props));let a=s.filter(d=>!(0,bc.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)}}};vc.default=fS});var xh=b(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var wh=De(),Ho=C(),bh=B(),vh=B(),pS={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,wh.allSchemaProperties)(r),c=a.filter(h=>(0,bh.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 Ho.Name)&&(i.props=(0,vh.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,bh.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,Ho._)`${(0,wh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:vh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,Ho._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,Ho.not)(u),()=>t.break())})})}}};xc.default=pS});var $h=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var mS=B(),hS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,mS.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"}};$c.default=hS});var kh=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var gS=De(),yS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:gS.validateUnion,error:{message:"must match a schema in anyOf"}};kc.default=yS});var Sh=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Wo=C(),_S=B(),wS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Wo._)`{passingSchemas: ${e.passing}}`},bS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wS,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,_S.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Wo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Wo._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,Wo.Name)})})}}};Sc.default=bS});var Eh=b(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var vS=B(),xS={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,vS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Ec.default=xS});var Rh=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Go=C(),Ph=B(),$S={message:({params:e})=>(0,Go.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Go._)`{failingKeyword: ${e.ifClause}}`},kS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$S,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Ph.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Th(n,"then"),i=Th(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,Go.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,Go._)`${u}`):e.setParams({ifClause:u})}}}};function Th(e,t){let r=e.schema[t];return r!==void 0&&!(0,Ph.alwaysValidSchema)(e,r)}Tc.default=kS});var zh=b(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var SS=B(),ES={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,SS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Pc.default=ES});var Ih=b(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var TS=dc(),PS=ah(),RS=fc(),zS=uh(),IS=lh(),OS=ph(),AS=hh(),NS=wc(),CS=_h(),DS=xh(),jS=$h(),MS=kh(),qS=Sh(),LS=Eh(),BS=Rh(),ZS=zh();function US(e=!1){let t=[jS.default,MS.default,qS.default,LS.default,BS.default,ZS.default,AS.default,NS.default,OS.default,CS.default,DS.default];return e?t.push(PS.default,zS.default):t.push(TS.default,RS.default),t.push(IS.default),t}Rc.default=US});var Oh=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var ie=C(),FS={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},VS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:FS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(w,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(w,h)),e.fail$data((0,ie.or)(v(),x()));function v(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${w}`}function x(){let P=u.$async?(0,ie._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ie._)`${w}(${n})`,I=(0,ie._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,ie._)`${w} && ${w} !== true && ${_} === ${t} && !${I}`}}function p(){let m=d.formats[i];if(!m){v();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(P());function v(){if(c.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function x(I){let we=I instanceof RegExp?(0,ie.regexpCode)(I):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Ie=r.scopeValue("formats",{key:i,ref:I,code:we});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,ie._)`${Ie}.validate`]:["string",I,Ie]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${w}(${n})`}return typeof _=="function"?(0,ie._)`${w}(${n})`:(0,ie._)`${w}.test(${n})`}}}};zc.default=VS});var Ah=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var KS=Oh(),HS=[KS.default];Ic.default=HS});var Nh=b(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Dh=b(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var WS=Um(),GS=nh(),JS=Ih(),QS=Ah(),Ch=Nh(),YS=[WS.default,GS.default,(0,JS.default)(),QS.default,Ch.metadataVocabulary,Ch.contentVocabulary];Oc.default=YS});var Mh=b(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.DiscrError=void 0;var jh;(function(e){e.Tag="tag",e.Mapping="mapping"})(jh||(Jo.DiscrError=jh={}))});var Lh=b(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var pr=C(),Ac=Mh(),qh=Ao(),XS=fn(),eE=B(),tE={message:({params:{discrError:e,tagName:t}})=>e===Ac.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,pr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},rE={keyword:"discriminator",type:"object",schemaType:"object",error:tE,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,pr._)`${r}${(0,pr.getProperty)(a)}`);t.if((0,pr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Ac.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,pr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Ac.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,pr.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let P=0;P<s.length;P++){let I=s[P];if(I?.$ref&&!(0,eE.schemaHasRulesButRef)(I,i.self.RULES)){let Ie=I.$ref;if(I=qh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ie),I instanceof qh.SchemaEnv&&(I=I.schema),I===void 0)throw new XS.default(i.opts.uriResolver,i.baseId,Ie)}let we=(p=I?.properties)===null||p===void 0?void 0:p[a];if(typeof we!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(I)),v(we,P)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function v(P,I){if(P.const)x(P.const,I);else if(P.enum)for(let we of P.enum)x(we,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(P,I){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=I}}}};Nc.default=rE});var Bh=b((ij,nE)=>{nE.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 Dc=b((ee,Cc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var oE=jm(),iE=Dh(),sE=Lh(),Zh=Bh(),aE=["/properties"],Qo="http://json-schema.org/draft-07/schema",mr=class extends oE.default{_addVocabularies(){super._addVocabularies(),iE.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(sE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Zh,aE):Zh;this.addMetaSchema(t,Qo,!1),this.refs["http://json-schema.org/schema"]=Qo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Qo)?Qo:void 0)}};ee.Ajv=mr;Cc.exports=ee=mr;Cc.exports.Ajv=mr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=mr;var cE=dn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return cE.KeywordCxt}});var hr=C();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var uE=Io();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return uE.default}});var lE=fn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return lE.default}})});var Jh=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.formatNames=rt.fastFormats=rt.fullFormats=void 0;function tt(e,t){return{validate:e,compare:t}}rt.fullFormats={date:tt(Kh,Lc),time:tt(Mc(!0),Bc),"date-time":tt(Uh(!0),Wh),"iso-time":tt(Mc(),Hh),"iso-date-time":tt(Uh(),Gh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:gE,"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:$E,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:yE,int32:{type:"number",validate:bE},int64:{type:"number",validate:vE},float:{type:"number",validate:Vh},double:{type:"number",validate:Vh},password:!0,binary:!0};rt.fastFormats={...rt.fullFormats,date:tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Lc),time:tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bc),"date-time":tt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wh),"iso-time":tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hh),"iso-date-time":tt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Gh),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rt.formatNames=Object.keys(rt.fullFormats);function dE(e){return e%4===0&&(e%100!==0||e%400===0)}var fE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,pE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Kh(e){let t=fE.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&&dE(r)?29:pE[n])}function Lc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var jc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Mc(e){return function(r){let n=jc.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 Bc(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 Hh(e,t){if(!(e&&t))return;let r=jc.exec(e),n=jc.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 qc=/t|\s/i;function Uh(e){let t=Mc(e);return function(n){let o=n.split(qc);return o.length===2&&Kh(o[0])&&t(o[1])}}function Wh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Gh(e,t){if(!(e&&t))return;let[r,n]=e.split(qc),[o,i]=t.split(qc),s=Lc(r,o);if(s!==void 0)return s||Bc(n,i)}var mE=/\/|:/,hE=/^(?:[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 gE(e){return mE.test(e)&&hE.test(e)}var Fh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function yE(e){return Fh.lastIndex=0,Fh.test(e)}var _E=-(2**31),wE=2**31-1;function bE(e){return Number.isInteger(e)&&e<=wE&&e>=_E}function vE(e){return Number.isInteger(e)}function Vh(){return!0}var xE=/[^\\]\\Z/;function $E(e){if(xE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Qh=b(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.formatLimitDefinition=void 0;var kE=Dc(),Ke=C(),$t=Ke.operators,Yo={formatMaximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},formatMinimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},formatExclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},formatExclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},SE={message:({keyword:e,schemaCode:t})=>(0,Ke.str)`should be ${Yo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ke._)`{comparison: ${Yo[e].okStr}, limit: ${t}}`};gr.formatLimitDefinition={keyword:Object.keys(Yo),type:"string",schemaType:"string",$data:!0,error:SE,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 kE.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,Ke._)`${f}[${c.schemaCode}]`);e.fail$data((0,Ke.or)((0,Ke._)`typeof ${p} != "object"`,(0,Ke._)`${p} instanceof RegExp`,(0,Ke._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Ke._)`${s.code.formats}${(0,Ke.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,Ke._)`${f}.compare(${r}, ${n}) ${Yo[o].fail} 0`}},dependencies:["format"]};var EE=e=>(e.addKeyword(gr.formatLimitDefinition),e);gr.default=EE});var tg=b((En,eg)=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});var yr=Jh(),TE=Qh(),Zc=C(),Yh=new Zc.Name("fullFormats"),PE=new Zc.Name("fastFormats"),Uc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Xh(e,t,yr.fullFormats,Yh),e;let[r,n]=t.mode==="fast"?[yr.fastFormats,PE]:[yr.fullFormats,Yh],o=t.formats||yr.formatNames;return Xh(e,o,r,n),t.keywords&&(0,TE.default)(e),e};Uc.get=(e,t="full")=>{let n=(t==="fast"?yr.fastFormats:yr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Xh(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Zc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}eg.exports=En=Uc;Object.defineProperty(En,"__esModule",{value:!0});En.default=Uc});var lg=b((wj,ug)=>{ug.exports=cg;cg.sync=OE;var sg=dt("fs");function IE(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 ag(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:IE(t,r)}function cg(e,t,r){sg.stat(e,function(n,o){r(n,n?!1:ag(o,e,t))})}function OE(e,t){return ag(sg.statSync(e),e,t)}});var hg=b((bj,mg)=>{mg.exports=fg;fg.sync=AE;var dg=dt("fs");function fg(e,t,r){dg.stat(e,function(n,o){r(n,n?!1:pg(o,t))})}function AE(e,t){return pg(dg.statSync(e),t)}function pg(e,t){return e.isFile()&&NE(e,t)}function NE(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=b((xj,gg)=>{var vj=dt("fs"),ni;process.platform==="win32"||global.TESTING_WINDOWS?ni=lg():ni=hg();gg.exports=Fc;Fc.sync=CE;function Fc(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){Fc(e,t||{},function(i,s){i?o(i):n(s)})})}ni(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function CE(e,t){try{return ni.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var kg=b(($j,$g)=>{var _r=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",_g=dt("path"),DE=_r?";":":",wg=yg(),bg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),vg=(e,t)=>{let r=t.colon||DE,n=e.match(/\//)||_r&&e.match(/\\/)?[""]:[..._r?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=_r?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=_r?o.split(r):[""];return _r&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},xg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=vg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(bg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=_g.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];wg(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)},jE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=vg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=_g.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(wg.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 bg(e)};$g.exports=xg;xg.sync=jE});var Eg=b((kj,Vc)=>{"use strict";var Sg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Vc.exports=Sg;Vc.exports.default=Sg});var zg=b((Sj,Rg)=>{"use strict";var Tg=dt("path"),ME=kg(),qE=Eg();function Pg(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=ME.sync(e.command,{path:r[qE({env:r})],pathExt:t?Tg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Tg.resolve(o?e.options.cwd:"",s)),s}function LE(e){return Pg(e)||Pg(e,!0)}Rg.exports=LE});var Ig=b((Ej,Hc)=>{"use strict";var Kc=/([()\][%!^"`<>&|;, *?])/g;function BE(e){return e=e.replace(Kc,"^$1"),e}function ZE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Kc,"^$1"),t&&(e=e.replace(Kc,"^$1")),e}Hc.exports.command=BE;Hc.exports.argument=ZE});var Ag=b((Tj,Og)=>{"use strict";Og.exports=/^#!(.*)/});var Cg=b((Pj,Ng)=>{"use strict";var UE=Ag();Ng.exports=(e="")=>{let t=e.match(UE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var jg=b((Rj,Dg)=>{"use strict";var Wc=dt("fs"),FE=Cg();function VE(e){let r=Buffer.alloc(150),n;try{n=Wc.openSync(e,"r"),Wc.readSync(n,r,0,150,0),Wc.closeSync(n)}catch{}return FE(r.toString())}Dg.exports=VE});var Bg=b((zj,Lg)=>{"use strict";var KE=dt("path"),Mg=zg(),qg=Ig(),HE=jg(),WE=process.platform==="win32",GE=/\.(?:com|exe)$/i,JE=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function QE(e){e.file=Mg(e);let t=e.file&&HE(e.file);return t?(e.args.unshift(e.file),e.command=t,Mg(e)):e.file}function YE(e){if(!WE)return e;let t=QE(e),r=!GE.test(t);if(e.options.forceShell||r){let n=JE.test(t);e.command=KE.normalize(e.command),e.command=qg.command(e.command),e.args=e.args.map(i=>qg.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 XE(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:YE(n)}Lg.exports=XE});var Fg=b((Ij,Ug)=>{"use strict";var Gc=process.platform==="win32";function Jc(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 eT(e,t){if(!Gc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=Zg(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function Zg(e,t){return Gc&&e===1&&!t.file?Jc(t.original,"spawn"):null}function tT(e,t){return Gc&&e===1&&!t.file?Jc(t.original,"spawnSync"):null}Ug.exports={hookChildProcess:eT,verifyENOENT:Zg,verifyENOENTSync:tT,notFoundError:Jc}});var Hg=b((Oj,wr)=>{"use strict";var Vg=dt("child_process"),Qc=Bg(),Yc=Fg();function Kg(e,t,r){let n=Qc(e,t,r),o=Vg.spawn(n.command,n.args,n.options);return Yc.hookChildProcess(o,n),o}function rT(e,t,r){let n=Qc(e,t,r),o=Vg.spawnSync(n.command,n.args,n.options);return o.error=o.error||Yc.verifyENOENTSync(o.status,n),o}wr.exports=Kg;wr.exports.spawn=Kg;wr.exports.sync=rT;wr.exports._parse=Qc;wr.exports._enoent=Yc});import{readFile as Jz,mkdir as Qz,writeFile as Yz}from"node:fs/promises";import{dirname as Xz,join as __}from"node:path";var _I=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 wI=Symbol("zod_brand"),ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Zn={};function Oe(e){return e&&Object.assign(Zn,e),Zn}var F={};Lu(F,{BIGINT_FORMAT_RANGES:()=>Zu,Class:()=>Ni,NUMBER_FORMAT_RANGES:()=>Zi,aborted:()=>Pt,allowsEval:()=>qi,assert:()=>z_,assertEqual:()=>E_,assertIs:()=>P_,assertNever:()=>R_,assertNotEqual:()=>T_,assignProp:()=>Mi,cached:()=>zr,captureStackTrace:()=>Fn,cleanEnum:()=>U_,cleanRegex:()=>Or,clone:()=>Je,createTransparentProxy:()=>D_,defineLazy:()=>W,esc:()=>Tt,escapeRegex:()=>ft,extend:()=>q_,finalizeIssue:()=>Le,floatSafeRemainder:()=>ji,getElementAtPath:()=>I_,getEnumValues:()=>Ci,getLengthableOrigin:()=>Ar,getParsedType:()=>C_,getSizableOrigin:()=>Uu,isObject:()=>Wt,isPlainObject:()=>Gt,issue:()=>Ui,joinValues:()=>Un,jsonStringifyReplacer:()=>Di,merge:()=>L_,normalizeParams:()=>R,nullish:()=>Ir,numKeys:()=>N_,omit:()=>M_,optionalKeys:()=>Bi,partial:()=>B_,pick:()=>j_,prefixIssues:()=>Qe,primitiveTypes:()=>Bu,promiseAllObject:()=>O_,propertyKeyTypes:()=>Li,randomString:()=>A_,required:()=>Z_,stringifyPrimitive:()=>Vn,unwrapMessage:()=>Rr});function E_(e){return e}function T_(e){return e}function P_(e){}function R_(e){throw new Error}function z_(e){}function Ci(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 Un(e,t="|"){return e.map(r=>Vn(r)).join(t)}function Di(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 Ir(e){return e==null}function Or(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ji(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 Mi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function I_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function O_(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 A_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Tt(e){return JSON.stringify(e)}var Fn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qi=zr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Gt(e){if(Wt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Wt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function N_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var C_=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}`)}},Li=new Set(["string","number","symbol"]),Bu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function R(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 D_(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 Vn(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Bi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zi={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]},Zu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function j_(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Je(e,{...e._zod.def,shape:r,checks:[]})}function M_(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Je(e,{...e._zod.def,shape:r,checks:[]})}function q_(e,t){if(!Gt(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Mi(this,"shape",n),n},checks:[]};return Je(e,r)}function L_(e,t){return Je(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Mi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function B_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Je(t,{...t._zod.def,shape:o,checks:[]})}function Z_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Je(t,{...t._zod.def,shape:o,checks:[]})}function Pt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Qe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Rr(e){return typeof e=="string"?e:e?.message}function Le(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Rr(e.inst?._zod.def?.error?.(e))??Rr(t?.error?.(e))??Rr(r.customError?.(e))??Rr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Uu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ar(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ui(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function U_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ni=class{constructor(...t){}};var Fu=(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,Di,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kn=y("$ZodError",Fu),Fi=y("$ZodError",Fu,{Parent:Error});function Vu(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 Ku(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 Hu=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ot;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Le(c,i,Oe())));throw Fn(a,o?.callee),a}return s.value};var Wu=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=>Le(c,i,Oe())));throw Fn(a,o?.callee),a}return s.value};var Vi=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ot;return i.issues.length?{success:!1,error:new(e??Kn)(i.issues.map(s=>Le(s,o,Oe())))}:{success:!0,data:i.value}},Nr=Vi(Fi),Ki=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=>Le(s,o,Oe())))}:{success:!0,data:i.value}},Hn=Ki(Fi);var Gu=/^[cC][^\s-]{8,}$/,Ju=/^[0-9a-z]+$/,Qu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yu=/^[0-9a-vA-V]{20}$/,Xu=/^[A-Za-z0-9]{27}$/,el=/^[a-zA-Z0-9_-]{21}$/,tl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var rl=/^([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})$/,Hi=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 nl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var V_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ol(){return new RegExp(V_,"u")}var il=/^(?:(?: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])$/,sl=/^(([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})$/,al=/^((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])$/,cl=/^(([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}=))?$/,Wi=/^[A-Za-z0-9_-]*$/,ll=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var dl=/^\+(?:[0-9]){6,14}[0-9]$/,fl="(?:(?:\\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])))",pl=new RegExp(`^${fl}$`);function ml(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 hl(e){return new RegExp(`^${ml(e)}$`)}function gl(e){let t=ml({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(`^${fl}T(?:${n})$`)}var yl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var _l=/^\d+$/,wl=/^-?\d+(?:\.\d+)?/i,bl=/true|false/i,vl=/null/i;var xl=/^[^A-Z]*$/,$l=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),kl={number:"number",bigint:"bigint",object:"date"},Ji=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=kl[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})}}),Qi=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=kl[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})}}),Sl=y("$ZodCheckMultipleOf",(e,t)=>{me.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ji(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})}}),El=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Zi[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=_l)}),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 Tl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Ar(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Pl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Ar(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rl=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ir(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Ar(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Cr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),zl=y("$ZodCheckRegex",(e,t)=>{Cr.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})}}),Il=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xl),Cr.init(e,t)}),Ol=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$l),Cr.init(e,t)}),Al=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=ft(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Nl=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${ft(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Cl=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${ft(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Dl=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Wn=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 Ml={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=Ml;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=Pt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new ot;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Pt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Pt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new ot;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Nr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Hn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Jn=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)=>{Cr.init(e,t),Jn.init(e,t)}),Wl=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=rl),Q.init(e,t)}),Gl=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=Hi(n))}else t.pattern??(t.pattern=Hi());Q.init(e,t)}),Jl=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nl),Q.init(e,t)}),Ql=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:ll.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})}}}),Yl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ol()),Q.init(e,t)}),Xl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=el),Q.init(e,t)}),ed=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Gu),Q.init(e,t)}),td=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ju),Q.init(e,t)}),rd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qu),Q.init(e,t)}),nd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yu),Q.init(e,t)}),od=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xu),Q.init(e,t)}),id=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gl(t)),Q.init(e,t)}),sd=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pl),Q.init(e,t)}),ad=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hl(t)),Q.init(e,t)}),cd=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=tl),Q.init(e,t)}),ud=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=il),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ld=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sl),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})}}}),dd=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=al),Q.init(e,t)}),fd=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cl),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 pd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var md=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=>{pd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function F_(e){if(!Wi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return pd(r)}var hd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Wi),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{F_(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=dl),Q.init(e,t)});function V_(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=>{V_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Xi=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??wl,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}}),_d=y("$ZodNumber",(e,t)=>{El.init(e,t),Xi.init(e,t)}),wd=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=bl,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 bd=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=vl,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 vd=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),xd=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 ql(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}var $d=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=>ql(l,r,s))):ql(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Gn(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}function Ll(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Qe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var kd=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=Bi(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 Wn(["shape","payload","ctx"]),p=r.value,m=v=>{let x=Tt(v);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let v of p.keys)h[v]=`key_${_++}`;f.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let x=h[v];f.write(`const ${x} = ${m(v)};`);let P=Tt(v);f.write(`
12
+ `))}};var Ml={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=Ml;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=Pt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new ot;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Pt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Pt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new ot;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Nr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Hn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Jn=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)=>{Cr.init(e,t),Jn.init(e,t)}),Wl=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=rl),Q.init(e,t)}),Gl=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=Hi(n))}else t.pattern??(t.pattern=Hi());Q.init(e,t)}),Jl=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nl),Q.init(e,t)}),Ql=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:ll.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})}}}),Yl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ol()),Q.init(e,t)}),Xl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=el),Q.init(e,t)}),ed=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Gu),Q.init(e,t)}),td=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ju),Q.init(e,t)}),rd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qu),Q.init(e,t)}),nd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yu),Q.init(e,t)}),od=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xu),Q.init(e,t)}),id=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gl(t)),Q.init(e,t)}),sd=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pl),Q.init(e,t)}),ad=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hl(t)),Q.init(e,t)}),cd=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=tl),Q.init(e,t)}),ud=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=il),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ld=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sl),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})}}}),dd=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=al),Q.init(e,t)}),fd=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cl),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 pd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var md=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=>{pd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function K_(e){if(!Wi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return pd(r)}var hd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Wi),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{K_(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=dl),Q.init(e,t)});function H_(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=>{H_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Xi=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??wl,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}}),_d=y("$ZodNumber",(e,t)=>{El.init(e,t),Xi.init(e,t)}),wd=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=bl,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 bd=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=vl,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 vd=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),xd=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 ql(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}var $d=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=>ql(l,r,s))):ql(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Gn(e,t,r){e.issues.length&&t.issues.push(...Qe(r,e.issues)),t.value[r]=e.value}function Ll(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Qe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var kd=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=Bi(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 Wn(["shape","payload","ctx"]),p=r.value,m=v=>{let x=Tt(v);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let v of p.keys)h[v]=`key_${_++}`;f.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let x=h[v];f.write(`const ${x} = ${m(v)};`);let P=Tt(v);f.write(`
13
13
  if (${x}.issues.length) {
14
14
  if (input[${P}] === undefined) {
15
15
  if (${P} in input) {
@@ -32,31 +32,31 @@ var __=Object.create;var Ii=Object.defineProperty;var w_=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 ? [${Tt(v)}, ...iss.path] : [${Tt(v)}]
35
- })));`),f.write(`newResult[${Tt(v)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(v,x)=>w(d,v,x)},o,i=Wt,s=!Zn.jitless,c=s&&qi.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 P of u.keys){let I=x[P],we=I._zod.run({value:p[P],issues:[]},f),Ie=I._zod.optin==="optional"&&I._zod.optout==="optional";we instanceof Promise?m.push(we.then(Ht=>Ie?Ll(Ht,d,P,p):Gn(Ht,d,P))):Ie?Ll(we,d,P,p):Gn(we,d,P)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,v=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(v==="never"){h.push(x);continue}let P=w.run({value:p[x],issues:[]},f);P instanceof Promise?m.push(P.then(I=>Gn(I,d,x))):Gn(P,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 Bl(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=>Le(i,n,Oe())))}),t}var es=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=>Or(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=>Bl(s,r,e,n)):Bl(i,r,e,n)}}),Sd=y("$ZodDiscriminatedUnion",(e,t)=>{es.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(!Wt(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)}}),Ed=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])=>Zl(r,c,l)):Zl(r,i,s)}});function Yi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Gt(e)&&Gt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=Yi(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=Yi(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 Zl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Pt(e))return e;let n=Yi(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 Td=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Gt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Qe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Qe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Le(l,n,Oe())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Qe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Qe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Pd=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=Ci(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Li.has(typeof n)).map(n=>typeof n=="string"?ft(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),Rd=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"?ft(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var zd=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 ot;return r.value=o,r}}),Id=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(`^(${Or(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)}),Od=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(`^(${Or(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)}),Ad=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=>Ul(i,t)):Ul(o,t)}});function Ul(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Nd=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))}),Cd=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=>Fl(i,e)):Fl(o,e)}});function Fl(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 Dd=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=>Le(s,n,Oe()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Le(i,n,Oe()))},input:r.value}),r.issues=[]),r)}});var jd=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=>Vl(i,t,n)):Vl(o,t,n)}});function Vl(e,t,r){return Pt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Md=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(Kl):Kl(o)}});function Kl(e){return e.value=Object.freeze(e.value),e}var qd=y("$ZodCustom",(e,t)=>{me.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=>Hl(i,r,n,e));Hl(o,r,n,e)}});function Hl(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(Ui(o))}}var K_=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},H_=()=>{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 ${K_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Vn(n.values[0])}`:`Invalid option: expected one of ${Un(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":""}: ${Un(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 Ld(){return{localeError:H_()}}var RI=Symbol("ZodOutput"),zI=Symbol("ZodInput"),ts=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 W_(){return new ts}var Dr=W_();function Bd(e,t){return new e({type:"string",...R(t)})}function Zd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function rs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Ud(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function Fd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Kd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function Hd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Wd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Gd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function Jd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Qd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Yd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function Xd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function ef(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function tf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function rf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function nf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function of(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function sf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function af(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function cf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function uf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function lf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function df(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function ff(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function pf(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function mf(e,t){return new e({type:"number",checks:[],...R(t)})}function hf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function gf(e,t){return new e({type:"boolean",...R(t)})}function yf(e,t){return new e({type:"null",...R(t)})}function _f(e){return new e({type:"unknown"})}function wf(e,t){return new e({type:"never",...R(t)})}function Qn(e,t){return new Ji({check:"less_than",...R(t),value:e,inclusive:!1})}function jr(e,t){return new Ji({check:"less_than",...R(t),value:e,inclusive:!0})}function Yn(e,t){return new Qi({check:"greater_than",...R(t),value:e,inclusive:!1})}function Mr(e,t){return new Qi({check:"greater_than",...R(t),value:e,inclusive:!0})}function Xn(e,t){return new Sl({check:"multiple_of",...R(t),value:e})}function eo(e,t){return new Tl({check:"max_length",...R(t),maximum:e})}function Jt(e,t){return new Pl({check:"min_length",...R(t),minimum:e})}function to(e,t){return new Rl({check:"length_equals",...R(t),length:e})}function ns(e,t){return new zl({check:"string_format",format:"regex",...R(t),pattern:e})}function os(e){return new Il({check:"string_format",format:"lowercase",...R(e)})}function is(e){return new Ol({check:"string_format",format:"uppercase",...R(e)})}function ss(e,t){return new Al({check:"string_format",format:"includes",...R(t),includes:e})}function as(e,t){return new Nl({check:"string_format",format:"starts_with",...R(t),prefix:e})}function cs(e,t){return new Cl({check:"string_format",format:"ends_with",...R(t),suffix:e})}function Rt(e){return new Dl({check:"overwrite",tx:e})}function us(e){return Rt(t=>t.normalize(e))}function ls(){return Rt(e=>e.trim())}function ds(){return Rt(e=>e.toLowerCase())}function fs(){return Rt(e=>e.toUpperCase())}function bf(e,t,r){return new e({type:"array",element:t,...R(r)})}function vf(e,t,r){let n=R(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function xf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...R(r)})}function Qt(e){return!!e._zod}function Be(e,t){return Qt(e)?Nr(e,t):e.safeParse(t)}function ro(e){if(!e)return;let t;if(Qt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $f(e){if(Qt(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 Lr={};Lu(Lr,{ZodISODate:()=>Sf,ZodISODateTime:()=>kf,ZodISODuration:()=>Tf,ZodISOTime:()=>Ef,date:()=>ms,datetime:()=>ps,duration:()=>gs,time:()=>hs});var kf=y("ZodISODateTime",(e,t)=>{id.init(e,t),te.init(e,t)});function ps(e){return lf(kf,e)}var Sf=y("ZodISODate",(e,t)=>{sd.init(e,t),te.init(e,t)});function ms(e){return df(Sf,e)}var Ef=y("ZodISOTime",(e,t)=>{ad.init(e,t),te.init(e,t)});function hs(e){return ff(Ef,e)}var Tf=y("ZodISODuration",(e,t)=>{cd.init(e,t),te.init(e,t)});function gs(e){return pf(Tf,e)}var Pf=(e,t)=>{Kn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Ku(e,r)},flatten:{value:r=>Vu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},lO=y("ZodError",Pf),Br=y("ZodError",Pf,{Parent:Error});var Rf=Hu(Br),zf=Wu(Br),If=Vi(Br),Of=Ki(Br);var oe=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)=>Je(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Rf(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>If(e,r,n),e.parseAsync=async(r,n)=>zf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Of(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Vw(r,n)),e.superRefine=r=>e.check(Kw(r)),e.overwrite=r=>e.check(Rt(r)),e.optional=()=>ne(e),e.nullable=()=>Cf(e),e.nullish=()=>ne(Cf(e)),e.nonoptional=r=>Mw(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>oo(e,r),e.transform=r=>_s(e,Bf(r)),e.default=r=>Cw(e,r),e.prefault=r=>jw(e,r),e.catch=r=>Lw(e,r),e.pipe=r=>_s(e,r),e.readonly=()=>Uw(e),e.describe=r=>{let n=e.clone();return Dr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Dr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Dr.get(e);let n=e.clone();return Dr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Df=y("_ZodString",(e,t)=>{Jn.init(e,t),oe.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(ns(...n)),e.includes=(...n)=>e.check(ss(...n)),e.startsWith=(...n)=>e.check(as(...n)),e.endsWith=(...n)=>e.check(cs(...n)),e.min=(...n)=>e.check(Jt(...n)),e.max=(...n)=>e.check(eo(...n)),e.length=(...n)=>e.check(to(...n)),e.nonempty=(...n)=>e.check(Jt(1,...n)),e.lowercase=n=>e.check(os(n)),e.uppercase=n=>e.check(is(n)),e.trim=()=>e.check(ls()),e.normalize=(...n)=>e.check(us(...n)),e.toLowerCase=()=>e.check(ds()),e.toUpperCase=()=>e.check(fs())}),nw=y("ZodString",(e,t)=>{Jn.init(e,t),Df.init(e,t),e.email=r=>e.check(Zd(ow,r)),e.url=r=>e.check(Hd(iw,r)),e.jwt=r=>e.check(uf(bw,r)),e.emoji=r=>e.check(Wd(sw,r)),e.guid=r=>e.check(rs(Af,r)),e.uuid=r=>e.check(Ud(no,r)),e.uuidv4=r=>e.check(Fd(no,r)),e.uuidv6=r=>e.check(Vd(no,r)),e.uuidv7=r=>e.check(Kd(no,r)),e.nanoid=r=>e.check(Gd(aw,r)),e.guid=r=>e.check(rs(Af,r)),e.cuid=r=>e.check(Jd(cw,r)),e.cuid2=r=>e.check(Qd(uw,r)),e.ulid=r=>e.check(Yd(lw,r)),e.base64=r=>e.check(sf(yw,r)),e.base64url=r=>e.check(af(_w,r)),e.xid=r=>e.check(Xd(dw,r)),e.ksuid=r=>e.check(ef(fw,r)),e.ipv4=r=>e.check(tf(pw,r)),e.ipv6=r=>e.check(rf(mw,r)),e.cidrv4=r=>e.check(nf(hw,r)),e.cidrv6=r=>e.check(of(gw,r)),e.e164=r=>e.check(cf(ww,r)),e.datetime=r=>e.check(ps(r)),e.date=r=>e.check(ms(r)),e.time=r=>e.check(hs(r)),e.duration=r=>e.check(gs(r))});function g(e){return Bd(nw,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),Df.init(e,t)}),ow=y("ZodEmail",(e,t)=>{Jl.init(e,t),te.init(e,t)});var Af=y("ZodGUID",(e,t)=>{Wl.init(e,t),te.init(e,t)});var no=y("ZodUUID",(e,t)=>{Gl.init(e,t),te.init(e,t)});var iw=y("ZodURL",(e,t)=>{Ql.init(e,t),te.init(e,t)});var sw=y("ZodEmoji",(e,t)=>{Yl.init(e,t),te.init(e,t)});var aw=y("ZodNanoID",(e,t)=>{Xl.init(e,t),te.init(e,t)});var cw=y("ZodCUID",(e,t)=>{ed.init(e,t),te.init(e,t)});var uw=y("ZodCUID2",(e,t)=>{td.init(e,t),te.init(e,t)});var lw=y("ZodULID",(e,t)=>{rd.init(e,t),te.init(e,t)});var dw=y("ZodXID",(e,t)=>{nd.init(e,t),te.init(e,t)});var fw=y("ZodKSUID",(e,t)=>{od.init(e,t),te.init(e,t)});var pw=y("ZodIPv4",(e,t)=>{ud.init(e,t),te.init(e,t)});var mw=y("ZodIPv6",(e,t)=>{ld.init(e,t),te.init(e,t)});var hw=y("ZodCIDRv4",(e,t)=>{dd.init(e,t),te.init(e,t)});var gw=y("ZodCIDRv6",(e,t)=>{fd.init(e,t),te.init(e,t)});var yw=y("ZodBase64",(e,t)=>{md.init(e,t),te.init(e,t)});var _w=y("ZodBase64URL",(e,t)=>{hd.init(e,t),te.init(e,t)});var ww=y("ZodE164",(e,t)=>{gd.init(e,t),te.init(e,t)});var bw=y("ZodJWT",(e,t)=>{yd.init(e,t),te.init(e,t)});var jf=y("ZodNumber",(e,t)=>{Xi.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(Yn(n,o)),e.gte=(n,o)=>e.check(Mr(n,o)),e.min=(n,o)=>e.check(Mr(n,o)),e.lt=(n,o)=>e.check(Qn(n,o)),e.lte=(n,o)=>e.check(jr(n,o)),e.max=(n,o)=>e.check(jr(n,o)),e.int=n=>e.check(Nf(n)),e.safe=n=>e.check(Nf(n)),e.positive=n=>e.check(Yn(0,n)),e.nonnegative=n=>e.check(Mr(0,n)),e.negative=n=>e.check(Qn(0,n)),e.nonpositive=n=>e.check(jr(0,n)),e.multipleOf=(n,o)=>e.check(Xn(n,o)),e.step=(n,o)=>e.check(Xn(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 mf(jf,e)}var vw=y("ZodNumberFormat",(e,t)=>{_d.init(e,t),jf.init(e,t)});function Nf(e){return hf(vw,e)}var xw=y("ZodBoolean",(e,t)=>{wd.init(e,t),oe.init(e,t)});function ce(e){return gf(xw,e)}var $w=y("ZodNull",(e,t)=>{bd.init(e,t),oe.init(e,t)});function Mf(e){return yf($w,e)}var kw=y("ZodUnknown",(e,t)=>{vd.init(e,t),oe.init(e,t)});function re(){return _f(kw)}var Sw=y("ZodNever",(e,t)=>{xd.init(e,t),oe.init(e,t)});function Ew(e){return wf(Sw,e)}var Tw=y("ZodArray",(e,t)=>{$d.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Jt(r,n)),e.nonempty=r=>e.check(Jt(1,r)),e.max=(r,n)=>e.check(eo(r,n)),e.length=(r,n)=>e.check(to(r,n)),e.unwrap=()=>e.element});function q(e,t){return bf(Tw,e,t)}var qf=y("ZodObject",(e,t)=>{kd.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ke(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ew()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(Zf,e,r[0]),e.required=(...r)=>F.required(Uf,e,r[0])});function $(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new qf(r)}function be(e,t){return new qf({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var Lf=y("ZodUnion",(e,t)=>{es.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new Lf({type:"union",options:e,...F.normalizeParams(t)})}var Pw=y("ZodDiscriminatedUnion",(e,t)=>{Lf.init(e,t),Sd.init(e,t)});function ws(e,t,r){return new Pw({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var Rw=y("ZodIntersection",(e,t)=>{Ed.init(e,t),oe.init(e,t)});function oo(e,t){return new Rw({type:"intersection",left:e,right:t})}var zw=y("ZodRecord",(e,t)=>{Td.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new zw({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var ys=y("ZodEnum",(e,t)=>{Pd.init(e,t),oe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ys({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ys({...t,checks:[],...F.normalizeParams(o),entries:i})}});function ke(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ys({type:"enum",entries:r,...F.normalizeParams(t)})}var Iw=y("ZodLiteral",(e,t)=>{Rd.init(e,t),oe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function k(e,t){return new Iw({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var Ow=y("ZodTransform",(e,t)=>{zd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Bf(e){return new Ow({type:"transform",transform:e})}var Zf=y("ZodOptional",(e,t)=>{Id.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new Zf({type:"optional",innerType:e})}var Aw=y("ZodNullable",(e,t)=>{Od.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Cf(e){return new Aw({type:"nullable",innerType:e})}var Nw=y("ZodDefault",(e,t)=>{Ad.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Cw(e,t){return new Nw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Dw=y("ZodPrefault",(e,t)=>{Nd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jw(e,t){return new Dw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Uf=y("ZodNonOptional",(e,t)=>{Cd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Mw(e,t){return new Uf({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var qw=y("ZodCatch",(e,t)=>{Dd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Lw(e,t){return new qw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Bw=y("ZodPipe",(e,t)=>{jd.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function _s(e,t){return new Bw({type:"pipe",in:e,out:t})}var Zw=y("ZodReadonly",(e,t)=>{Md.init(e,t),oe.init(e,t)});function Uw(e){return new Zw({type:"readonly",innerType:e})}var Ff=y("ZodCustom",(e,t)=>{qd.init(e,t),oe.init(e,t)});function Fw(e){let t=new me({check:"custom"});return t._zod.check=e,t}function Vf(e,t){return vf(Ff,e??(()=>!0),t)}function Vw(e,t={}){return xf(Ff,e,t)}function Kw(e){let t=Fw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(F.issue(o))}},e(r.value,r)));return t}function bs(e,t){return _s(Bf(e),t)}Oe(Ld());var xs="2025-11-25";var Kf=[xs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],pt="io.modelcontextprotocol/related-task",so="2.0",ae=Vf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Hf=Y([g(),V().int()]),Wf=g(),nA=be({ttl:V().optional(),pollInterval:V().optional()}),Hw=$({ttl:V().optional()}),Ww=$({taskId:g()}),$s=be({progressToken:Hf.optional(),[pt]:Ww.optional()}),ze=$({_meta:$s.optional()}),Zr=ze.extend({task:Hw.optional()}),Gf=e=>Zr.safeParse(e).success,ue=$({method:g(),params:ze.loose().optional()}),Ae=$({_meta:$s.optional()}),Ne=$({method:g(),params:Ae.loose().optional()}),le=be({_meta:$s.optional()}),ao=Y([g(),V().int()]),Jf=$({jsonrpc:k(so),id:ao,...ue.shape}).strict(),ks=e=>Jf.safeParse(e).success,Qf=$({jsonrpc:k(so),...Ne.shape}).strict(),Yf=e=>Qf.safeParse(e).success,Ss=$({jsonrpc:k(so),id:ao,result:le}).strict(),Ur=e=>Ss.safeParse(e).success;var O;(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"})(O||(O={}));var Es=$({jsonrpc:k(so),id:ao.optional(),error:$({code:V().int(),message:g(),data:re().optional()})}).strict();var Xf=e=>Es.safeParse(e).success;var ep=Y([Jf,Qf,Ss,Es]),oA=Y([Ss,Es]),zt=le.strict(),Gw=Ae.extend({requestId:ao.optional(),reason:g().optional()}),co=Ne.extend({method:k("notifications/cancelled"),params:Gw}),Jw=$({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:ke(["light","dark"]).optional()}),Fr=$({icons:q(Jw).optional()}),Yt=$({name:g(),title:g().optional()}),tp=Yt.extend({...Yt.shape,...Fr.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Qw=oo($({applyDefaults:ce().optional()}),J(g(),re())),Yw=bs(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,oo($({form:Qw.optional(),url:ae.optional()}),J(g(),re()).optional())),Xw=be({list:ae.optional(),cancel:ae.optional(),requests:be({sampling:be({createMessage:ae.optional()}).optional(),elicitation:be({create:ae.optional()}).optional()}).optional()}),eb=be({list:ae.optional(),cancel:ae.optional(),requests:be({tools:be({call:ae.optional()}).optional()}).optional()}),tb=$({experimental:J(g(),ae).optional(),sampling:$({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:Yw.optional(),roots:$({listChanged:ce().optional()}).optional(),tasks:Xw.optional(),extensions:J(g(),ae).optional()}),rb=ze.extend({protocolVersion:g(),capabilities:tb,clientInfo:tp}),nb=ue.extend({method:k("initialize"),params:rb});var ob=$({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:$({listChanged:ce().optional()}).optional(),resources:$({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:$({listChanged:ce().optional()}).optional(),tasks:eb.optional(),extensions:J(g(),ae).optional()}),Ts=le.extend({protocolVersion:g(),capabilities:ob,serverInfo:tp,instructions:g().optional()}),ib=Ne.extend({method:k("notifications/initialized"),params:Ae.optional()});var uo=ue.extend({method:k("ping"),params:ze.optional()}),sb=$({progress:V(),total:ne(V()),message:ne(g())}),ab=$({...Ae.shape,...sb.shape,progressToken:Hf}),lo=Ne.extend({method:k("notifications/progress"),params:ab}),cb=ze.extend({cursor:Wf.optional()}),Vr=ue.extend({params:cb.optional()}),Kr=le.extend({nextCursor:Wf.optional()}),ub=ke(["working","input_required","completed","failed","cancelled"]),Hr=$({taskId:g(),status:ub,ttl:Y([V(),Mf()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(V()),statusMessage:ne(g())}),It=le.extend({task:Hr}),lb=Ae.merge(Hr),Wr=Ne.extend({method:k("notifications/tasks/status"),params:lb}),fo=ue.extend({method:k("tasks/get"),params:ze.extend({taskId:g()})}),po=le.merge(Hr),mo=ue.extend({method:k("tasks/result"),params:ze.extend({taskId:g()})}),iA=le.loose(),ho=Vr.extend({method:k("tasks/list")}),go=Kr.extend({tasks:q(Hr)}),yo=ue.extend({method:k("tasks/cancel"),params:ze.extend({taskId:g()})}),rp=le.merge(Hr),np=$({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),op=np.extend({text:g()}),Ps=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ip=np.extend({blob:Ps}),Gr=ke(["user","assistant"]),Xt=$({audience:q(Gr).optional(),priority:V().min(0).max(1).optional(),lastModified:Lr.datetime({offset:!0}).optional()}),sp=$({...Yt.shape,...Fr.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(V()),annotations:Xt.optional(),_meta:ne(be({}))}),db=$({...Yt.shape,...Fr.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:Xt.optional(),_meta:ne(be({}))}),fb=Vr.extend({method:k("resources/list")}),Rs=Kr.extend({resources:q(sp)}),pb=Vr.extend({method:k("resources/templates/list")}),zs=Kr.extend({resourceTemplates:q(db)}),Is=ze.extend({uri:g()}),mb=Is,hb=ue.extend({method:k("resources/read"),params:mb}),Os=le.extend({contents:q(Y([op,ip]))}),As=Ne.extend({method:k("notifications/resources/list_changed"),params:Ae.optional()}),gb=Is,yb=ue.extend({method:k("resources/subscribe"),params:gb}),_b=Is,wb=ue.extend({method:k("resources/unsubscribe"),params:_b}),bb=Ae.extend({uri:g()}),vb=Ne.extend({method:k("notifications/resources/updated"),params:bb}),xb=$({name:g(),description:ne(g()),required:ne(ce())}),$b=$({...Yt.shape,...Fr.shape,description:ne(g()),arguments:ne(q(xb)),_meta:ne(be({}))}),kb=Vr.extend({method:k("prompts/list")}),Ns=Kr.extend({prompts:q($b)}),Sb=ze.extend({name:g(),arguments:J(g(),g()).optional()}),Eb=ue.extend({method:k("prompts/get"),params:Sb}),Cs=$({type:k("text"),text:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Ds=$({type:k("image"),data:Ps,mimeType:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),js=$({type:k("audio"),data:Ps,mimeType:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Tb=$({type:k("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),Pb=$({type:k("resource"),resource:Y([op,ip]),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Rb=sp.extend({type:k("resource_link")}),Ms=Y([Cs,Ds,js,Rb,Pb]),zb=$({role:Gr,content:Ms}),qs=le.extend({description:g().optional(),messages:q(zb)}),Ls=Ne.extend({method:k("notifications/prompts/list_changed"),params:Ae.optional()}),Ib=$({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),Ob=$({taskSupport:ke(["required","optional","forbidden"]).optional()}),ap=$({...Yt.shape,...Fr.shape,description:g().optional(),inputSchema:$({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:$({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:Ib.optional(),execution:Ob.optional(),_meta:J(g(),re()).optional()}),Ab=Vr.extend({method:k("tools/list")}),Bs=Kr.extend({tools:q(ap)}),mt=le.extend({content:q(Ms).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),sA=mt.or(le.extend({toolResult:re()})),Nb=Zr.extend({name:g(),arguments:J(g(),re()).optional()}),Cb=ue.extend({method:k("tools/call"),params:Nb}),Zs=Ne.extend({method:k("notifications/tools/list_changed"),params:Ae.optional()}),cp=$({autoRefresh:ce().default(!0),debounceMs:V().int().nonnegative().default(300)}),up=ke(["debug","info","notice","warning","error","critical","alert","emergency"]),Db=ze.extend({level:up}),jb=ue.extend({method:k("logging/setLevel"),params:Db}),Mb=Ae.extend({level:up,logger:g().optional(),data:re()}),qb=Ne.extend({method:k("notifications/message"),params:Mb}),Lb=$({name:g().optional()}),Bb=$({hints:q(Lb).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),Zb=$({mode:ke(["auto","required","none"]).optional()}),Ub=$({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Ms).default([]),structuredContent:$({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),Fb=ws("type",[Cs,Ds,js]),io=ws("type",[Cs,Ds,js,Tb,Ub]),Vb=$({role:Gr,content:Y([io,q(io)]),_meta:J(g(),re()).optional()}),Kb=Zr.extend({messages:q(Vb),modelPreferences:Bb.optional(),systemPrompt:g().optional(),includeContext:ke(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(ap).optional(),toolChoice:Zb.optional()}),Us=ue.extend({method:k("sampling/createMessage"),params:Kb}),Fs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens"]).or(g())),role:Gr,content:Fb}),Vs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Gr,content:Y([io,q(io)])}),Hb=$({type:k("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),Wb=$({type:k("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:ke(["email","uri","date","date-time"]).optional(),default:g().optional()}),Gb=$({type:ke(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),Jb=$({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),Qb=$({type:k("string"),title:g().optional(),description:g().optional(),oneOf:q($({const:g(),title:g()})),default:g().optional()}),Yb=$({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),Xb=Y([Jb,Qb]),ev=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:k("string"),enum:q(g())}),default:q(g()).optional()}),tv=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:q($({const:g(),title:g()}))}),default:q(g()).optional()}),rv=Y([ev,tv]),nv=Y([Yb,Xb,rv]),ov=Y([nv,Hb,Wb,Gb]),iv=Zr.extend({mode:k("form").optional(),message:g(),requestedSchema:$({type:k("object"),properties:J(g(),ov),required:q(g()).optional()})}),sv=Zr.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),av=Y([iv,sv]),Ks=ue.extend({method:k("elicitation/create"),params:av}),cv=Ae.extend({elicitationId:g()}),uv=Ne.extend({method:k("notifications/elicitation/complete"),params:cv}),Hs=le.extend({action:ke(["accept","decline","cancel"]),content:bs(e=>e===null?void 0:e,J(g(),Y([g(),V(),ce(),q(g())])).optional())}),lv=$({type:k("ref/resource"),uri:g()});var dv=$({type:k("ref/prompt"),name:g()}),fv=ze.extend({ref:Y([dv,lv]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),pv=ue.extend({method:k("completion/complete"),params:fv});var Ws=le.extend({completion:be({values:q(g()).max(100),total:ne(V().int()),hasMore:ne(ce())})}),mv=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),hv=ue.extend({method:k("roots/list"),params:ze.optional()}),gv=le.extend({roots:q(mv)}),yv=Ne.extend({method:k("notifications/roots/list_changed"),params:Ae.optional()}),aA=Y([uo,nb,pv,jb,Eb,kb,fb,pb,hb,yb,wb,Cb,Ab,fo,mo,ho,yo]),cA=Y([co,lo,ib,yv,Wr]),uA=Y([zt,Fs,Vs,Hs,gv,po,go,It]),lA=Y([uo,Us,Ks,hv,fo,mo,ho,yo]),dA=Y([co,lo,qb,vb,As,Zs,Ls,Wr,uv]),fA=Y([zt,Ts,Ws,qs,Ns,Rs,zs,Os,mt,Bs,po,go,It]),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===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new vs(o.elicitations,r)}return new e(t,r,n)}},vs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function ht(e){return e==="completed"||e==="failed"||e==="cancelled"}var _v=Symbol("Let zodToJsonSchema decide on which parser to use");var VA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Gs(e){let r=ro(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$f(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Js(e,t){let r=Be(e,t);if(!r.success)throw r.error;return r.data}var kv=6e4,_o=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(co,r=>{this._oncancel(r)}),this.setNotificationHandler(lo,r=>{this._onprogress(r)}),this.setRequestHandler(uo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(fo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(O.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(mo,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(O.InvalidParams,`Task not found: ${i}`);if(!ht(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ht(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[pt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(ho,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(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(yo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(ht(o.status))throw new T(O.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(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(O.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(O.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),Ur(i)||Xf(i)?this._onresponse(i):ks(i)?this._onrequest(i,s):Yf(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(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[pt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:O.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=Gf(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(O.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:O.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),Ur(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(Ur(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),Ur(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(O.InternalError,String(s))}}return}let i;try{let s=await this.request(t,It,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ht(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(O.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(O.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(O.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=v=>{u(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[pt]:c}});let m=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let x=v instanceof T?v:new T(O.RequestTimeout,String(v));u(x)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let x=Be(r,v.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??kv,_=()=>m(T.fromError(O.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let v=x=>{let P=this._responseHandlers.get(f);P?P(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),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(v=>{this._cleanupTimeout(f),u(v)})})}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},go,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},rp,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[pt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[pt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Gs(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Js(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=Gs(t);this._notificationHandlers.set(n,o=>{let i=Js(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"&&ks(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(O.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(O.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(O.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(O.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=Wr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ht(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new T(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ht(a.status))throw new T(O.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=Wr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ht(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function lp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dp(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];lp(s)&&lp(i)?r[o]={...s,...i}:r[o]=i}return r}var rg=Oi(Dc(),1),ng=Oi(tg(),1);function TE(){let e=new rg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ng.default)(e),e}var Xo=class{constructor(t){this._ajv=t??TE()}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 ei=class{constructor(t){this._client=t}async*callToolStream(t,r=mt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new T(O.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(O.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(O.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 og(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ig(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function ti(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&&ti(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&ti(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&ti(r,t)}}function PE(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 ri=class extends _o{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 Xo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Zs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ls,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",As,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ei(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=dp(this._capabilities,t)}setRequestHandler(t,r){let o=ro(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Qt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Be(Ks,c);if(!u.success){let v=u.error instanceof Error?u.error.message:String(u.error);throw new T(O.InvalidParams,`Invalid elicitation request: ${v}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=PE(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(O.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(O.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let v=Be(It,m);if(!v.success){let x=v.error instanceof Error?v.error.message:String(v.error);throw new T(O.InvalidParams,`Invalid task creation result: ${x}`)}return v.data}let h=Be(Hs,m);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new T(O.InvalidParams,`Invalid elicitation result: ${v}`)}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{ti(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Be(Us,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(O.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Be(It,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(O.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?Vs:Fs,h=Be(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(O.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:xs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ts,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Kf.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){og(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&ig(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},zt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Ws,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},zt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},qs,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Ns,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Rs,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},zs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Os,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},zt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},zt,r)}async callTool(t,r=mt,n){if(this.isToolTaskRequired(t.name))throw new T(O.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(O.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(O.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(O.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},Bs,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=cp.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 Gg=Oi(Hg(),1);import Xc from"node:process";import{PassThrough as rT}from"node:stream";var oi=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),tT(r)}clear(){this._buffer=void 0}};function tT(e){return ep.parse(JSON.parse(e))}function Wg(e){return JSON.stringify(e)+`
37
- `}var nT=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function oT(){let e={};for(let t of nT){let r=Xc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var ii=class{constructor(t){this._readBuffer=new oi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new rT)}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,Gg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...oT(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.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=Wg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var iT=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Ut=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new ii({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??sT(),stderr:t.stderr??"pipe"}),n=new ri({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:cT(r).map(uT),nextCursor:Jg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!si(n,["error"])&&fT(n,["ok","success"],!0),target:t,messageId:He(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:lT(r).map(dT).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=iT.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:aT(r)},mt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
- `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function sT(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function aT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function cT(e){if(Array.isArray(e))return e;if(!br(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&br(r)?[r]:[]}function uT(e){return br(e)?{id:He(e,["id","message_id","messageId"]),cursor:Jg(e,["cursor"]),type:He(e,["type","event_type","eventType"]),platform:He(e,["platform"]),target:He(e,["target"]),sessionKey:He(e,["session_key","sessionKey"]),timestamp:He(e,["timestamp","created_at","createdAt"]),message:He(e,["message","text","content"]),raw:e}:{raw:e}}function lT(e){if(Array.isArray(e))return e;if(!br(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function dT(e){if(!br(e))return null;let t=He(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:He(e,["platform"]),name:He(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function He(e,t){let r=si(e,t);return typeof r=="string"?r:void 0}function fT(e,t,r){let n=si(e,t);return typeof n=="boolean"?n:r}function Jg(e,t){let r=si(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function si(e,t){if(br(e))for(let r of t){let n=e[r];if(n!=null)return n}}function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as Sz,writeFile as Ez}from"node:fs/promises";import{join as n_}from"node:path";import{basename as r_}from"node:path";import{createHash as NT,randomUUID as pu}from"node:crypto";import{spawn as CT}from"node:child_process";import{constants as lu}from"node:fs";import{readFileSync as DT}from"node:fs";import{mkdir as ly,open as jT,readFile as MT,rename as MM,rm as In,stat as qM,writeFile as LM}from"node:fs/promises";import{tmpdir as qT}from"node:os";import{dirname as xr,join as qe,resolve as fi}from"node:path";import{fileURLToPath as LT}from"node:url";var ai=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 ai(e,t)}var ci=",";function eu(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 nt(e){return E(e,"invalid quoted string")}function kt(e,t){if(e==="")return"";if(e.startsWith('"'))return Qg(e,t);if(e.includes('"'))throw nt(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:pT(e)?Number(e):e}function Ft(e,t){let r=e.trim();if(r.startsWith('"'))return[Qg(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function Qg(e,t){if(e[0]!=='"')throw nt(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw nt(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw nt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw nt(t);r+=String.fromCharCode(a),n+=4;break}default:throw nt(t)}continue}if(o<" "&&o!==" ")throw nt(t);r+=o}throw nt(t)}function Tn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw nt(r);return n.push(e.slice(o).trim()),n}function Re(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw nt(r);return-1}function pT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Pn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Xg=2;function yT(e={}){return{indent:Math.max(1,e.indent??Xg),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function _T(e,t){let r=[],n=!1;return eu(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 zn(e,t){let r=yT(t),n=_T(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=au(o.content,Re(o.content,":",o.number))}catch(u){if(r.strict)throw ou(u,o.number);l=void 0}if(l!==void 0)return vT(l,n,r)}if(i&&Re(o.content,":",o.number)===-1)return kt(o.content.trim(),o.number);let s={index:0},a=iu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function iu(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}=wT(e,t,r,n);ty(o,s,a,c,n,i.number)}return o}function wT(e,t,r,n){let o=e[t.index],i=o.content,s=Re(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=Re(a,"[",o.number),u=Re(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=ST(a)}catch(_){if(n.strict)throw ou(_,o.number);t.index+=1;let w=tu(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=bT(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=au(a,s)}catch(_){if(n.strict)throw ou(_,o.number);t.index+=1;let w=tu(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=su(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Ft(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=tu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function tu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return kt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?iu(e,t,r+1,i):{}}function bT(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=Re(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Ft(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Tn(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)=>{Rn(d,f,kt(u[p],s.number),o,s.number)}),ty(i,c,l,d,o,s.number),r.index+=1}return i}function vT(e,t,r){let n=t[0],o=Re(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=su(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 su(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 xT(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Tn(a,e.delimiter,s).map(l=>kt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return $T(e,r,n,o+1,i)}function xT(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw ru(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(!Yg(c.content,e.delimiter,c.number))break;let l=Tn(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)=>{Rn(u,d,kt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw ru(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Yg(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function Yg(e,t,r){let n=Re(e,":",r);if(n===-1)return!0;let o=Re(e,t,r);return o===-1?!1:o<n}function $T(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 ru(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(kT(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 kT(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=Re(i,":",o.number),a;try{a=au(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return su(a,c,e,t,r,n)}}if(Re(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return iu(s,{index:0},r+1,n)}return t.index+=1,kt(i,o.number)}function ru(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function au(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=Re(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Ft(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=ey(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 ST(e){let t=Re(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Ft(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=ey(e.slice(t+1,-1),ci)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:ci,fields:o}}function ey(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]=Ft(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(ET(r[a],r[c])||nu(r[a],r[c])||nu(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 ET(e,t){return e.length===t.length&&nu(e,t)}function nu(e,t){return t.every((r,n)=>e[n]===r)}function ou(e,t){return E(t,e.reason??String(e.message))}function ty(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(TT)){Rn(e,s,n,o,i);return}}Rn(e,[t],n,o,i)}function Rn(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");Pn(e,i,r);return}if(s&&!PT(e[i])){if(n.strict)throw E(o,"path expansion conflict");Pn(e,i,{})}else s||Pn(e,i,{});Rn(e[i],t.slice(1),r,n,o)}function TT(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function PT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Yj=new TextEncoder,Xj=new TextDecoder;import{isAbsolute as PM,join as vr,resolve as RM}from"node:path";var zT=".red";function IT(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function ry(e){return vr(IT(e),zT)}function ny(e){return vr(ry(e),"state")}function OT(e){return vr(ry(e),"tmp")}function oy(e){return vr(ny(e),"rsp")}function cu(e){return vr(ny(e),"red-skills.rdb")}function uu(e){return vr(OT(e),"red-skills.rdb")}function iy(e,t){let r=cu(e);if(t(r))return r;let n=uu(e);return t(n)?n:r}import{createConnection as AT}from"node:net";async function li(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=AT(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
35
+ })));`),f.write(`newResult[${Tt(v)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(v,x)=>w(d,v,x)},o,i=Wt,s=!Zn.jitless,c=s&&qi.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 P of u.keys){let I=x[P],we=I._zod.run({value:p[P],issues:[]},f),Ie=I._zod.optin==="optional"&&I._zod.optout==="optional";we instanceof Promise?m.push(we.then(Ht=>Ie?Ll(Ht,d,P,p):Gn(Ht,d,P))):Ie?Ll(we,d,P,p):Gn(we,d,P)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,v=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(v==="never"){h.push(x);continue}let P=w.run({value:p[x],issues:[]},f);P instanceof Promise?m.push(P.then(I=>Gn(I,d,x))):Gn(P,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 Bl(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=>Le(i,n,Oe())))}),t}var es=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=>Or(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=>Bl(s,r,e,n)):Bl(i,r,e,n)}}),Sd=y("$ZodDiscriminatedUnion",(e,t)=>{es.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(!Wt(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)}}),Ed=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])=>Zl(r,c,l)):Zl(r,i,s)}});function Yi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Gt(e)&&Gt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=Yi(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=Yi(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 Zl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Pt(e))return e;let n=Yi(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 Td=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Gt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Qe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Qe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Le(l,n,Oe())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Qe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Qe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Pd=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=Ci(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Li.has(typeof n)).map(n=>typeof n=="string"?ft(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),Rd=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"?ft(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var zd=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 ot;return r.value=o,r}}),Id=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(`^(${Or(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)}),Od=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(`^(${Or(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)}),Ad=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=>Ul(i,t)):Ul(o,t)}});function Ul(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Nd=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))}),Cd=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=>Fl(i,e)):Fl(o,e)}});function Fl(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 Dd=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=>Le(s,n,Oe()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Le(i,n,Oe()))},input:r.value}),r.issues=[]),r)}});var jd=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=>Vl(i,t,n)):Vl(o,t,n)}});function Vl(e,t,r){return Pt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Md=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(Kl):Kl(o)}});function Kl(e){return e.value=Object.freeze(e.value),e}var qd=y("$ZodCustom",(e,t)=>{me.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=>Hl(i,r,n,e));Hl(o,r,n,e)}});function Hl(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(Ui(o))}}var W_=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},G_=()=>{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 ${W_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Vn(n.values[0])}`:`Invalid option: expected one of ${Un(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":""}: ${Un(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 Ld(){return{localeError:G_()}}var AI=Symbol("ZodOutput"),NI=Symbol("ZodInput"),ts=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 J_(){return new ts}var Dr=J_();function Bd(e,t){return new e({type:"string",...R(t)})}function Zd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function rs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Ud(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function Fd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Kd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function Hd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Wd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Gd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function Jd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Qd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Yd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function Xd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function ef(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function tf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function rf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function nf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function of(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function sf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function af(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function cf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function uf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function lf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function df(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function ff(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function pf(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function mf(e,t){return new e({type:"number",checks:[],...R(t)})}function hf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function gf(e,t){return new e({type:"boolean",...R(t)})}function yf(e,t){return new e({type:"null",...R(t)})}function _f(e){return new e({type:"unknown"})}function wf(e,t){return new e({type:"never",...R(t)})}function Qn(e,t){return new Ji({check:"less_than",...R(t),value:e,inclusive:!1})}function jr(e,t){return new Ji({check:"less_than",...R(t),value:e,inclusive:!0})}function Yn(e,t){return new Qi({check:"greater_than",...R(t),value:e,inclusive:!1})}function Mr(e,t){return new Qi({check:"greater_than",...R(t),value:e,inclusive:!0})}function Xn(e,t){return new Sl({check:"multiple_of",...R(t),value:e})}function eo(e,t){return new Tl({check:"max_length",...R(t),maximum:e})}function Jt(e,t){return new Pl({check:"min_length",...R(t),minimum:e})}function to(e,t){return new Rl({check:"length_equals",...R(t),length:e})}function ns(e,t){return new zl({check:"string_format",format:"regex",...R(t),pattern:e})}function os(e){return new Il({check:"string_format",format:"lowercase",...R(e)})}function is(e){return new Ol({check:"string_format",format:"uppercase",...R(e)})}function ss(e,t){return new Al({check:"string_format",format:"includes",...R(t),includes:e})}function as(e,t){return new Nl({check:"string_format",format:"starts_with",...R(t),prefix:e})}function cs(e,t){return new Cl({check:"string_format",format:"ends_with",...R(t),suffix:e})}function Rt(e){return new Dl({check:"overwrite",tx:e})}function us(e){return Rt(t=>t.normalize(e))}function ls(){return Rt(e=>e.trim())}function ds(){return Rt(e=>e.toLowerCase())}function fs(){return Rt(e=>e.toUpperCase())}function bf(e,t,r){return new e({type:"array",element:t,...R(r)})}function vf(e,t,r){let n=R(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function xf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...R(r)})}function Qt(e){return!!e._zod}function Be(e,t){return Qt(e)?Nr(e,t):e.safeParse(t)}function ro(e){if(!e)return;let t;if(Qt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $f(e){if(Qt(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 Lr={};Lu(Lr,{ZodISODate:()=>Sf,ZodISODateTime:()=>kf,ZodISODuration:()=>Tf,ZodISOTime:()=>Ef,date:()=>ms,datetime:()=>ps,duration:()=>gs,time:()=>hs});var kf=y("ZodISODateTime",(e,t)=>{id.init(e,t),te.init(e,t)});function ps(e){return lf(kf,e)}var Sf=y("ZodISODate",(e,t)=>{sd.init(e,t),te.init(e,t)});function ms(e){return df(Sf,e)}var Ef=y("ZodISOTime",(e,t)=>{ad.init(e,t),te.init(e,t)});function hs(e){return ff(Ef,e)}var Tf=y("ZodISODuration",(e,t)=>{cd.init(e,t),te.init(e,t)});function gs(e){return pf(Tf,e)}var Pf=(e,t)=>{Kn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Ku(e,r)},flatten:{value:r=>Vu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},mO=y("ZodError",Pf),Br=y("ZodError",Pf,{Parent:Error});var Rf=Hu(Br),zf=Wu(Br),If=Vi(Br),Of=Ki(Br);var oe=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)=>Je(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Rf(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>If(e,r,n),e.parseAsync=async(r,n)=>zf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Of(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Hw(r,n)),e.superRefine=r=>e.check(Ww(r)),e.overwrite=r=>e.check(Rt(r)),e.optional=()=>ne(e),e.nullable=()=>Cf(e),e.nullish=()=>ne(Cf(e)),e.nonoptional=r=>Lw(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>oo(e,r),e.transform=r=>_s(e,Bf(r)),e.default=r=>jw(e,r),e.prefault=r=>qw(e,r),e.catch=r=>Zw(e,r),e.pipe=r=>_s(e,r),e.readonly=()=>Vw(e),e.describe=r=>{let n=e.clone();return Dr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Dr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Dr.get(e);let n=e.clone();return Dr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Df=y("_ZodString",(e,t)=>{Jn.init(e,t),oe.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(ns(...n)),e.includes=(...n)=>e.check(ss(...n)),e.startsWith=(...n)=>e.check(as(...n)),e.endsWith=(...n)=>e.check(cs(...n)),e.min=(...n)=>e.check(Jt(...n)),e.max=(...n)=>e.check(eo(...n)),e.length=(...n)=>e.check(to(...n)),e.nonempty=(...n)=>e.check(Jt(1,...n)),e.lowercase=n=>e.check(os(n)),e.uppercase=n=>e.check(is(n)),e.trim=()=>e.check(ls()),e.normalize=(...n)=>e.check(us(...n)),e.toLowerCase=()=>e.check(ds()),e.toUpperCase=()=>e.check(fs())}),iw=y("ZodString",(e,t)=>{Jn.init(e,t),Df.init(e,t),e.email=r=>e.check(Zd(sw,r)),e.url=r=>e.check(Hd(aw,r)),e.jwt=r=>e.check(uf(xw,r)),e.emoji=r=>e.check(Wd(cw,r)),e.guid=r=>e.check(rs(Af,r)),e.uuid=r=>e.check(Ud(no,r)),e.uuidv4=r=>e.check(Fd(no,r)),e.uuidv6=r=>e.check(Vd(no,r)),e.uuidv7=r=>e.check(Kd(no,r)),e.nanoid=r=>e.check(Gd(uw,r)),e.guid=r=>e.check(rs(Af,r)),e.cuid=r=>e.check(Jd(lw,r)),e.cuid2=r=>e.check(Qd(dw,r)),e.ulid=r=>e.check(Yd(fw,r)),e.base64=r=>e.check(sf(ww,r)),e.base64url=r=>e.check(af(bw,r)),e.xid=r=>e.check(Xd(pw,r)),e.ksuid=r=>e.check(ef(mw,r)),e.ipv4=r=>e.check(tf(hw,r)),e.ipv6=r=>e.check(rf(gw,r)),e.cidrv4=r=>e.check(nf(yw,r)),e.cidrv6=r=>e.check(of(_w,r)),e.e164=r=>e.check(cf(vw,r)),e.datetime=r=>e.check(ps(r)),e.date=r=>e.check(ms(r)),e.time=r=>e.check(hs(r)),e.duration=r=>e.check(gs(r))});function g(e){return Bd(iw,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),Df.init(e,t)}),sw=y("ZodEmail",(e,t)=>{Jl.init(e,t),te.init(e,t)});var Af=y("ZodGUID",(e,t)=>{Wl.init(e,t),te.init(e,t)});var no=y("ZodUUID",(e,t)=>{Gl.init(e,t),te.init(e,t)});var aw=y("ZodURL",(e,t)=>{Ql.init(e,t),te.init(e,t)});var cw=y("ZodEmoji",(e,t)=>{Yl.init(e,t),te.init(e,t)});var uw=y("ZodNanoID",(e,t)=>{Xl.init(e,t),te.init(e,t)});var lw=y("ZodCUID",(e,t)=>{ed.init(e,t),te.init(e,t)});var dw=y("ZodCUID2",(e,t)=>{td.init(e,t),te.init(e,t)});var fw=y("ZodULID",(e,t)=>{rd.init(e,t),te.init(e,t)});var pw=y("ZodXID",(e,t)=>{nd.init(e,t),te.init(e,t)});var mw=y("ZodKSUID",(e,t)=>{od.init(e,t),te.init(e,t)});var hw=y("ZodIPv4",(e,t)=>{ud.init(e,t),te.init(e,t)});var gw=y("ZodIPv6",(e,t)=>{ld.init(e,t),te.init(e,t)});var yw=y("ZodCIDRv4",(e,t)=>{dd.init(e,t),te.init(e,t)});var _w=y("ZodCIDRv6",(e,t)=>{fd.init(e,t),te.init(e,t)});var ww=y("ZodBase64",(e,t)=>{md.init(e,t),te.init(e,t)});var bw=y("ZodBase64URL",(e,t)=>{hd.init(e,t),te.init(e,t)});var vw=y("ZodE164",(e,t)=>{gd.init(e,t),te.init(e,t)});var xw=y("ZodJWT",(e,t)=>{yd.init(e,t),te.init(e,t)});var jf=y("ZodNumber",(e,t)=>{Xi.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(Yn(n,o)),e.gte=(n,o)=>e.check(Mr(n,o)),e.min=(n,o)=>e.check(Mr(n,o)),e.lt=(n,o)=>e.check(Qn(n,o)),e.lte=(n,o)=>e.check(jr(n,o)),e.max=(n,o)=>e.check(jr(n,o)),e.int=n=>e.check(Nf(n)),e.safe=n=>e.check(Nf(n)),e.positive=n=>e.check(Yn(0,n)),e.nonnegative=n=>e.check(Mr(0,n)),e.negative=n=>e.check(Qn(0,n)),e.nonpositive=n=>e.check(jr(0,n)),e.multipleOf=(n,o)=>e.check(Xn(n,o)),e.step=(n,o)=>e.check(Xn(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 mf(jf,e)}var $w=y("ZodNumberFormat",(e,t)=>{_d.init(e,t),jf.init(e,t)});function Nf(e){return hf($w,e)}var kw=y("ZodBoolean",(e,t)=>{wd.init(e,t),oe.init(e,t)});function ce(e){return gf(kw,e)}var Sw=y("ZodNull",(e,t)=>{bd.init(e,t),oe.init(e,t)});function Mf(e){return yf(Sw,e)}var Ew=y("ZodUnknown",(e,t)=>{vd.init(e,t),oe.init(e,t)});function re(){return _f(Ew)}var Tw=y("ZodNever",(e,t)=>{xd.init(e,t),oe.init(e,t)});function Pw(e){return wf(Tw,e)}var Rw=y("ZodArray",(e,t)=>{$d.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Jt(r,n)),e.nonempty=r=>e.check(Jt(1,r)),e.max=(r,n)=>e.check(eo(r,n)),e.length=(r,n)=>e.check(to(r,n)),e.unwrap=()=>e.element});function q(e,t){return bf(Rw,e,t)}var qf=y("ZodObject",(e,t)=>{kd.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ke(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:Pw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(Zf,e,r[0]),e.required=(...r)=>F.required(Uf,e,r[0])});function $(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new qf(r)}function be(e,t){return new qf({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var Lf=y("ZodUnion",(e,t)=>{es.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new Lf({type:"union",options:e,...F.normalizeParams(t)})}var zw=y("ZodDiscriminatedUnion",(e,t)=>{Lf.init(e,t),Sd.init(e,t)});function ws(e,t,r){return new zw({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var Iw=y("ZodIntersection",(e,t)=>{Ed.init(e,t),oe.init(e,t)});function oo(e,t){return new Iw({type:"intersection",left:e,right:t})}var Ow=y("ZodRecord",(e,t)=>{Td.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new Ow({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var ys=y("ZodEnum",(e,t)=>{Pd.init(e,t),oe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ys({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ys({...t,checks:[],...F.normalizeParams(o),entries:i})}});function ke(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ys({type:"enum",entries:r,...F.normalizeParams(t)})}var Aw=y("ZodLiteral",(e,t)=>{Rd.init(e,t),oe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function k(e,t){return new Aw({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var Nw=y("ZodTransform",(e,t)=>{zd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Bf(e){return new Nw({type:"transform",transform:e})}var Zf=y("ZodOptional",(e,t)=>{Id.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new Zf({type:"optional",innerType:e})}var Cw=y("ZodNullable",(e,t)=>{Od.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Cf(e){return new Cw({type:"nullable",innerType:e})}var Dw=y("ZodDefault",(e,t)=>{Ad.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jw(e,t){return new Dw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Mw=y("ZodPrefault",(e,t)=>{Nd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function qw(e,t){return new Mw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Uf=y("ZodNonOptional",(e,t)=>{Cd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Lw(e,t){return new Uf({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var Bw=y("ZodCatch",(e,t)=>{Dd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zw(e,t){return new Bw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Uw=y("ZodPipe",(e,t)=>{jd.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function _s(e,t){return new Uw({type:"pipe",in:e,out:t})}var Fw=y("ZodReadonly",(e,t)=>{Md.init(e,t),oe.init(e,t)});function Vw(e){return new Fw({type:"readonly",innerType:e})}var Ff=y("ZodCustom",(e,t)=>{qd.init(e,t),oe.init(e,t)});function Kw(e){let t=new me({check:"custom"});return t._zod.check=e,t}function Vf(e,t){return vf(Ff,e??(()=>!0),t)}function Hw(e,t={}){return xf(Ff,e,t)}function Ww(e){let t=Kw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(F.issue(o))}},e(r.value,r)));return t}function bs(e,t){return _s(Bf(e),t)}Oe(Ld());var xs="2025-11-25";var Kf=[xs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],pt="io.modelcontextprotocol/related-task",so="2.0",ae=Vf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Hf=Y([g(),V().int()]),Wf=g(),aA=be({ttl:V().optional(),pollInterval:V().optional()}),Gw=$({ttl:V().optional()}),Jw=$({taskId:g()}),$s=be({progressToken:Hf.optional(),[pt]:Jw.optional()}),ze=$({_meta:$s.optional()}),Zr=ze.extend({task:Gw.optional()}),Gf=e=>Zr.safeParse(e).success,ue=$({method:g(),params:ze.loose().optional()}),Ae=$({_meta:$s.optional()}),Ne=$({method:g(),params:Ae.loose().optional()}),le=be({_meta:$s.optional()}),ao=Y([g(),V().int()]),Jf=$({jsonrpc:k(so),id:ao,...ue.shape}).strict(),ks=e=>Jf.safeParse(e).success,Qf=$({jsonrpc:k(so),...Ne.shape}).strict(),Yf=e=>Qf.safeParse(e).success,Ss=$({jsonrpc:k(so),id:ao,result:le}).strict(),Ur=e=>Ss.safeParse(e).success;var O;(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"})(O||(O={}));var Es=$({jsonrpc:k(so),id:ao.optional(),error:$({code:V().int(),message:g(),data:re().optional()})}).strict();var Xf=e=>Es.safeParse(e).success;var ep=Y([Jf,Qf,Ss,Es]),cA=Y([Ss,Es]),zt=le.strict(),Qw=Ae.extend({requestId:ao.optional(),reason:g().optional()}),co=Ne.extend({method:k("notifications/cancelled"),params:Qw}),Yw=$({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:ke(["light","dark"]).optional()}),Fr=$({icons:q(Yw).optional()}),Yt=$({name:g(),title:g().optional()}),tp=Yt.extend({...Yt.shape,...Fr.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Xw=oo($({applyDefaults:ce().optional()}),J(g(),re())),eb=bs(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,oo($({form:Xw.optional(),url:ae.optional()}),J(g(),re()).optional())),tb=be({list:ae.optional(),cancel:ae.optional(),requests:be({sampling:be({createMessage:ae.optional()}).optional(),elicitation:be({create:ae.optional()}).optional()}).optional()}),rb=be({list:ae.optional(),cancel:ae.optional(),requests:be({tools:be({call:ae.optional()}).optional()}).optional()}),nb=$({experimental:J(g(),ae).optional(),sampling:$({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:eb.optional(),roots:$({listChanged:ce().optional()}).optional(),tasks:tb.optional(),extensions:J(g(),ae).optional()}),ob=ze.extend({protocolVersion:g(),capabilities:nb,clientInfo:tp}),ib=ue.extend({method:k("initialize"),params:ob});var sb=$({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:$({listChanged:ce().optional()}).optional(),resources:$({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:$({listChanged:ce().optional()}).optional(),tasks:rb.optional(),extensions:J(g(),ae).optional()}),Ts=le.extend({protocolVersion:g(),capabilities:sb,serverInfo:tp,instructions:g().optional()}),ab=Ne.extend({method:k("notifications/initialized"),params:Ae.optional()});var uo=ue.extend({method:k("ping"),params:ze.optional()}),cb=$({progress:V(),total:ne(V()),message:ne(g())}),ub=$({...Ae.shape,...cb.shape,progressToken:Hf}),lo=Ne.extend({method:k("notifications/progress"),params:ub}),lb=ze.extend({cursor:Wf.optional()}),Vr=ue.extend({params:lb.optional()}),Kr=le.extend({nextCursor:Wf.optional()}),db=ke(["working","input_required","completed","failed","cancelled"]),Hr=$({taskId:g(),status:db,ttl:Y([V(),Mf()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(V()),statusMessage:ne(g())}),It=le.extend({task:Hr}),fb=Ae.merge(Hr),Wr=Ne.extend({method:k("notifications/tasks/status"),params:fb}),fo=ue.extend({method:k("tasks/get"),params:ze.extend({taskId:g()})}),po=le.merge(Hr),mo=ue.extend({method:k("tasks/result"),params:ze.extend({taskId:g()})}),uA=le.loose(),ho=Vr.extend({method:k("tasks/list")}),go=Kr.extend({tasks:q(Hr)}),yo=ue.extend({method:k("tasks/cancel"),params:ze.extend({taskId:g()})}),rp=le.merge(Hr),np=$({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),op=np.extend({text:g()}),Ps=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ip=np.extend({blob:Ps}),Gr=ke(["user","assistant"]),Xt=$({audience:q(Gr).optional(),priority:V().min(0).max(1).optional(),lastModified:Lr.datetime({offset:!0}).optional()}),sp=$({...Yt.shape,...Fr.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(V()),annotations:Xt.optional(),_meta:ne(be({}))}),pb=$({...Yt.shape,...Fr.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:Xt.optional(),_meta:ne(be({}))}),mb=Vr.extend({method:k("resources/list")}),Rs=Kr.extend({resources:q(sp)}),hb=Vr.extend({method:k("resources/templates/list")}),zs=Kr.extend({resourceTemplates:q(pb)}),Is=ze.extend({uri:g()}),gb=Is,yb=ue.extend({method:k("resources/read"),params:gb}),Os=le.extend({contents:q(Y([op,ip]))}),As=Ne.extend({method:k("notifications/resources/list_changed"),params:Ae.optional()}),_b=Is,wb=ue.extend({method:k("resources/subscribe"),params:_b}),bb=Is,vb=ue.extend({method:k("resources/unsubscribe"),params:bb}),xb=Ae.extend({uri:g()}),$b=Ne.extend({method:k("notifications/resources/updated"),params:xb}),kb=$({name:g(),description:ne(g()),required:ne(ce())}),Sb=$({...Yt.shape,...Fr.shape,description:ne(g()),arguments:ne(q(kb)),_meta:ne(be({}))}),Eb=Vr.extend({method:k("prompts/list")}),Ns=Kr.extend({prompts:q(Sb)}),Tb=ze.extend({name:g(),arguments:J(g(),g()).optional()}),Pb=ue.extend({method:k("prompts/get"),params:Tb}),Cs=$({type:k("text"),text:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Ds=$({type:k("image"),data:Ps,mimeType:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),js=$({type:k("audio"),data:Ps,mimeType:g(),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Rb=$({type:k("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),zb=$({type:k("resource"),resource:Y([op,ip]),annotations:Xt.optional(),_meta:J(g(),re()).optional()}),Ib=sp.extend({type:k("resource_link")}),Ms=Y([Cs,Ds,js,Ib,zb]),Ob=$({role:Gr,content:Ms}),qs=le.extend({description:g().optional(),messages:q(Ob)}),Ls=Ne.extend({method:k("notifications/prompts/list_changed"),params:Ae.optional()}),Ab=$({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),Nb=$({taskSupport:ke(["required","optional","forbidden"]).optional()}),ap=$({...Yt.shape,...Fr.shape,description:g().optional(),inputSchema:$({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:$({type:k("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:Ab.optional(),execution:Nb.optional(),_meta:J(g(),re()).optional()}),Cb=Vr.extend({method:k("tools/list")}),Bs=Kr.extend({tools:q(ap)}),mt=le.extend({content:q(Ms).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),lA=mt.or(le.extend({toolResult:re()})),Db=Zr.extend({name:g(),arguments:J(g(),re()).optional()}),jb=ue.extend({method:k("tools/call"),params:Db}),Zs=Ne.extend({method:k("notifications/tools/list_changed"),params:Ae.optional()}),cp=$({autoRefresh:ce().default(!0),debounceMs:V().int().nonnegative().default(300)}),up=ke(["debug","info","notice","warning","error","critical","alert","emergency"]),Mb=ze.extend({level:up}),qb=ue.extend({method:k("logging/setLevel"),params:Mb}),Lb=Ae.extend({level:up,logger:g().optional(),data:re()}),Bb=Ne.extend({method:k("notifications/message"),params:Lb}),Zb=$({name:g().optional()}),Ub=$({hints:q(Zb).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),Fb=$({mode:ke(["auto","required","none"]).optional()}),Vb=$({type:k("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Ms).default([]),structuredContent:$({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),Kb=ws("type",[Cs,Ds,js]),io=ws("type",[Cs,Ds,js,Rb,Vb]),Hb=$({role:Gr,content:Y([io,q(io)]),_meta:J(g(),re()).optional()}),Wb=Zr.extend({messages:q(Hb),modelPreferences:Ub.optional(),systemPrompt:g().optional(),includeContext:ke(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(ap).optional(),toolChoice:Fb.optional()}),Us=ue.extend({method:k("sampling/createMessage"),params:Wb}),Fs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens"]).or(g())),role:Gr,content:Kb}),Vs=le.extend({model:g(),stopReason:ne(ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Gr,content:Y([io,q(io)])}),Gb=$({type:k("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),Jb=$({type:k("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:ke(["email","uri","date","date-time"]).optional(),default:g().optional()}),Qb=$({type:ke(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),Yb=$({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),Xb=$({type:k("string"),title:g().optional(),description:g().optional(),oneOf:q($({const:g(),title:g()})),default:g().optional()}),ev=$({type:k("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),tv=Y([Yb,Xb]),rv=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({type:k("string"),enum:q(g())}),default:q(g()).optional()}),nv=$({type:k("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:$({anyOf:q($({const:g(),title:g()}))}),default:q(g()).optional()}),ov=Y([rv,nv]),iv=Y([ev,tv,ov]),sv=Y([iv,Gb,Jb,Qb]),av=Zr.extend({mode:k("form").optional(),message:g(),requestedSchema:$({type:k("object"),properties:J(g(),sv),required:q(g()).optional()})}),cv=Zr.extend({mode:k("url"),message:g(),elicitationId:g(),url:g().url()}),uv=Y([av,cv]),Ks=ue.extend({method:k("elicitation/create"),params:uv}),lv=Ae.extend({elicitationId:g()}),dv=Ne.extend({method:k("notifications/elicitation/complete"),params:lv}),Hs=le.extend({action:ke(["accept","decline","cancel"]),content:bs(e=>e===null?void 0:e,J(g(),Y([g(),V(),ce(),q(g())])).optional())}),fv=$({type:k("ref/resource"),uri:g()});var pv=$({type:k("ref/prompt"),name:g()}),mv=ze.extend({ref:Y([pv,fv]),argument:$({name:g(),value:g()}),context:$({arguments:J(g(),g()).optional()}).optional()}),hv=ue.extend({method:k("completion/complete"),params:mv});var Ws=le.extend({completion:be({values:q(g()).max(100),total:ne(V().int()),hasMore:ne(ce())})}),gv=$({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),yv=ue.extend({method:k("roots/list"),params:ze.optional()}),_v=le.extend({roots:q(gv)}),wv=Ne.extend({method:k("notifications/roots/list_changed"),params:Ae.optional()}),dA=Y([uo,ib,hv,qb,Pb,Eb,mb,hb,yb,wb,vb,jb,Cb,fo,mo,ho,yo]),fA=Y([co,lo,ab,wv,Wr]),pA=Y([zt,Fs,Vs,Hs,_v,po,go,It]),mA=Y([uo,Us,Ks,yv,fo,mo,ho,yo]),hA=Y([co,lo,Bb,$b,As,Zs,Ls,Wr,dv]),gA=Y([zt,Ts,Ws,qs,Ns,Rs,zs,Os,mt,Bs,po,go,It]),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===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new vs(o.elicitations,r)}return new e(t,r,n)}},vs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function ht(e){return e==="completed"||e==="failed"||e==="cancelled"}var bv=Symbol("Let zodToJsonSchema decide on which parser to use");var GA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Gs(e){let r=ro(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$f(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Js(e,t){let r=Be(e,t);if(!r.success)throw r.error;return r.data}var Ev=6e4,_o=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(co,r=>{this._oncancel(r)}),this.setNotificationHandler(lo,r=>{this._onprogress(r)}),this.setRequestHandler(uo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(fo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(O.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(mo,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(O.InvalidParams,`Task not found: ${i}`);if(!ht(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ht(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[pt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(ho,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(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(yo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(ht(o.status))throw new T(O.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(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(O.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(O.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),Ur(i)||Xf(i)?this._onresponse(i):ks(i)?this._onrequest(i,s):Yf(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(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[pt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:O.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=Gf(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(O.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:O.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),Ur(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(Ur(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),Ur(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(O.InternalError,String(s))}}return}let i;try{let s=await this.request(t,It,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ht(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(O.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(O.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(O.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=v=>{u(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[pt]:c}});let m=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let x=v instanceof T?v:new T(O.RequestTimeout,String(v));u(x)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let x=Be(r,v.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??Ev,_=()=>m(T.fromError(O.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let v=x=>{let P=this._responseHandlers.get(f);P?P(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),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(v=>{this._cleanupTimeout(f),u(v)})})}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},go,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},rp,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[pt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[pt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Gs(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Js(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=Gs(t);this._notificationHandlers.set(n,o=>{let i=Js(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"&&ks(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(O.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(O.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(O.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(O.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=Wr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ht(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new T(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ht(a.status))throw new T(O.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=Wr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ht(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function lp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dp(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];lp(s)&&lp(i)?r[o]={...s,...i}:r[o]=i}return r}var rg=Oi(Dc(),1),ng=Oi(tg(),1);function RE(){let e=new rg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ng.default)(e),e}var Xo=class{constructor(t){this._ajv=t??RE()}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 ei=class{constructor(t){this._client=t}async*callToolStream(t,r=mt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new T(O.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(O.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(O.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 og(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ig(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function ti(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&&ti(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&ti(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&ti(r,t)}}function zE(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 ri=class extends _o{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 Xo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Zs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ls,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",As,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ei(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=dp(this._capabilities,t)}setRequestHandler(t,r){let o=ro(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Qt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Be(Ks,c);if(!u.success){let v=u.error instanceof Error?u.error.message:String(u.error);throw new T(O.InvalidParams,`Invalid elicitation request: ${v}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=zE(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(O.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(O.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let v=Be(It,m);if(!v.success){let x=v.error instanceof Error?v.error.message:String(v.error);throw new T(O.InvalidParams,`Invalid task creation result: ${x}`)}return v.data}let h=Be(Hs,m);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new T(O.InvalidParams,`Invalid elicitation result: ${v}`)}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{ti(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Be(Us,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(O.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Be(It,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(O.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?Vs:Fs,h=Be(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(O.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:xs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ts,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Kf.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){og(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&ig(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},zt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Ws,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},zt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},qs,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Ns,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Rs,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},zs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Os,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},zt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},zt,r)}async callTool(t,r=mt,n){if(this.isToolTaskRequired(t.name))throw new T(O.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(O.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(O.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(O.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},Bs,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=cp.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 Gg=Oi(Hg(),1);import Xc from"node:process";import{PassThrough as oT}from"node:stream";var oi=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),nT(r)}clear(){this._buffer=void 0}};function nT(e){return ep.parse(JSON.parse(e))}function Wg(e){return JSON.stringify(e)+`
37
+ `}var iT=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function sT(){let e={};for(let t of iT){let r=Xc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var ii=class{constructor(t){this._readBuffer=new oi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new oT)}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,Gg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...sT(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.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=Wg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var aT=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Ut=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new ii({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??cT(),stderr:t.stderr??"pipe"}),n=new ri({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:lT(r).map(dT),nextCursor:Jg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!si(n,["error"])&&mT(n,["ok","success"],!0),target:t,messageId:He(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:fT(r).map(pT).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=aT.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:uT(r)},mt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
+ `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function cT(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function uT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function lT(e){if(Array.isArray(e))return e;if(!br(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&br(r)?[r]:[]}function dT(e){return br(e)?{id:He(e,["id","message_id","messageId"]),cursor:Jg(e,["cursor"]),type:He(e,["type","event_type","eventType"]),platform:He(e,["platform"]),target:He(e,["target"]),sessionKey:He(e,["session_key","sessionKey"]),timestamp:He(e,["timestamp","created_at","createdAt"]),message:He(e,["message","text","content"]),raw:e}:{raw:e}}function fT(e){if(Array.isArray(e))return e;if(!br(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function pT(e){if(!br(e))return null;let t=He(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:He(e,["platform"]),name:He(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function He(e,t){let r=si(e,t);return typeof r=="string"?r:void 0}function mT(e,t,r){let n=si(e,t);return typeof n=="boolean"?n:r}function Jg(e,t){let r=si(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function si(e,t){if(br(e))for(let r of t){let n=e[r];if(n!=null)return n}}function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as Rz,writeFile as zz}from"node:fs/promises";import{join as i_}from"node:path";import{basename as o_}from"node:path";import{createHash as MT,randomUUID as pu}from"node:crypto";import{spawn as qT}from"node:child_process";import{constants as lu}from"node:fs";import{readFileSync as LT}from"node:fs";import{mkdir as fy,open as BT,readFile as ZT,rename as BM,rm as In,stat as ZM,writeFile as UM}from"node:fs/promises";import{tmpdir as UT}from"node:os";import{dirname as xr,join as qe,resolve as fi}from"node:path";import{fileURLToPath as FT}from"node:url";var ai=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 ai(e,t)}var ci=",";function eu(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 nt(e){return E(e,"invalid quoted string")}function kt(e,t){if(e==="")return"";if(e.startsWith('"'))return Qg(e,t);if(e.includes('"'))throw nt(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:hT(e)?Number(e):e}function Ft(e,t){let r=e.trim();if(r.startsWith('"'))return[Qg(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function Qg(e,t){if(e[0]!=='"')throw nt(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw nt(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
+ `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw nt(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw nt(t);r+=String.fromCharCode(a),n+=4;break}default:throw nt(t)}continue}if(o<" "&&o!==" ")throw nt(t);r+=o}throw nt(t)}function Tn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw nt(r);return n.push(e.slice(o).trim()),n}function Re(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw nt(r);return-1}function hT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Pn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Xg=2;function wT(e={}){return{indent:Math.max(1,e.indent??Xg),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function bT(e,t){let r=[],n=!1;return eu(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 zn(e,t){let r=wT(t),n=bT(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=au(o.content,Re(o.content,":",o.number))}catch(u){if(r.strict)throw ou(u,o.number);l=void 0}if(l!==void 0)return $T(l,n,r)}if(i&&Re(o.content,":",o.number)===-1)return kt(o.content.trim(),o.number);let s={index:0},a=iu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function iu(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}=vT(e,t,r,n);ty(o,s,a,c,n,i.number)}return o}function vT(e,t,r,n){let o=e[t.index],i=o.content,s=Re(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=Re(a,"[",o.number),u=Re(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=TT(a)}catch(_){if(n.strict)throw ou(_,o.number);t.index+=1;let w=tu(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=xT(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=au(a,s)}catch(_){if(n.strict)throw ou(_,o.number);t.index+=1;let w=tu(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=su(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Ft(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=tu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function tu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return kt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?iu(e,t,r+1,i):{}}function xT(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=Re(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Ft(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Tn(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)=>{Rn(d,f,kt(u[p],s.number),o,s.number)}),ty(i,c,l,d,o,s.number),r.index+=1}return i}function $T(e,t,r){let n=t[0],o=Re(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=su(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 su(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 kT(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Tn(a,e.delimiter,s).map(l=>kt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return ST(e,r,n,o+1,i)}function kT(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw ru(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(!Yg(c.content,e.delimiter,c.number))break;let l=Tn(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)=>{Rn(u,d,kt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw ru(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&Yg(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function Yg(e,t,r){let n=Re(e,":",r);if(n===-1)return!0;let o=Re(e,t,r);return o===-1?!1:o<n}function ST(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 ru(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(ET(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 ET(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=Re(i,":",o.number),a;try{a=au(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return su(a,c,e,t,r,n)}}if(Re(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return iu(s,{index:0},r+1,n)}return t.index+=1,kt(i,o.number)}function ru(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function au(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=Re(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Ft(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=ey(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 TT(e){let t=Re(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Ft(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=ey(e.slice(t+1,-1),ci)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:ci,fields:o}}function ey(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]=Ft(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(PT(r[a],r[c])||nu(r[a],r[c])||nu(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 PT(e,t){return e.length===t.length&&nu(e,t)}function nu(e,t){return t.every((r,n)=>e[n]===r)}function ou(e,t){return E(t,e.reason??String(e.message))}function ty(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(RT)){Rn(e,s,n,o,i);return}}Rn(e,[t],n,o,i)}function Rn(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");Pn(e,i,r);return}if(s&&!zT(e[i])){if(n.strict)throw E(o,"path expansion conflict");Pn(e,i,{})}else s||Pn(e,i,{});Rn(e[i],t.slice(1),r,n,o)}function RT(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function zT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var rM=new TextEncoder,nM=new TextDecoder;import{isAbsolute as OM,join as vr,resolve as OT}from"node:path";var AT=".red";function NT(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function ry(e){return vr(NT(e),AT)}function ny(e){return vr(ry(e),"state")}function CT(e){return vr(ry(e),"tmp")}function oy(e){return vr(ny(e),"rsp")}function cu(e){return vr(ny(e),"red-skills.rdb")}var DT=".red/tmp/red-skills.rdb";function iy(e){return vr(CT(e),"red-skills.rdb")}function sy(e,t){let r=cu(e);if(t(r))return r;let n=iy(e);if(t(n))throw uu();return r}function ay(e,t){return t===DT||OT(e,t)===iy(e)}function uu(){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{createConnection as jT}from"node:net";async function li(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=jT(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
41
41
  `)}),i.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
42
- `);if(d<0)return;let f=a.slice(0,d);l(()=>{try{n(JSON.parse(f))}catch(p){o(p)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var BT=108,ZT=1,UT=5e3;function pi(e){let t=nP(e)??fi(e),r=rP(t),n=oy(t);return{rootDir:t,socketPath:qe(r,"rsp.sock"),pidPath:qe(r,"rsp.pid"),lockPath:qe(r,"rsp.lock"),wakeLockPath:qe(t,".red","tmp","rsp.wake.lock"),summaryPath:qe(n,"rsp-status-summary.json"),registryPath:qe(n,"rsp-resident.pid.json")}}var di=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await FT(this.paths,this.config);let r=await li(this.paths,{...t,id:pu()});if(!r.ok)throw new Error(r.error);return r.value}};async function FT(e,t){if(await ly(xr(e.socketPath),{recursive:!0,mode:448}),await cy(e.socketPath,t))return;await ay(e,t);let r=await WT(e.lockPath);if(r)try{if(await cy(e.socketPath,t))return;await ay(e,t),await HT(e.socketPath);let n=GT(e,t);await sy(e.socketPath,n);return}finally{await r.close(),await In(e.lockPath,{force:!0})}await sy(e.socketPath)}async function An(e,t=200){try{return await dy(e,t)!=null}catch{return!1}}async function dy(e,t=200){let r=await li({socketPath:e,timeoutMs:t},{id:pu(),op:"ping"});return r.ok?py(r.value)?{version:aP(r.value.version)}:{}:null}async function VT(e){try{let t=YT(await MT(e,"utf8"));return cP(t)?t:null}catch{return null}}async function sy(e,t){let r=Date.now()+KT(),n;for(;Date.now()<r;){if(await An(e))return;if(t){let o=t.spawnError();if(o)throw new Error(du("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(du("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?du("resident rsp server did not start",t):"resident rsp server did not start")}function KT(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:UT}async function HT(e){await In(e,{force:!0})}async function WT(e){await ly(xr(e),{recursive:!0,mode:448});try{return await jT(e,lu.O_CREAT|lu.O_EXCL|lu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function GT(e,t){let[r,n]=tP(t),o=process.env.RSP_DEBUG==="1",i,s="",a=CT(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=QT(`${s}${c}`,JT)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var JT=8*1024;function du(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
42
+ `);if(d<0)return;let f=a.slice(0,d);l(()=>{try{n(JSON.parse(f))}catch(p){o(p)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var VT=108,KT=1,HT=5e3;function pi(e){let t=aP(e)??fi(e),r=sP(t),n=oy(t);return{rootDir:t,socketPath:qe(r,"rsp.sock"),pidPath:qe(r,"rsp.pid"),lockPath:qe(r,"rsp.lock"),wakeLockPath:qe(t,".red","tmp","rsp.wake.lock"),summaryPath:qe(n,"rsp-status-summary.json"),registryPath:qe(n,"rsp-resident.pid.json")}}var di=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await WT(this.paths,this.config);let r=await li(this.paths,{...t,id:pu()});if(!r.ok)throw new Error(r.error);return r.value}};async function WT(e,t){if(await fy(xr(e.socketPath),{recursive:!0,mode:448}),await ly(e.socketPath,t))return;await uy(e,t);let r=await YT(e.lockPath);if(r)try{if(await ly(e.socketPath,t))return;await uy(e,t),await QT(e.socketPath);let n=XT(e,t);await cy(e.socketPath,n);return}finally{await r.close(),await In(e.lockPath,{force:!0})}await cy(e.socketPath)}async function An(e,t=200){try{return await py(e,t)!=null}catch{return!1}}async function py(e,t=200){let r=await li({socketPath:e,timeoutMs:t},{id:pu(),op:"ping"});return r.ok?hy(r.value)?{version:dP(r.value.version)}:{}:null}async function GT(e){try{let t=rP(await ZT(e,"utf8"));return fP(t)?t:null}catch{return null}}async function cy(e,t){let r=Date.now()+JT(),n;for(;Date.now()<r;){if(await An(e))return;if(t){let o=t.spawnError();if(o)throw new Error(du("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(du("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?du("resident rsp server did not start",t):"resident rsp server did not start")}function JT(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:HT}async function QT(e){await In(e,{force:!0})}async function YT(e){await fy(xr(e),{recursive:!0,mode:448});try{return await BT(e,lu.O_CREAT|lu.O_EXCL|lu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function XT(e,t){let[r,n]=iP(t),o=process.env.RSP_DEBUG==="1",i,s="",a=qT(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=tP(`${s}${c}`,eP)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var eP=8*1024;function du(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
43
43
  ${o}`),n.join(`
44
- `)}function QT(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function YT(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return zn(t)}}async function ay(e,t){try{let r=await VT(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!On(r.pid)){await In(e.registryPath,{force:!0});return}if(await An(r.socket_path,100))return;if(fy(t.clientVersion,r.resident_version)&&(await eP(r.pid,1500),!On(r.pid))){await In(e.registryPath,{force:!0});return}await XT(r.pid),await In(e.registryPath,{force:!0})}catch{}}function On(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function XT(e){if(!On(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!On(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function eP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!On(e))return;await new Promise(n=>setTimeout(n,50))}}function tP(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?fi(process.argv[1]):LT(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function rP(e){let t=NT("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=qe(r,"red-skills",t);if(qe(o,"rsp.sock").length<BT)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return qe(qT(),`red-skills-${n}`,t)}function nP(e){let t=fi(e);for(let r=0;r<32;r++){try{let o=fu(qe(t,".git"));if(o!=null)return oP(t,o)??t;if(fu(qe(t,".git","HEAD"))!=null||fu(qe(t,".red","config.yaml"))!=null)return t}catch{}let n=xr(t);if(n===t)return null;t=n}return null}function oP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=fi(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?xr(xr(xr(n))):null}function fu(e){try{return DT(e,"utf8")}catch{return null}}async function cy(e,t){let r=await dy(e).catch(()=>null);return r?fy(t.clientVersion,r.version)?(await iP(e,t.clientVersion),await uP(e),!1):!0:!1}async function iP(e,t){try{await li({socketPath:e,timeoutMs:200},{id:pu(),op:"handover",clientVersion:t})}catch{}}function fy(e,t){return!e||!t?!1:sP(e,t)>0}function sP(e,t){let r=uy(e),n=uy(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function uy(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 py(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aP(e){return typeof e=="string"&&e.length>0?e:void 0}function cP(e){return py(e)&&e.version===ZT&&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 uP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await An(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as lP}from"node:child_process";var hu=["supports","contradicts","related_to"];function gu(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 yu(e){return typeof e=="string"&&hu.includes(e)}function $r(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function my(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
45
- `)}function dP(e){return{deriveConnections(t){return pP(e,t)}}}function hy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return dP({command:t,args:mP(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:hP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function fP(e){let t=JSON.parse(gP(e));return(Array.isArray(t)?t:mu(t)&&Array.isArray(t.connections)?t.connections:[]).filter(yP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:mu(n.metadata)?n.metadata:void 0}))}async function pP(e,t){let r=lP(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 fP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function mP(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 hP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function gP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function yP(e){return mu(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&yu(e.kind)}function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as mi}from"node:fs";import{mkdir as _P,readFile as _u,writeFile as wP}from"node:fs/promises";import{dirname as wu,isAbsolute as bP,join as kr,resolve as St}from"node:path";var hi="file://./.red/brain/brain.rdb",vP="RED_BRAIN_ROOT",xP="brain.root";async function $P(e=process.cwd(),t={}){let n=(t.env??process.env)[vP];if(n)return St(e,n);let o=await kP(e);if(o)return o;let i=St(e),s=null;for(;;){let a=kr(i,".red");if(mi(a)&&(s??=i,mi(kr(a,"brain"))||mi(kr(a,xP))))return i;let c=wu(i);if(c===i)return s??St(e);i=c}}async function kP(e){let t=St(e);for(;;){let r=kr(t,".red","config.yaml");try{let o=await _u(r,"utf8"),i=SP(o);if(i)return St(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=wu(t);if(n===t)return null;t=n}}function SP(e){let t=EP(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 EP(e){let t={},r=[],n=[];for(let o of e.split(`
46
- `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function gy(e){return kr(St(e),".red","brain","config.yaml")}function TP(e){return kr(St(e),".env")}async function PP(e){let t=gy(e);return mi(t)||(await _P(wu(t),{recursive:!0}),await wP(t,`connection_string: ${hi}
47
- `,"utf8")),t}async function RP(e){let t=gy(e);try{let r=await _u(t,"utf8");return zP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function zP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:hi};let r=t.slice(18).trim();return{connection_string:yy(r)||hi}}function yy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function _y(e=process.cwd()){let t=await $P(e),r=await PP(t),n=await RP(t)??{connection_string:hi},o=await IP(t),i=n.connection_string,s=OP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:AP(t,s)}}async function IP(e){let t={...process.env};try{let r=await _u(TP(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=yy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function OP(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 AP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return bP(r)?t:`file://${St(e,r)}`}import{existsSync as NP}from"node:fs";import{resolve as CP}from"node:path";var DP=7,jP=64*1024*1024;function by(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);return t===cu(e.rootDir)||t===uu(e.rootDir)}async function vy(e){let t=pi(e.rootDir),r=new di(t,qP(e.rootDir));return await r.request({op:"ping"}),new bu(r)}function MP(e){return`file://${iy(CP(e),NP)}`}function qP(e){return{storeUri:MP(e),ttlDays:DP,byteBudget:jP,serverCommand:process.env.RSP_BIN??"rsp"}}var bu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return LP(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:wy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:wy(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 wy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function LP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var BP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",ZP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function xy(e,t){return BP?FP(e,t):ZP?KP(e,t):UP(e,t)}async function UP(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 FP(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:VP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*VP(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 KP(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:HP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*HP(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 JP}from"node:url";import{dirname as QP,resolve as YP,join as fq}from"node:path";import{existsSync as WP}from"node:fs";import{join as GP}from"node:path";function $y(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=GP(r,"bin",t);if(WP(i))return i;throw new Error(`reddb: binary "${t}" not found.
44
+ `)}function tP(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function rP(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return zn(t)}}async function uy(e,t){try{let r=await GT(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!On(r.pid)){await In(e.registryPath,{force:!0});return}if(await An(r.socket_path,100))return;if(my(t.clientVersion,r.resident_version)&&(await oP(r.pid,1500),!On(r.pid))){await In(e.registryPath,{force:!0});return}await nP(r.pid),await In(e.registryPath,{force:!0})}catch{}}function On(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function nP(e){if(!On(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!On(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function oP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!On(e))return;await new Promise(n=>setTimeout(n,50))}}function iP(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?fi(process.argv[1]):FT(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function sP(e){let t=MT("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=qe(r,"red-skills",t);if(qe(o,"rsp.sock").length<VT)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return qe(UT(),`red-skills-${n}`,t)}function aP(e){let t=fi(e);for(let r=0;r<32;r++){try{let o=fu(qe(t,".git"));if(o!=null)return cP(t,o)??t;if(fu(qe(t,".git","HEAD"))!=null||fu(qe(t,".red","config.yaml"))!=null)return t}catch{}let n=xr(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=fi(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?xr(xr(xr(n))):null}function fu(e){try{return LT(e,"utf8")}catch{return null}}async function ly(e,t){let r=await py(e).catch(()=>null);return r?my(t.clientVersion,r.version)?(await uP(e,t.clientVersion),await pP(e),!1):!0:!1}async function uP(e,t){try{await li({socketPath:e,timeoutMs:200},{id:pu(),op:"handover",clientVersion:t})}catch{}}function my(e,t){return!e||!t?!1:lP(e,t)>0}function lP(e,t){let r=dy(e),n=dy(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function dy(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 hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dP(e){return typeof e=="string"&&e.length>0?e:void 0}function fP(e){return hy(e)&&e.version===KT&&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 pP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await An(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as mP}from"node:child_process";var hu=["supports","contradicts","related_to"];function gu(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 yu(e){return typeof e=="string"&&hu.includes(e)}function $r(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function gy(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
45
+ `)}function hP(e){return{deriveConnections(t){return yP(e,t)}}}function yy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return hP({command:t,args:_P(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:wP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function gP(e){let t=JSON.parse(bP(e));return(Array.isArray(t)?t:mu(t)&&Array.isArray(t.connections)?t.connections:[]).filter(vP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:mu(n.metadata)?n.metadata:void 0}))}async function yP(e,t){let r=mP(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 gP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function _P(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 wP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function bP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function vP(e){return mu(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&yu(e.kind)}function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as mi}from"node:fs";import{mkdir as xP,readFile as _u,writeFile as $P}from"node:fs/promises";import{dirname as wu,isAbsolute as kP,join as kr,resolve as St}from"node:path";var hi="file://./.red/brain/brain.rdb",SP="RED_BRAIN_ROOT",EP="brain.root";async function TP(e=process.cwd(),t={}){let n=(t.env??process.env)[SP];if(n)return St(e,n);let o=await PP(e);if(o)return o;let i=St(e),s=null;for(;;){let a=kr(i,".red");if(mi(a)&&(s??=i,mi(kr(a,"brain"))||mi(kr(a,EP))))return i;let c=wu(i);if(c===i)return s??St(e);i=c}}async function PP(e){let t=St(e);for(;;){let r=kr(t,".red","config.yaml");try{let o=await _u(r,"utf8"),i=RP(o);if(i)return St(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=wu(t);if(n===t)return null;t=n}}function RP(e){let t=zP(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 zP(e){let t={},r=[],n=[];for(let o of e.split(`
46
+ `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function _y(e){return kr(St(e),".red","brain","config.yaml")}function IP(e){return kr(St(e),".env")}async function OP(e){let t=_y(e);return mi(t)||(await xP(wu(t),{recursive:!0}),await $P(t,`connection_string: ${hi}
47
+ `,"utf8")),t}async function AP(e){let t=_y(e);try{let r=await _u(t,"utf8");return NP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function NP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:hi};let r=t.slice(18).trim();return{connection_string:wy(r)||hi}}function wy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function by(e=process.cwd()){let t=await TP(e),r=await OP(t),n=await AP(t)??{connection_string:hi},o=await CP(t),i=n.connection_string,s=DP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:jP(t,s)}}async function CP(e){let t={...process.env};try{let r=await _u(IP(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=wy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function DP(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 jP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return kP(r)?t:`file://${St(e,r)}`}import{existsSync as MP}from"node:fs";import{resolve as qP}from"node:path";var LP=7,BP=64*1024*1024;function xy(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(ay(e.rootDir,t))throw uu();return t===cu(e.rootDir)}async function $y(e){let t=pi(e.rootDir),r=new di(t,UP(e.rootDir));return await r.request({op:"ping"}),new bu(r)}function ZP(e){return`file://${sy(qP(e),MP)}`}function UP(e){return{storeUri:ZP(e),ttlDays:LP,byteBudget:BP,serverCommand:process.env.RSP_BIN??"rsp"}}var bu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return FP(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:vy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:vy(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 vy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function FP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var VP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",KP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function ky(e,t){return VP?WP(e,t):KP?JP(e,t):HP(e,t)}async function HP(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 WP(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:GP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*GP(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 JP(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:QP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*QP(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 eR}from"node:url";import{dirname as tR,resolve as rR,join as hq}from"node:path";import{existsSync as YP}from"node:fs";import{join as XP}from"node:path";function Sy(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=XP(r,"bin",t);if(YP(i))return i;throw new Error(`reddb: binary "${t}" not found.
48
48
  expected at: ${i}
49
49
  override: set ${n}=/path/to/${t}
50
50
  fix: re-run \`pnpm install\` (the postinstall script downloads it),
51
- or check the postinstall log for a download error.`)}var XP=QP(JP(import.meta.url)),eR=YP(XP,"..");function tR(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function ky(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:$y({name:tR(),packageRoot:eR,envVar:"REDDB_BIN"})}var rR=new TextEncoder,nR=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},gi=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(rR.encode(o+`
52
- `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(nR.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:/"?oR(e):iR(e)}function oR(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=sR(o),a=r.port?Number(r.port):vu(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 iR(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):vu(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):vu(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 sR(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 vu(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 aR=new Set(["embedded"]),Nn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&aR.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:uR(n.value)}async put(t,r,n,o={}){this._guard("put");let i=cR(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 cR(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Sy(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Sy(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Sy(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 uR(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 Sr=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(Ey).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${$u(o,t)} = ${dR(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 ${$u(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 ${$u(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 ${ku(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(Ey).join(", ")}] FROM ${ku(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
51
+ or check the postinstall log for a download error.`)}var nR=tR(eR(import.meta.url)),oR=rR(nR,"..");function iR(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function Ey(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:Sy({name:iR(),packageRoot:oR,envVar:"REDDB_BIN"})}var sR=new TextEncoder,aR=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},gi=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(sR.encode(o+`
52
+ `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(aR.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:/"?cR(e):uR(e)}function cR(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=lR(o),a=r.port?Number(r.port):vu(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 uR(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):vu(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):vu(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 lR(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 vu(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 dR=new Set(["embedded"]),Nn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&dR.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:pR(n.value)}async put(t,r,n,o={}){this._guard("put");let i=fR(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 fR(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Ty(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Ty(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Ty(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 pR(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 Sr=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(Py).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${$u(o,t)} = ${hR(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 ${$u(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 ${$u(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 ${ku(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(Py).join(", ")}] FROM ${ku(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
53
53
 
54
54
  `)){let u=l.split(`
55
- `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function $u(e,t){return`${ku(e)}.${lR(t)}`}function ku(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 lR(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function dR(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 Ey(e){return`'${String(e).replace(/'/g,"''")}'`}var Cn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${lt(t)}`})}push(t,r,n={}){let o=mR(n);return this.client.call("query",{sql:`QUEUE PUSH ${lt(t)} ${hR(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${lt(t)}${Eu(r)}`});return Su(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${lt(t)}${Eu(r)}`});return Su(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${lt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${lt(t)}`})}async readWait(t,r,n={}){let o=fR(t,r,n),i=await this.client.call("query",{sql:o});return Su(i)}};function fR(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=lt(e),a=lt(t),c=o!=null?` GROUP ${lt(o)}`:"",l=i!=null?Eu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function lt(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Eu(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 pR(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function mR(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 ${pR(e.priority)}`),e.key!=null&&(t+=` KEY ${Tu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Tu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function hR(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Tu(e):JSON.stringify(e)}function Tu(e){return`'${String(e).replace(/'/g,"''")}'`}function Su(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Dn=class{constructor(t){this.db=t}async insert(t,r){Ty(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${yi(t)} DOCUMENT VALUES (${_R(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=gR(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 ${yi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){Ty(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])=>`${Py(c)} = ${wR(l)}`).join(", "),a=(await this.db.query(`UPDATE ${yi(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 ${yi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function Ty(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function gR(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 yi(e){return String(e).split(".").map(Py).join(".")}function Py(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 yR(e){return Ry(JSON.stringify(e))}function _R(e){return JSON.stringify(e)}function wR(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?yR(e):Ry(e)}function Ry(e){return`'${String(e).replace(/'/g,"''")}'`}var jn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){vR(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(zy).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${Et(o)} ${Et(t)} = ${bR(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${Et(n)} ${Et(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${Et(n)} ${Et(t)}`})}};function bR(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${Et(r)}.${Et(n)})`}return xR(e)}function vR(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 Et(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 xR(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):zy(e)}function zy(e){return`'${String(e).replace(/'/g,"''")}'`}var Mn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){$R(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Iy).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Er(o)}.${Er(t)} = ${kR(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Er(n)}.${Er(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Er(n)}.${Er(t)}`})}};function $R(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 Er(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 kR(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Iy(e)}function Iy(e){return`'${String(e).replace(/'/g,"''")}'`}async function Ay(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(SR)}async function Ny(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${TR(t)}`)).rows??[]).some(n=>n.name===String(t))}var qn=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(Oy).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${Oy(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 SR(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function Oy(e){return String(e).split(".").map(ER).join(".")}function ER(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 TR(e){return`'${String(e).replace(/'/g,"''")}'`}var PR="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",RR="1.0",jy="1.0.9",Cy="NESTED_TX_NOT_SUPPORTED";async function My(e,t={}){let r=xu(e);if(jR(r),r.kind==="embedded"){let n=DR(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=CR(r),i=t.binary??ky(),s=await xy(i,o),a=new gi(s);return await a.call("version",{}),new Ru(a,{transport:"embedded"})}}function Dy(e){return zR(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:OR(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&NR(e)?{$uuid:e}:e}function zR(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 IR(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Dy):e.map(Dy)}function OR(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 AR(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 NR(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function _i(e){if(Array.isArray(e))return e.map(_i);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return AR(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]=_i(o);return r}return e}function CR(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function DR(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 jR(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",PR)}var wi=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 zu()}},Pu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw zu();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 wi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){qy(r,n)}throw r}}},Ru=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=RR,this.cache=new Nn(t,this.transport),this.queue=new Cn(t),this.queues=this.queue,this.documents=new Dn(this);let n=new Sr(t);this.kv=Object.assign((o="kv_default")=>new Sr(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 jn(t,o),this.vault=(o="red.vault")=>new Mn(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=IR(r);return n==null?this.client.call("query",{sql:t}).then(_i):this.client.call("query",{sql:t,params:n}).then(_i)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return MR(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 qR(n,r.length)}tx(){return new Pu(this)}async transaction(t){if(this.inTransaction)throw zu();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 wi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){qy(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return Ny(this,t)}list(){return Ay(this)}from(t){return new qn(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 zu(){return new z(Cy,`${Cy}: nested transactions are not supported on one connection`)}function qy(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function MR(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${jy} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function qR(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 >= ${jy} 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 Ln(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"&&LR(t.chosenOption)&&BR(t.outcome)&&ZR(t.cost)}function LR(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function BR(e){return e==="success"||e==="failure"||e==="escalated"}function ZR(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 UR}from"node:crypto";function Iu(e){return UR("sha256").update(e).digest("hex")}function Ly(e){return Iu(JSON.stringify(e))}function By(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Ou="unknown",bi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Cu(t.from),i=Cu(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>FR(p,n)).filter(p=>p!=null).filter(p=>KR(p,t)).filter(p=>HR(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=JR(c,l,r),f=[Zy(null,s,u,r)];if(t.groupBy){let m=[...WR(s,t.groupBy).entries()].map(([h,_])=>Zy(h,_,u,r)).sort((h,_)=>_.total-h.total||YR(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function FR(e,t){let r=e.properties.metadata??{},n=VR(e,r,t);return n==null?null:{ts:n,platform:Au(r,"platform")??Ou,eventType:Au(r,"event_type")??Ou,target:Au(r,"target")??Ou}}function VR(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Cu(t.timestamp)??n}function Au(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function KR(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 HR(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function WR(e,t){let r=new Map;for(let n of e){let o=GR(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function GR(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Zy(e,t,r,n){let o=new Map;for(let s of t){let a=Nu(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 JR(e,t,r){if(e==null||t==null)return[];let n=[],o=Nu(e,r),i=Nu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=QR(o,r),s++;return n}function Nu(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 QR(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 Cu(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 YR(e,t){return String(e??"").localeCompare(String(t??""))}var XR=["validate","simple","complex","think"];var ez={validate:1,simple:.85,complex:.65,think:.45};function tz(){return{schemaVersion:1,buckets:{}}}function Fy(e,t={}){let r=az(t.initial??tz());for(let n of e)rz(r,n,t);return r}function rz(e,t,r={}){let n=(r.tierForEvent??nz)(t);if(!n)return e;let i=iz(e,t.taskClass).arms[n],s=oz(t,n);return i.posterior.alpha=Uy(i.posterior.alpha+s),i.posterior.beta=Uy(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 nz(e){let t=e.chosenOption.kind;if(cz(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 oz(e,t){return e.outcome!=="success"?0:ez[t]}function iz(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=sz(),e.buckets[r]}function sz(){return{arms:{validate:vi(),simple:vi(),complex:vi(),think:vi()}}}function vi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function az(e){return JSON.parse(JSON.stringify(e))}function cz(e){return XR.includes(e)}function Uy(e){return Math.round(e*1e3)/1e3}var xi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Vy={contact:"person"},$i=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],We={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Si=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 My(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 ${We.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${We.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${We.outcomeEvents}`)}kv(){return this.db.kv(We.kv)}async capture(t){let r=Yy(t.kind??"note"),n=Date.now(),o=fz(t.tags??[]),i=Ly([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=`${By(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 ${We.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(Hy(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 ${We.artifacts}`);this.artifactCache=t.rows.map(uz).filter(ki)}return this.artifactCache}async search(t,r=10,n={}){let o=pz(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=e_(u,o),f=t_({...d,connections:mz(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:gz(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=Xy(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 ${We.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(Wy(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 ${We.connections}`);this.connectionCache=t.rows.map(lz).filter(ki)}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:$z(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new bi(r).events(t)}async appendOutcomeEvent(t){if(!Ln(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${We.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 ${We.outcomeEvents}`);this.outcomeEventCache=t.rows.map(dz).filter(ki).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(Gy());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return Jy(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!Jy(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(Gy(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=Fy(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!$r(i.artifact)).slice(0,r);return yz(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(Hy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Wy(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||$r(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=my(t),i=new Set([t.rid]);for(let d of r)$r(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!$r(d.artifact)).map(d=>({artifact:gu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:gu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:hu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!yu(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 Yy(e){let r=Vy[e]??e;if(xi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Xy(e){if($i.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function uz(e){let t=Number(e.red_entity_id??e.rid),r=Du(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:Yy(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 lz(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:Xy(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:Du(e.properties??e.PROPERTIES)}}function dz(e){let t=Number(e.red_entity_id??e.rid),r=Du(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Ln(r)?null:{rid:t,event:r}}function Du(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function ki(e){return e!=null}function fz(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function pz(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Ky(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function e_(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+Ky(r,a)*3+Ky(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 mz(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||$r(a))continue;let c=t_({...e_(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*hz(i.kind))}return Vt(o*.35)}function hz(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 t_(e){return{...e,lexical:Vt(e.lexical),tags:Vt(e.tags),kind:Vt(e.kind),connections:Vt(e.connections),vector:Vt(e.vector),total:Vt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Vt(e){return Math.round(e*1e3)/1e3}function gz(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 yz(e,t){let r=t.map(_z),n=wz(t),o=bz(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:vz(e,r,n,o)}}function _z(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 wz(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 bz(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 vz(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
56
- `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${xz(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
57
- `)}function xz(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(ki);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function Hy(e){return`artifact.hash.${e}`}function Wy(e,t,r){return`connection.${e}.${r}.${t}`}function Gy(){return`model-tier-bandit.v${1}`}function Jy(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function $z(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function kz(e=process.cwd()){let t=await _y(e);if(by(t))try{return{config:t,store:await vy(t),project:r_(t.rootDir)}}catch(n){let o=pi(t.rootDir);if(await An(o.socketPath,50))throw n}let r=await Si.open({uri:t.connectionString,autoLinker:hy()});return{config:t,store:r,project:r_(t.rootDir)}}async function _e(e,t=process.cwd()){let r=await kz(t);try{return await e(r)}finally{await r.store.close()}}async function o_(e,t){if(e!=="SessionStart")return{};let r=await _e(async({config:o,store:i})=>(await i.status(),o)),n=n_(r.rootDir,".red","brain","sessions");return await Sz(n,{recursive:!0}),await Ez(n_(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var Ei=class{map({event:t,sourceAgent:r}){return{title:Tz(t),content:Pz(t),kind:"event",tags:Rz(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:i_(t),metadata:zz(t)}}};function i_(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Iu(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function Tz(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 Pz(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
58
- `)||JSON.stringify(e.raw)}function Rz(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function zz(e){let t={event_key:i_(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 Ti(e){let t=new Ei,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Kt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function a_(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Kt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Kt("brain_act requires a non-empty message");let o=t.connect??(a=>Ut.connect(a)),i=t.process??Iz(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Kt(`brain_act could not reach the channel bridge: ${s_(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Kt(`brain_act could not send to "${r}": ${s_(c)}`,{cause:c})}if(!a.ok)throw new Kt(`brain_act could not send to "${r}": ${Oz(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function Iz(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 Oz(e){return Az(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function Az(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 s_(e){return e instanceof Error?e.message:String(e)}import{createServer as Nz}from"node:http";async function l_(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:ju(n,"supports"),contradicts:ju(n,"contradicts"),depends_on:ju(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=>Cz(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=>Dz(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 d_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:jz(e)}}async function f_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=Nz((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
59
- `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function Cz(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:Lz(e.properties.content)}}function Dz(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 jz(e){return`<!doctype html>
55
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function $u(e,t){return`${ku(e)}.${mR(t)}`}function ku(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 mR(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function hR(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 Py(e){return`'${String(e).replace(/'/g,"''")}'`}var Cn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${lt(t)}`})}push(t,r,n={}){let o=_R(n);return this.client.call("query",{sql:`QUEUE PUSH ${lt(t)} ${wR(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${lt(t)}${Eu(r)}`});return Su(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${lt(t)}${Eu(r)}`});return Su(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${lt(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${lt(t)}`})}async readWait(t,r,n={}){let o=gR(t,r,n),i=await this.client.call("query",{sql:o});return Su(i)}};function gR(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=lt(e),a=lt(t),c=o!=null?` GROUP ${lt(o)}`:"",l=i!=null?Eu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function lt(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Eu(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 yR(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function _R(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 ${yR(e.priority)}`),e.key!=null&&(t+=` KEY ${Tu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Tu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function wR(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Tu(e):JSON.stringify(e)}function Tu(e){return`'${String(e).replace(/'/g,"''")}'`}function Su(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Dn=class{constructor(t){this.db=t}async insert(t,r){Ry(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${yi(t)} DOCUMENT VALUES (${xR(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=bR(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 ${yi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){Ry(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])=>`${zy(c)} = ${$R(l)}`).join(", "),a=(await this.db.query(`UPDATE ${yi(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 ${yi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function Ry(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function bR(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 yi(e){return String(e).split(".").map(zy).join(".")}function zy(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 vR(e){return Iy(JSON.stringify(e))}function xR(e){return JSON.stringify(e)}function $R(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?vR(e):Iy(e)}function Iy(e){return`'${String(e).replace(/'/g,"''")}'`}var jn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){SR(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Oy).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${Et(o)} ${Et(t)} = ${kR(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${Et(n)} ${Et(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${Et(n)} ${Et(t)}`})}};function kR(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${Et(r)}.${Et(n)})`}return ER(e)}function SR(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 Et(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 ER(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Oy(e)}function Oy(e){return`'${String(e).replace(/'/g,"''")}'`}var Mn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){TR(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Ay).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Er(o)}.${Er(t)} = ${PR(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Er(n)}.${Er(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Er(n)}.${Er(t)}`})}};function TR(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 Er(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 PR(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Ay(e)}function Ay(e){return`'${String(e).replace(/'/g,"''")}'`}async function Cy(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(RR)}async function Dy(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${IR(t)}`)).rows??[]).some(n=>n.name===String(t))}var qn=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(Ny).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${Ny(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 RR(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function Ny(e){return String(e).split(".").map(zR).join(".")}function zR(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 IR(e){return`'${String(e).replace(/'/g,"''")}'`}var OR="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",AR="1.0",qy="1.0.9",jy="NESTED_TX_NOT_SUPPORTED";async function Ly(e,t={}){let r=xu(e);if(BR(r),r.kind==="embedded"){let n=LR(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=qR(r),i=t.binary??Ey(),s=await ky(i,o),a=new gi(s);return await a.call("version",{}),new Ru(a,{transport:"embedded"})}}function My(e){return NR(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:DR(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&MR(e)?{$uuid:e}:e}function NR(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 CR(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(My):e.map(My)}function DR(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 jR(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 MR(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function _i(e){if(Array.isArray(e))return e.map(_i);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return jR(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]=_i(o);return r}return e}function qR(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function LR(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 BR(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",OR)}var wi=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 zu()}},Pu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw zu();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 wi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){By(r,n)}throw r}}},Ru=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=AR,this.cache=new Nn(t,this.transport),this.queue=new Cn(t),this.queues=this.queue,this.documents=new Dn(this);let n=new Sr(t);this.kv=Object.assign((o="kv_default")=>new Sr(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 jn(t,o),this.vault=(o="red.vault")=>new Mn(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=CR(r);return n==null?this.client.call("query",{sql:t}).then(_i):this.client.call("query",{sql:t,params:n}).then(_i)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return ZR(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 UR(n,r.length)}tx(){return new Pu(this)}async transaction(t){if(this.inTransaction)throw zu();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 wi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){By(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return Dy(this,t)}list(){return Cy(this)}from(t){return new qn(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 zu(){return new z(jy,`${jy}: nested transactions are not supported on one connection`)}function By(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function ZR(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${qy} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function UR(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 >= ${qy} 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 Ln(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"&&FR(t.chosenOption)&&VR(t.outcome)&&KR(t.cost)}function FR(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function VR(e){return e==="success"||e==="failure"||e==="escalated"}function KR(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 HR}from"node:crypto";function Iu(e){return HR("sha256").update(e).digest("hex")}function Zy(e){return Iu(JSON.stringify(e))}function Uy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Ou="unknown",bi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Cu(t.from),i=Cu(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>WR(p,n)).filter(p=>p!=null).filter(p=>JR(p,t)).filter(p=>QR(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=ez(c,l,r),f=[Fy(null,s,u,r)];if(t.groupBy){let m=[...YR(s,t.groupBy).entries()].map(([h,_])=>Fy(h,_,u,r)).sort((h,_)=>_.total-h.total||rz(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function WR(e,t){let r=e.properties.metadata??{},n=GR(e,r,t);return n==null?null:{ts:n,platform:Au(r,"platform")??Ou,eventType:Au(r,"event_type")??Ou,target:Au(r,"target")??Ou}}function GR(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Cu(t.timestamp)??n}function Au(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function JR(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 QR(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function YR(e,t){let r=new Map;for(let n of e){let o=XR(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function XR(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Fy(e,t,r,n){let o=new Map;for(let s of t){let a=Nu(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 ez(e,t,r){if(e==null||t==null)return[];let n=[],o=Nu(e,r),i=Nu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=tz(o,r),s++;return n}function Nu(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 tz(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 Cu(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 rz(e,t){return String(e??"").localeCompare(String(t??""))}var nz=["validate","simple","complex","think"];var oz={validate:1,simple:.85,complex:.65,think:.45};function iz(){return{schemaVersion:1,buckets:{}}}function Ky(e,t={}){let r=dz(t.initial??iz());for(let n of e)sz(r,n,t);return r}function sz(e,t,r={}){let n=(r.tierForEvent??az)(t);if(!n)return e;let i=uz(e,t.taskClass).arms[n],s=cz(t,n);return i.posterior.alpha=Vy(i.posterior.alpha+s),i.posterior.beta=Vy(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 az(e){let t=e.chosenOption.kind;if(fz(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 cz(e,t){return e.outcome!=="success"?0:oz[t]}function uz(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=lz(),e.buckets[r]}function lz(){return{arms:{validate:vi(),simple:vi(),complex:vi(),think:vi()}}}function vi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function dz(e){return JSON.parse(JSON.stringify(e))}function fz(e){return nz.includes(e)}function Vy(e){return Math.round(e*1e3)/1e3}var xi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Hy={contact:"person"},$i=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],We={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Si=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 Ly(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 ${We.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${We.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${We.outcomeEvents}`)}kv(){return this.db.kv(We.kv)}async capture(t){let r=e_(t.kind??"note"),n=Date.now(),o=gz(t.tags??[]),i=Zy([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=`${Uy(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 ${We.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(Gy(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 ${We.artifacts}`);this.artifactCache=t.rows.map(pz).filter(ki)}return this.artifactCache}async search(t,r=10,n={}){let o=yz(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=r_(u,o),f=n_({...d,connections:_z(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:bz(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=t_(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 ${We.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(Jy(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 ${We.connections}`);this.connectionCache=t.rows.map(mz).filter(ki)}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:Tz(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new bi(r).events(t)}async appendOutcomeEvent(t){if(!Ln(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${We.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 ${We.outcomeEvents}`);this.outcomeEventCache=t.rows.map(hz).filter(ki).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(Qy());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return Yy(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!Yy(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(Qy(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=Ky(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!$r(i.artifact)).slice(0,r);return vz(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(Gy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Jy(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||$r(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=gy(t),i=new Set([t.rid]);for(let d of r)$r(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!$r(d.artifact)).map(d=>({artifact:gu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:gu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:hu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!yu(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 e_(e){let r=Hy[e]??e;if(xi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function t_(e){if($i.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function pz(e){let t=Number(e.red_entity_id??e.rid),r=Du(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:e_(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 mz(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:t_(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:Du(e.properties??e.PROPERTIES)}}function hz(e){let t=Number(e.red_entity_id??e.rid),r=Du(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Ln(r)?null:{rid:t,event:r}}function Du(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function ki(e){return e!=null}function gz(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function yz(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Wy(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function r_(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+Wy(r,a)*3+Wy(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 _z(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||$r(a))continue;let c=n_({...r_(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*wz(i.kind))}return Vt(o*.35)}function wz(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 n_(e){return{...e,lexical:Vt(e.lexical),tags:Vt(e.tags),kind:Vt(e.kind),connections:Vt(e.connections),vector:Vt(e.vector),total:Vt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Vt(e){return Math.round(e*1e3)/1e3}function bz(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 vz(e,t){let r=t.map(xz),n=$z(t),o=kz(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:Sz(e,r,n,o)}}function xz(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 $z(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 kz(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 Sz(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
56
+ `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${Ez(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
57
+ `)}function Ez(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(ki);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function Gy(e){return`artifact.hash.${e}`}function Jy(e,t,r){return`connection.${e}.${r}.${t}`}function Qy(){return`model-tier-bandit.v${1}`}function Yy(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function Tz(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function Pz(e=process.cwd()){let t=await by(e);if(xy(t))try{return{config:t,store:await $y(t),project:o_(t.rootDir)}}catch(n){let o=pi(t.rootDir);if(await An(o.socketPath,50))throw n}let r=await Si.open({uri:t.connectionString,autoLinker:yy()});return{config:t,store:r,project:o_(t.rootDir)}}async function _e(e,t=process.cwd()){let r=await Pz(t);try{return await e(r)}finally{await r.store.close()}}async function s_(e,t){if(e!=="SessionStart")return{};let r=await _e(async({config:o,store:i})=>(await i.status(),o)),n=i_(r.rootDir,".red","brain","sessions");return await Rz(n,{recursive:!0}),await zz(i_(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var Ei=class{map({event:t,sourceAgent:r}){return{title:Iz(t),content:Oz(t),kind:"event",tags:Az(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:a_(t),metadata:Nz(t)}}};function a_(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Iu(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function Iz(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 Oz(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
58
+ `)||JSON.stringify(e.raw)}function Az(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function Nz(e){let t={event_key:a_(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 Ti(e){let t=new Ei,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Kt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function u_(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Kt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Kt("brain_act requires a non-empty message");let o=t.connect??(a=>Ut.connect(a)),i=t.process??Cz(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Kt(`brain_act could not reach the channel bridge: ${c_(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Kt(`brain_act could not send to "${r}": ${c_(c)}`,{cause:c})}if(!a.ok)throw new Kt(`brain_act could not send to "${r}": ${Dz(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function Cz(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 Dz(e){return jz(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function jz(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 c_(e){return e instanceof Error?e.message:String(e)}import{createServer as Mz}from"node:http";async function f_(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:ju(n,"supports"),contradicts:ju(n,"contradicts"),depends_on:ju(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=>qz(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=>Lz(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 p_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:Bz(e)}}async function m_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=Mz((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
59
+ `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function qz(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:Fz(e.properties.content)}}function Lz(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 Bz(e){return`<!doctype html>
60
60
  <html lang="en">
61
61
  <head>
62
62
  <meta charset="utf-8">
@@ -248,36 +248,36 @@ ${o}`),n.join(`
248
248
  <section>
249
249
  <h2>Event KPIs</h2>
250
250
  <div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
251
- ${c_(e.kpis.events_by_platform,"Platform")}
252
- ${c_(e.kpis.events_by_type,"Event type")}
251
+ ${l_(e.kpis.events_by_platform,"Platform")}
252
+ ${l_(e.kpis.events_by_type,"Event type")}
253
253
  </section>
254
254
  <section>
255
255
  <h2>Recent Decisions</h2>
256
256
  <div class="feed">
257
- ${e.recent_decisions.length===0?u_("No decision artifacts captured yet."):e.recent_decisions.map(Mz).join("")}
257
+ ${e.recent_decisions.length===0?d_("No decision artifacts captured yet."):e.recent_decisions.map(Zz).join("")}
258
258
  </div>
259
259
  </section>
260
260
  </div>
261
261
  <section>
262
262
  <h2>Recent Connections</h2>
263
263
  <div class="feed">
264
- ${e.recent_connections.length===0?u_("No graph connections captured yet."):e.recent_connections.map(qz).join("")}
264
+ ${e.recent_connections.length===0?d_("No graph connections captured yet."):e.recent_connections.map(Uz).join("")}
265
265
  </div>
266
266
  </section>
267
267
  </main>
268
268
  <footer class="meta">${se(e.attribution.red_hermes)}</footer>
269
- <script id="brain-dashboard-data" type="application/json">${Bz(e)}</script>
269
+ <script id="brain-dashboard-data" type="application/json">${Vz(e)}</script>
270
270
  </body>
271
- </html>`}function Tr(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function c_(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function Mz(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
271
+ </html>`}function Tr(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function l_(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function Zz(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
272
272
  <h3>${se(e.title)}</h3>
273
273
  <div class="meta">#${e.rid} - ${se(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
274
274
  <p class="meta">${se(e.excerpt)}</p>
275
275
  ${r}
276
- </article>`}function qz(e){return`<article class="item">
276
+ </article>`}function Uz(e){return`<article class="item">
277
277
  <h3><span class="edge ${se(e.kind)}">${se(e.kind)}</span> ${se(e.from.title)} -> ${se(e.to.title)}</h3>
278
278
  <div class="meta">#${e.rid} - ${se(e.created_at)}${e.reason?` - ${se(e.reason)}`:""}</div>
279
- </article>`}function u_(e){return`<div class="empty">${se(e)}</div>`}function ju(e,t){return e.filter(r=>r.kind===t).length}function Lz(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function Bz(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as Zz,readFile as Uz,writeFile as Fz}from"node:fs/promises";import{dirname as Vz}from"node:path";async function p_(e){let t=await Ti({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 m_(e){try{let t=await Uz(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function h_(e,t){await Zz(Vz(e),{recursive:!0}),await Fz(e,JSON.stringify(t,null,2)+`
280
- `,"utf8")}async function Jz(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":fI();return;case"init":await _e(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await _e(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await Yz(t);return;case"search":await Xz(t);return;case"think":case"query":await eI(t);return;case"get":await tI(t);return;case"link":await rI(t);return;case"backlinks":await nI(t);return;case"act":await cI(t);return;case"hook":await uI(t);return;case"ingest-events":await iI(t);return;case"schedule-ingest":await oI(t);return;case"kpi":case"kpis":await sI(t);return;case"dashboard":await aI(t);return;case"outcome-event":await Qz(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function Qz(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=Ge(r),o=await dI(),i=JSON.parse(o);if(!Ln(i))throw new Error("invalid brain outcome event");await _e(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function Yz(e){let t=Ge(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await Kz(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await _e(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:lI(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});$e(i)})}async function Xz(e){let t=Ge(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=Bn(t,"limit")??10;await _e(async({store:o})=>$e(await o.search(r,n)))}async function eI(e){let t=Ge(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=Bn(t,"limit")??8;await _e(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function tI(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await _e(async({store:r})=>{let n=await r.getArtifact(Pi(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function rI(e){let t=Ge(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await _e(async({store:o})=>{$e(await o.link({from:Pi(r),to:Pi(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function nI(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await _e(async({store:r})=>$e(await r.backlinks(Pi(t))))}async function oI(e){let t=Ge(e),r=M(t,"session-key")??M(t,"session"),n=Bn(t,"limit"),o=await Ut.connect();try{await _e(async({config:i,store:s})=>{let a=M(t,"state")??g_(i.rootDir,".red","brain","ingestion-state.json"),c=await m_(a),l=await p_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await h_(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function iI(e){let t=Ge(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=Bn(t,"limit"),i=await Ut.connect();try{await _e(async({store:s})=>{let a=await Ti({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function sI(e){let t=Ge(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await _e(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function aI(e){let t=Ge(e),r=await _e(async({config:o,store:i,project:s})=>{let a=await l_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:d_(a),defaultOut:g_(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=Bn(t,"port")??4738,s=await f_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await Hz(Gz(n),{recursive:!0}),await Wz(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function cI(e){let t=Ge(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await a_({target:r,message:n}))}async function uI(e){let[t="SessionStart",...r]=e,n=Ge(r),o=M(n,"runner")??"unknown";$e(await o_(t,o))}function Pi(e){return/^\d+$/.test(e)?Number(e):e}function Ge(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function lI(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Bn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function dI(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function fI(){console.log(`brain commands:
279
+ </article>`}function d_(e){return`<div class="empty">${se(e)}</div>`}function ju(e,t){return e.filter(r=>r.kind===t).length}function Fz(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function Vz(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as Kz,readFile as Hz,writeFile as Wz}from"node:fs/promises";import{dirname as Gz}from"node:path";async function h_(e){let t=await Ti({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 g_(e){try{let t=await Hz(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function y_(e,t){await Kz(Gz(e),{recursive:!0}),await Wz(e,JSON.stringify(t,null,2)+`
280
+ `,"utf8")}async function eI(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":gI();return;case"init":await _e(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await _e(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await rI(t);return;case"search":await nI(t);return;case"think":case"query":await oI(t);return;case"get":await iI(t);return;case"link":await sI(t);return;case"backlinks":await aI(t);return;case"act":await fI(t);return;case"hook":await pI(t);return;case"ingest-events":await uI(t);return;case"schedule-ingest":await cI(t);return;case"kpi":case"kpis":await lI(t);return;case"dashboard":await dI(t);return;case"outcome-event":await tI(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function tI(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=Ge(r),o=await hI(),i=JSON.parse(o);if(!Ln(i))throw new Error("invalid brain outcome event");await _e(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function rI(e){let t=Ge(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await Jz(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await _e(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:mI(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});$e(i)})}async function nI(e){let t=Ge(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=Bn(t,"limit")??10;await _e(async({store:o})=>$e(await o.search(r,n)))}async function oI(e){let t=Ge(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=Bn(t,"limit")??8;await _e(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function iI(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await _e(async({store:r})=>{let n=await r.getArtifact(Pi(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function sI(e){let t=Ge(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await _e(async({store:o})=>{$e(await o.link({from:Pi(r),to:Pi(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function aI(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await _e(async({store:r})=>$e(await r.backlinks(Pi(t))))}async function cI(e){let t=Ge(e),r=M(t,"session-key")??M(t,"session"),n=Bn(t,"limit"),o=await Ut.connect();try{await _e(async({config:i,store:s})=>{let a=M(t,"state")??__(i.rootDir,".red","brain","ingestion-state.json"),c=await g_(a),l=await h_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await y_(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function uI(e){let t=Ge(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=Bn(t,"limit"),i=await Ut.connect();try{await _e(async({store:s})=>{let a=await Ti({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function lI(e){let t=Ge(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await _e(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function dI(e){let t=Ge(e),r=await _e(async({config:o,store:i,project:s})=>{let a=await f_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:p_(a),defaultOut:__(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=Bn(t,"port")??4738,s=await m_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await Qz(Xz(n),{recursive:!0}),await Yz(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function fI(e){let t=Ge(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await u_({target:r,message:n}))}async function pI(e){let[t="SessionStart",...r]=e,n=Ge(r),o=M(n,"runner")??"unknown";$e(await s_(t,o))}function Pi(e){return/^\d+$/.test(e)?Number(e):e}function Ge(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function mI(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Bn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function hI(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function gI(){console.log(`brain commands:
281
281
  init
282
282
  status
283
283
  capture [text] --title <title> --kind <${xi.join("|")}> --tag <tag>
@@ -292,4 +292,4 @@ ${o}`),n.join(`
292
292
  kpi [--interval hour|day|week|month] [--group-by platform|event_type|target] [--time-field event|ingested] [--from T] [--to T] [--platform P] [--event-type T] [--target T]
293
293
  dashboard [--out PATH] [--json] [--serve] [--host 127.0.0.1] [--port 4738]
294
294
  outcome-event record [--root PATH] < event.json
295
- `)}Jz().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
295
+ `)}eI().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});